@zorgo/next 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cli.mjs.map +1 -1
- package/dist/images.js.map +1 -1
- package/dist/images.mjs.map +1 -1
- package/dist/index.d.mts +5 -2
- package/dist/index.d.ts +5 -2
- package/dist/index.js +25 -25
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +23 -23
- package/dist/index.mjs.map +1 -1
- package/dist/item-page.js.map +1 -1
- package/dist/item-page.mjs.map +1 -1
- package/dist/server.js.map +1 -1
- package/dist/server.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
var xy=Object.create;var Rs=Object.defineProperty;var ky=Object.getOwnPropertyDescriptor;var Ty=Object.getOwnPropertyNames;var Cy=Object.getPrototypeOf,Ey=Object.prototype.hasOwnProperty;var Is=(t,e)=>()=>(t&&(e=t(t=0)),e);var ot=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Py=(t,e)=>{for(var r in e)Rs(t,r,{get:e[r],enumerable:!0})},Gc=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ty(e))!Ey.call(t,n)&&n!==r&&Rs(t,n,{get:()=>e[n],enumerable:!(o=ky(e,n))||o.enumerable});return t};var yn=(t,e,r)=>(r=t!=null?xy(Cy(t)):{},Gc(e||!t||!t.__esModule?Rs(r,"default",{value:t,enumerable:!0}):r,t)),Kc=t=>Gc(Rs({},"__esModule",{value:!0}),t);var mu=ot(fu=>{"use strict";fu.parse=Zw;fu.serialize=ev;var Gw=Object.prototype.toString,Kw=Object.prototype.hasOwnProperty,Jw=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Yw=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,Xw=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Qw=/^[\u0020-\u003A\u003D-\u007E]*$/;function Zw(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");var r={},o=t.length;if(o<2)return r;var n=e&&e.decode||tv,s=0,i=0,a=0;do{if(i=t.indexOf("=",s),i===-1)break;if(a=t.indexOf(";",s),a===-1)a=o;else if(i>a){s=t.lastIndexOf(";",i-1)+1;continue}var l=lm(t,s,i),u=um(t,i,l),c=t.slice(l,u);if(!Kw.call(r,c)){var d=lm(t,i+1,a),f=um(t,a,d);t.charCodeAt(d)===34&&t.charCodeAt(f-1)===34&&(d++,f--);var m=t.slice(d,f);r[c]=ov(m,n)}s=a+1}while(s<o);return r}function lm(t,e,r){do{var o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<r);return r}function um(t,e,r){for(;e>r;){var o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return r}function ev(t,e,r){var o=r&&r.encode||encodeURIComponent;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!Jw.test(t))throw new TypeError("argument name is invalid");var n=o(e);if(!Yw.test(n))throw new TypeError("argument val is invalid");var s=t+"="+n;if(!r)return s;if(r.maxAge!=null){var i=Math.floor(r.maxAge);if(!isFinite(i))throw new TypeError("option maxAge is invalid");s+="; Max-Age="+i}if(r.domain){if(!Xw.test(r.domain))throw new TypeError("option domain is invalid");s+="; Domain="+r.domain}if(r.path){if(!Qw.test(r.path))throw new TypeError("option path is invalid");s+="; Path="+r.path}if(r.expires){var a=r.expires;if(!rv(a)||isNaN(a.valueOf()))throw new TypeError("option expires is invalid");s+="; Expires="+a.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority){var l=typeof r.priority=="string"?r.priority.toLowerCase():r.priority;switch(l){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(r.sameSite){var u=typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite;switch(u){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return s}function tv(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}function rv(t){return Gw.call(t)==="[object Date]"}function ov(t,e){try{return e(t)}catch{return t}}});var gm=ot((pI,pm)=>{"use strict";pm.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var Sm=ot((wm,vm)=>{"use strict";var Ii=gm(),{hasOwnProperty:bm}=Object.prototype,{propertyIsEnumerable:uv}=Object,$o=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),cv=wm,ym={concatArrays:!1,ignoreUndefined:!1},Di=t=>{let e=[];for(let r in t)bm.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let o of r)uv.call(t,o)&&e.push(o)}return e};function Bo(t){return Array.isArray(t)?dv(t):Ii(t)?fv(t):t}function dv(t){let e=t.slice(0,0);return Di(t).forEach(r=>{$o(e,r,Bo(t[r]))}),e}function fv(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return Di(t).forEach(r=>{$o(e,r,Bo(t[r]))}),e}var _m=(t,e,r,o)=>(r.forEach(n=>{typeof e[n]>"u"&&o.ignoreUndefined||(n in t&&t[n]!==Object.getPrototypeOf(t)?$o(t,n,xu(t[n],e[n],o)):$o(t,n,Bo(e[n])))}),t),mv=(t,e,r)=>{let o=t.slice(0,0),n=0;return[t,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)bm.call(s,a)&&(i.push(String(a)),s===t?$o(o,n++,s[a]):$o(o,n++,Bo(s[a])));o=_m(o,s,Di(s).filter(a=>!i.includes(a)),r)}),o};function xu(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?mv(t,e,r):!Ii(e)||!Ii(t)?Bo(e):_m(t,e,Di(e),r)}vm.exports=function(...t){let e=xu(Bo(ym),this!==cv&&this||{},ym),r={_:{}};for(let o of t)if(o!==void 0){if(!Ii(o))throw new TypeError("`"+o+"` is not an Option Object");r=xu(r,{_:o},e)}return r._}});var xm,km,Tm=Is(()=>{"use strict";xm=yn(Sm(),1),km=xm.default});function pv(t,e){let r=window.localStorage.getItem(t);if(r){let o=JSON.parse(r),n=JSON.parse(e),s=JSON.stringify(hv(o,n));window.localStorage.setItem(t,s)}else window.localStorage.setItem(t,e)}function qo(t,e){return new Promise((r,o)=>{try{let n=t();e?.(null,n),r(n)}catch(n){e?.(n),o(n)}})}function Li(t,e,r){return Promise.all(t).then(o=>{let n=r?.(o)??null;return e?.(null,n),Promise.resolve(n)},o=>(e?.(o),Promise.reject(o)))}var hv,fs,Zr,ku=Is(()=>{"use strict";Tm();hv=km.bind({concatArrays:!0,ignoreUndefined:!0});fs={getItem:(t,e)=>qo(()=>window.localStorage.getItem(t),e),setItem:(t,e,r)=>qo(()=>window.localStorage.setItem(t,e),r),removeItem:(t,e)=>qo(()=>window.localStorage.removeItem(t),e),mergeItem:(t,e,r)=>qo(()=>pv(t,e),r),clear:t=>qo(()=>window.localStorage.clear(),t),getAllKeys:t=>qo(()=>{let e=window.localStorage.length,r=[];for(let o=0;o<e;o+=1){let n=window.localStorage.key(o)||"";r.push(n)}return r},t),flushGetRequests:()=>{},multiGet:(t,e)=>{let r=t.map(n=>fs.getItem(n));return Li(r,e,n=>n.map((s,i)=>[t[i],s]))},multiSet:(t,e)=>{let r=t.map(o=>fs.setItem(o[0],o[1]));return Li(r,e)},multiRemove:(t,e)=>{let r=t.map(o=>fs.removeItem(o));return Li(r,e)},multiMerge:(t,e)=>{let r=t.map(o=>fs.mergeItem(o[0],o[1]));return Li(r,e)}},Zr=fs});function Cm(t){return{getItem:(...e)=>Zr.getItem(t,...e),setItem:(...e)=>Zr.setItem(t,...e),mergeItem:(...e)=>Zr.mergeItem(t,...e),removeItem:(...e)=>Zr.removeItem(t,...e)}}var Em=Is(()=>{"use strict";ku()});var Tu={};Py(Tu,{default:()=>gv,useAsyncStorage:()=>Cm});var gv,Cu=Is(()=>{"use strict";ku();Em();gv=Zr});var ap=ot((wU,ip)=>{"use strict";ip.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var o,n,s;if(Array.isArray(e)){if(o=e.length,o!=r.length)return!1;for(n=o;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),o=s.length,o!==Object.keys(r).length)return!1;for(n=o;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=o;n--!==0;){var i=s[n];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var lc=ot((L$,Ip)=>{"use strict";Ip.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var Lp=ot((N$,Dp)=>{"use strict";Dp.exports=function(e){return!e||typeof e=="string"?!1:e instanceof Array||Array.isArray(e)||e.length>=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&e.constructor.name!=="String")}});var Mp=ot((j$,jp)=>{"use strict";var Tx=Lp(),Cx=Array.prototype.concat,Ex=Array.prototype.slice,Np=jp.exports=function(e){for(var r=[],o=0,n=e.length;o<n;o++){var s=e[o];Tx(s)?r=Cx.call(r,Ex.call(s)):r.push(s)}return r};Np.wrap=function(t){return function(){return t(Np(arguments))}}});var Bp=ot((M$,$p)=>{"use strict";var Ts=lc(),Cs=Mp(),Up=Object.hasOwnProperty,Fp=Object.create(null);for(za in Ts)Up.call(Ts,za)&&(Fp[Ts[za]]=za);var za,Xe=$p.exports={to:{},get:{}};Xe.get=function(t){var e=t.substring(0,3).toLowerCase(),r,o;switch(e){case"hsl":r=Xe.get.hsl(t),o="hsl";break;case"hwb":r=Xe.get.hwb(t),o="hwb";break;default:r=Xe.get.rgb(t),o="rgb";break}return r?{model:o,value:r}:null};Xe.get.rgb=function(t){if(!t)return null;var e=/^#([a-f0-9]{3,4})$/i,r=/^#([a-f0-9]{6})([a-f0-9]{2})?$/i,o=/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,n=/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,s=/^(\w+)$/,i=[0,0,0,1],a,l,u;if(a=t.match(r)){for(u=a[2],a=a[1],l=0;l<3;l++){var c=l*2;i[l]=parseInt(a.slice(c,c+2),16)}u&&(i[3]=parseInt(u,16)/255)}else if(a=t.match(e)){for(a=a[1],u=a[3],l=0;l<3;l++)i[l]=parseInt(a[l]+a[l],16);u&&(i[3]=parseInt(u+u,16)/255)}else if(a=t.match(o)){for(l=0;l<3;l++)i[l]=parseInt(a[l+1],0);a[4]&&(a[5]?i[3]=parseFloat(a[4])*.01:i[3]=parseFloat(a[4]))}else if(a=t.match(n)){for(l=0;l<3;l++)i[l]=Math.round(parseFloat(a[l+1])*2.55);a[4]&&(a[5]?i[3]=parseFloat(a[4])*.01:i[3]=parseFloat(a[4]))}else return(a=t.match(s))?a[1]==="transparent"?[0,0,0,0]:Up.call(Ts,a[1])?(i=Ts[a[1]],i[3]=1,i):null:null;for(l=0;l<3;l++)i[l]=Tr(i[l],0,255);return i[3]=Tr(i[3],0,1),i};Xe.get.hsl=function(t){if(!t)return null;var e=/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){var o=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=Tr(parseFloat(r[2]),0,100),i=Tr(parseFloat(r[3]),0,100),a=Tr(isNaN(o)?1:o,0,1);return[n,s,i,a]}return null};Xe.get.hwb=function(t){if(!t)return null;var e=/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){var o=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=Tr(parseFloat(r[2]),0,100),i=Tr(parseFloat(r[3]),0,100),a=Tr(isNaN(o)?1:o,0,1);return[n,s,i,a]}return null};Xe.to.hex=function(){var t=Cs(arguments);return"#"+Ga(t[0])+Ga(t[1])+Ga(t[2])+(t[3]<1?Ga(Math.round(t[3]*255)):"")};Xe.to.rgb=function(){var t=Cs(arguments);return t.length<4||t[3]===1?"rgb("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+")":"rgba("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+", "+t[3]+")"};Xe.to.rgb.percent=function(){var t=Cs(arguments),e=Math.round(t[0]/255*100),r=Math.round(t[1]/255*100),o=Math.round(t[2]/255*100);return t.length<4||t[3]===1?"rgb("+e+"%, "+r+"%, "+o+"%)":"rgba("+e+"%, "+r+"%, "+o+"%, "+t[3]+")"};Xe.to.hsl=function(){var t=Cs(arguments);return t.length<4||t[3]===1?"hsl("+t[0]+", "+t[1]+"%, "+t[2]+"%)":"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+t[3]+")"};Xe.to.hwb=function(){var t=Cs(arguments),e="";return t.length>=4&&t[3]!==1&&(e=", "+t[3]),"hwb("+t[0]+", "+t[1]+"%, "+t[2]+"%"+e+")"};Xe.to.keyword=function(t){return Fp[t.slice(0,3)]};function Tr(t,e,r){return Math.min(Math.max(e,t),r)}function Ga(t){var e=Math.round(t).toString(16).toUpperCase();return e.length<2?"0"+e:e}});var uc=ot((U$,Vp)=>{"use strict";var Es=lc(),qp={};for(let t of Object.keys(Es))qp[Es[t]]=t;var E={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};Vp.exports=E;for(let t of Object.keys(E)){if(!("channels"in E[t]))throw new Error("missing channels property: "+t);if(!("labels"in E[t]))throw new Error("missing channel labels property: "+t);if(E[t].labels.length!==E[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:r}=E[t];delete E[t].channels,delete E[t].labels,Object.defineProperty(E[t],"channels",{value:e}),Object.defineProperty(E[t],"labels",{value:r})}E.rgb.hsl=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.min(e,r,o),s=Math.max(e,r,o),i=s-n,a,l;s===n?a=0:e===s?a=(r-o)/i:r===s?a=2+(o-e)/i:o===s&&(a=4+(e-r)/i),a=Math.min(a*60,360),a<0&&(a+=360);let u=(n+s)/2;return s===n?l=0:u<=.5?l=i/(s+n):l=i/(2-s-n),[a,l*100,u*100]};E.rgb.hsv=function(t){let e,r,o,n,s,i=t[0]/255,a=t[1]/255,l=t[2]/255,u=Math.max(i,a,l),c=u-Math.min(i,a,l),d=function(f){return(u-f)/6/c+1/2};return c===0?(n=0,s=0):(s=c/u,e=d(i),r=d(a),o=d(l),i===u?n=o-r:a===u?n=1/3+e-o:l===u&&(n=2/3+r-e),n<0?n+=1:n>1&&(n-=1)),[n*360,s*100,u*100]};E.rgb.hwb=function(t){let e=t[0],r=t[1],o=t[2],n=E.rgb.hsl(t)[0],s=1/255*Math.min(e,Math.min(r,o));return o=1-1/255*Math.max(e,Math.max(r,o)),[n,s*100,o*100]};E.rgb.cmyk=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.min(1-e,1-r,1-o),s=(1-e-n)/(1-n)||0,i=(1-r-n)/(1-n)||0,a=(1-o-n)/(1-n)||0;return[s*100,i*100,a*100,n*100]};function Px(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}E.rgb.keyword=function(t){let e=qp[t];if(e)return e;let r=1/0,o;for(let n of Object.keys(Es)){let s=Es[n],i=Px(t,s);i<r&&(r=i,o=n)}return o};E.keyword.rgb=function(t){return Es[t]};E.rgb.xyz=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,o=o>.04045?((o+.055)/1.055)**2.4:o/12.92;let n=e*.4124+r*.3576+o*.1805,s=e*.2126+r*.7152+o*.0722,i=e*.0193+r*.1192+o*.9505;return[n*100,s*100,i*100]};E.rgb.lab=function(t){let e=E.rgb.xyz(t),r=e[0],o=e[1],n=e[2];r/=95.047,o/=100,n/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let s=116*o-16,i=500*(r-o),a=200*(o-n);return[s,i,a]};E.hsl.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,n,s,i;if(r===0)return i=o*255,[i,i,i];o<.5?n=o*(1+r):n=o+r-o*r;let a=2*o-n,l=[0,0,0];for(let u=0;u<3;u++)s=e+1/3*-(u-1),s<0&&s++,s>1&&s--,6*s<1?i=a+(n-a)*6*s:2*s<1?i=n:3*s<2?i=a+(n-a)*(2/3-s)*6:i=a,l[u]=i*255;return l};E.hsl.hsv=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,n=r,s=Math.max(o,.01);o*=2,r*=o<=1?o:2-o,n*=s<=1?s:2-s;let i=(o+r)/2,a=o===0?2*n/(s+n):2*r/(o+r);return[e,a*100,i*100]};E.hsv.rgb=function(t){let e=t[0]/60,r=t[1]/100,o=t[2]/100,n=Math.floor(e)%6,s=e-Math.floor(e),i=255*o*(1-r),a=255*o*(1-r*s),l=255*o*(1-r*(1-s));switch(o*=255,n){case 0:return[o,l,i];case 1:return[a,o,i];case 2:return[i,o,l];case 3:return[i,a,o];case 4:return[l,i,o];case 5:return[o,i,a]}};E.hsv.hsl=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,n=Math.max(o,.01),s,i;i=(2-r)*o;let a=(2-r)*n;return s=r*n,s/=a<=1?a:2-a,s=s||0,i/=2,[e,s*100,i*100]};E.hwb.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,n=r+o,s;n>1&&(r/=n,o/=n);let i=Math.floor(6*e),a=1-o;s=6*e-i,(i&1)!==0&&(s=1-s);let l=r+s*(a-r),u,c,d;switch(i){default:case 6:case 0:u=a,c=l,d=r;break;case 1:u=l,c=a,d=r;break;case 2:u=r,c=a,d=l;break;case 3:u=r,c=l,d=a;break;case 4:u=l,c=r,d=a;break;case 5:u=a,c=r,d=l;break}return[u*255,c*255,d*255]};E.cmyk.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,n=t[3]/100,s=1-Math.min(1,e*(1-n)+n),i=1-Math.min(1,r*(1-n)+n),a=1-Math.min(1,o*(1-n)+n);return[s*255,i*255,a*255]};E.xyz.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,n,s,i;return n=e*3.2406+r*-1.5372+o*-.4986,s=e*-.9689+r*1.8758+o*.0415,i=e*.0557+r*-.204+o*1.057,n=n>.0031308?1.055*n**(1/2.4)-.055:n*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,n=Math.min(Math.max(0,n),1),s=Math.min(Math.max(0,s),1),i=Math.min(Math.max(0,i),1),[n*255,s*255,i*255]};E.xyz.lab=function(t){let e=t[0],r=t[1],o=t[2];e/=95.047,r/=100,o/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116;let n=116*r-16,s=500*(e-r),i=200*(r-o);return[n,s,i]};E.lab.xyz=function(t){let e=t[0],r=t[1],o=t[2],n,s,i;s=(e+16)/116,n=r/500+s,i=s-o/200;let a=s**3,l=n**3,u=i**3;return s=a>.008856?a:(s-16/116)/7.787,n=l>.008856?l:(n-16/116)/7.787,i=u>.008856?u:(i-16/116)/7.787,n*=95.047,s*=100,i*=108.883,[n,s,i]};E.lab.lch=function(t){let e=t[0],r=t[1],o=t[2],n;n=Math.atan2(o,r)*360/2/Math.PI,n<0&&(n+=360);let i=Math.sqrt(r*r+o*o);return[e,i,n]};E.lch.lab=function(t){let e=t[0],r=t[1],n=t[2]/360*2*Math.PI,s=r*Math.cos(n),i=r*Math.sin(n);return[e,s,i]};E.rgb.ansi16=function(t,e=null){let[r,o,n]=t,s=e===null?E.rgb.hsv(t)[2]:e;if(s=Math.round(s/50),s===0)return 30;let i=30+(Math.round(n/255)<<2|Math.round(o/255)<<1|Math.round(r/255));return s===2&&(i+=60),i};E.hsv.ansi16=function(t){return E.rgb.ansi16(E.hsv.rgb(t),t[2])};E.rgb.ansi256=function(t){let e=t[0],r=t[1],o=t[2];return e===r&&r===o?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(o/255*5)};E.ansi16.rgb=function(t){let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let r=(~~(t>50)+1)*.5,o=(e&1)*r*255,n=(e>>1&1)*r*255,s=(e>>2&1)*r*255;return[o,n,s]};E.ansi256.rgb=function(t){if(t>=232){let s=(t-232)*10+8;return[s,s,s]}t-=16;let e,r=Math.floor(t/36)/5*255,o=Math.floor((e=t%36)/6)/5*255,n=e%6/5*255;return[r,o,n]};E.rgb.hex=function(t){let r=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return"000000".substring(r.length)+r};E.hex.rgb=function(t){let e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let r=e[0];e[0].length===3&&(r=r.split("").map(a=>a+a).join(""));let o=parseInt(r,16),n=o>>16&255,s=o>>8&255,i=o&255;return[n,s,i]};E.rgb.hcg=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.max(Math.max(e,r),o),s=Math.min(Math.min(e,r),o),i=n-s,a,l;return i<1?a=s/(1-i):a=0,i<=0?l=0:n===e?l=(r-o)/i%6:n===r?l=2+(o-e)/i:l=4+(e-r)/i,l/=6,l%=1,[l*360,i*100,a*100]};E.hsl.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=r<.5?2*e*r:2*e*(1-r),n=0;return o<1&&(n=(r-.5*o)/(1-o)),[t[0],o*100,n*100]};E.hsv.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=e*r,n=0;return o<1&&(n=(r-o)/(1-o)),[t[0],o*100,n*100]};E.hcg.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100;if(r===0)return[o*255,o*255,o*255];let n=[0,0,0],s=e%1*6,i=s%1,a=1-i,l=0;switch(Math.floor(s)){case 0:n[0]=1,n[1]=i,n[2]=0;break;case 1:n[0]=a,n[1]=1,n[2]=0;break;case 2:n[0]=0,n[1]=1,n[2]=i;break;case 3:n[0]=0,n[1]=a,n[2]=1;break;case 4:n[0]=i,n[1]=0,n[2]=1;break;default:n[0]=1,n[1]=0,n[2]=a}return l=(1-r)*o,[(r*n[0]+l)*255,(r*n[1]+l)*255,(r*n[2]+l)*255]};E.hcg.hsv=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e),n=0;return o>0&&(n=e/o),[t[0],n*100,o*100]};E.hcg.hsl=function(t){let e=t[1]/100,o=t[2]/100*(1-e)+.5*e,n=0;return o>0&&o<.5?n=e/(2*o):o>=.5&&o<1&&(n=e/(2*(1-o))),[t[0],n*100,o*100]};E.hcg.hwb=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e);return[t[0],(o-e)*100,(1-o)*100]};E.hwb.hcg=function(t){let e=t[1]/100,o=1-t[2]/100,n=o-e,s=0;return n<1&&(s=(o-n)/(1-n)),[t[0],n*100,s*100]};E.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};E.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};E.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};E.gray.hsl=function(t){return[0,0,t[0]]};E.gray.hsv=E.gray.hsl;E.gray.hwb=function(t){return[0,100,t[0]]};E.gray.cmyk=function(t){return[0,0,0,t[0]]};E.gray.lab=function(t){return[t[0],0,0]};E.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,o=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(o.length)+o};E.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var Hp=ot((F$,Wp)=>{"use strict";var Ka=uc();function Ox(){let t={},e=Object.keys(Ka);for(let r=e.length,o=0;o<r;o++)t[e[o]]={distance:-1,parent:null};return t}function Ax(t){let e=Ox(),r=[t];for(e[t].distance=0;r.length;){let o=r.pop(),n=Object.keys(Ka[o]);for(let s=n.length,i=0;i<s;i++){let a=n[i],l=e[a];l.distance===-1&&(l.distance=e[o].distance+1,l.parent=o,r.unshift(a))}}return e}function Rx(t,e){return function(r){return e(t(r))}}function Ix(t,e){let r=[e[t].parent,t],o=Ka[e[t].parent][t],n=e[t].parent;for(;e[n].parent;)r.unshift(e[n].parent),o=Rx(Ka[e[n].parent][n],o),n=e[n].parent;return o.conversion=r,o}Wp.exports=function(t){let e=Ax(t),r={},o=Object.keys(e);for(let n=o.length,s=0;s<n;s++){let i=o[s];e[i].parent!==null&&(r[i]=Ix(i,e))}return r}});var Gp=ot(($$,zp)=>{"use strict";var cc=uc(),Dx=Hp(),rn={},Lx=Object.keys(cc);function Nx(t){let e=function(...r){let o=r[0];return o==null?o:(o.length>1&&(r=o),t(r))};return"conversion"in t&&(e.conversion=t.conversion),e}function jx(t){let e=function(...r){let o=r[0];if(o==null)return o;o.length>1&&(r=o);let n=t(r);if(typeof n=="object")for(let s=n.length,i=0;i<s;i++)n[i]=Math.round(n[i]);return n};return"conversion"in t&&(e.conversion=t.conversion),e}Lx.forEach(t=>{rn[t]={},Object.defineProperty(rn[t],"channels",{value:cc[t].channels}),Object.defineProperty(rn[t],"labels",{value:cc[t].labels});let e=Dx(t);Object.keys(e).forEach(o=>{let n=e[o];rn[t][o]=jx(n),rn[t][o].raw=Nx(n)})});zp.exports=rn});var Yp=ot((B$,Jp)=>{"use strict";var on=Bp(),Qe=Gp(),Kp=["keyword","gray","hex"],dc={};for(let t of Object.keys(Qe))dc[[...Qe[t].labels].sort().join("")]=t;var Ja={};function Ee(t,e){if(!(this instanceof Ee))return new Ee(t,e);if(e&&e in Kp&&(e=null),e&&!(e in Qe))throw new Error("Unknown model: "+e);let r,o;if(t==null)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(t instanceof Ee)this.model=t.model,this.color=[...t.color],this.valpha=t.valpha;else if(typeof t=="string"){let n=on.get(t);if(n===null)throw new Error("Unable to parse color from string: "+t);this.model=n.model,o=Qe[this.model].channels,this.color=n.value.slice(0,o),this.valpha=typeof n.value[o]=="number"?n.value[o]:1}else if(t.length>0){this.model=e||"rgb",o=Qe[this.model].channels;let n=Array.prototype.slice.call(t,0,o);this.color=fc(n,o),this.valpha=typeof t[o]=="number"?t[o]:1}else if(typeof t=="number")this.model="rgb",this.color=[t>>16&255,t>>8&255,t&255],this.valpha=1;else{this.valpha=1;let n=Object.keys(t);"alpha"in t&&(n.splice(n.indexOf("alpha"),1),this.valpha=typeof t.alpha=="number"?t.alpha:0);let s=n.sort().join("");if(!(s in dc))throw new Error("Unable to parse color from object: "+JSON.stringify(t));this.model=dc[s];let{labels:i}=Qe[this.model],a=[];for(r=0;r<i.length;r++)a.push(t[i[r]]);this.color=fc(a)}if(Ja[this.model])for(o=Qe[this.model].channels,r=0;r<o;r++){let n=Ja[this.model][r];n&&(this.color[r]=n(this.color[r]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}Ee.prototype={toString(){return this.string()},toJSON(){return this[this.model]()},string(t){let e=this.model in on.to?this:this.rgb();e=e.round(typeof t=="number"?t:1);let r=e.valpha===1?e.color:[...e.color,this.valpha];return on.to[e.model](r)},percentString(t){let e=this.rgb().round(typeof t=="number"?t:1),r=e.valpha===1?e.color:[...e.color,this.valpha];return on.to.rgb.percent(r)},array(){return this.valpha===1?[...this.color]:[...this.color,this.valpha]},object(){let t={},{channels:e}=Qe[this.model],{labels:r}=Qe[this.model];for(let o=0;o<e;o++)t[r[o]]=this.color[o];return this.valpha!==1&&(t.alpha=this.valpha),t},unitArray(){let t=this.rgb().color;return t[0]/=255,t[1]/=255,t[2]/=255,this.valpha!==1&&t.push(this.valpha),t},unitObject(){let t=this.rgb().object();return t.r/=255,t.g/=255,t.b/=255,this.valpha!==1&&(t.alpha=this.valpha),t},round(t){return t=Math.max(t||0,0),new Ee([...this.color.map(Ux(t)),this.valpha],this.model)},alpha(t){return t!==void 0?new Ee([...this.color,Math.max(0,Math.min(1,t))],this.model):this.valpha},red:de("rgb",0,Se(255)),green:de("rgb",1,Se(255)),blue:de("rgb",2,Se(255)),hue:de(["hsl","hsv","hsl","hwb","hcg"],0,t=>(t%360+360)%360),saturationl:de("hsl",1,Se(100)),lightness:de("hsl",2,Se(100)),saturationv:de("hsv",1,Se(100)),value:de("hsv",2,Se(100)),chroma:de("hcg",1,Se(100)),gray:de("hcg",2,Se(100)),white:de("hwb",1,Se(100)),wblack:de("hwb",2,Se(100)),cyan:de("cmyk",0,Se(100)),magenta:de("cmyk",1,Se(100)),yellow:de("cmyk",2,Se(100)),black:de("cmyk",3,Se(100)),x:de("xyz",0,Se(95.047)),y:de("xyz",1,Se(100)),z:de("xyz",2,Se(108.833)),l:de("lab",0,Se(100)),a:de("lab",1),b:de("lab",2),keyword(t){return t!==void 0?new Ee(t):Qe[this.model].keyword(this.color)},hex(t){return t!==void 0?new Ee(t):on.to.hex(this.rgb().round().color)},hexa(t){if(t!==void 0)return new Ee(t);let e=this.rgb().round().color,r=Math.round(this.valpha*255).toString(16).toUpperCase();return r.length===1&&(r="0"+r),on.to.hex(e)+r},rgbNumber(){let t=this.rgb().color;return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255},luminosity(){let t=this.rgb().color,e=[];for(let[r,o]of t.entries()){let n=o/255;e[r]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return .2126*e[0]+.7152*e[1]+.0722*e[2]},contrast(t){let e=this.luminosity(),r=t.luminosity();return e>r?(e+.05)/(r+.05):(r+.05)/(e+.05)},level(t){let e=this.contrast(t);return e>=7?"AAA":e>=4.5?"AA":""},isDark(){let t=this.rgb().color;return(t[0]*2126+t[1]*7152+t[2]*722)/1e4<128},isLight(){return!this.isDark()},negate(){let t=this.rgb();for(let e=0;e<3;e++)t.color[e]=255-t.color[e];return t},lighten(t){let e=this.hsl();return e.color[2]+=e.color[2]*t,e},darken(t){let e=this.hsl();return e.color[2]-=e.color[2]*t,e},saturate(t){let e=this.hsl();return e.color[1]+=e.color[1]*t,e},desaturate(t){let e=this.hsl();return e.color[1]-=e.color[1]*t,e},whiten(t){let e=this.hwb();return e.color[1]+=e.color[1]*t,e},blacken(t){let e=this.hwb();return e.color[2]+=e.color[2]*t,e},grayscale(){let t=this.rgb().color,e=t[0]*.3+t[1]*.59+t[2]*.11;return Ee.rgb(e,e,e)},fade(t){return this.alpha(this.valpha-this.valpha*t)},opaquer(t){return this.alpha(this.valpha+this.valpha*t)},rotate(t){let e=this.hsl(),r=e.color[0];return r=(r+t)%360,r=r<0?360+r:r,e.color[0]=r,e},mix(t,e){if(!t||!t.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof t);let r=t.rgb(),o=this.rgb(),n=e===void 0?.5:e,s=2*n-1,i=r.alpha()-o.alpha(),a=((s*i===-1?s:(s+i)/(1+s*i))+1)/2,l=1-a;return Ee.rgb(a*r.red()+l*o.red(),a*r.green()+l*o.green(),a*r.blue()+l*o.blue(),r.alpha()*n+o.alpha()*(1-n))}};for(let t of Object.keys(Qe)){if(Kp.includes(t))continue;let{channels:e}=Qe[t];Ee.prototype[t]=function(...r){return this.model===t?new Ee(this):r.length>0?new Ee(r,t):new Ee([...Fx(Qe[this.model][t].raw(this.color)),this.valpha],t)},Ee[t]=function(...r){let o=r[0];return typeof o=="number"&&(o=fc(r,e)),new Ee(o,t)}}function Mx(t,e){return Number(t.toFixed(e))}function Ux(t){return function(e){return Mx(e,t)}}function de(t,e,r){t=Array.isArray(t)?t:[t];for(let o of t)(Ja[o]||(Ja[o]=[]))[e]=r;return t=t[0],function(o){let n;return o!==void 0?(r&&(o=r(o)),n=this[t](),n.color[e]=o,n):(n=this[t]().color[e],r&&(n=r(n)),n)}}function Se(t){return function(e){return Math.max(0,Math.min(t,e))}}function Fx(t){return Array.isArray(t)?t:[t]}function fc(t,e){for(let r=0;r<e;r++)typeof t[r]!="number"&&(t[r]=0);return t}Jp.exports=Ee});import{usePathname as TC}from"next/navigation";import{useCallback as Cr,useEffect as lr,useMemo as Ze,useRef as ar,useState as Er}from"react";import{create as NS}from"zustand";function Be(t,e){var r={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,o=Object.getOwnPropertySymbols(t);n<o.length;n++)e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(r[o[n]]=t[o[n]]);return r}function Ds(t,e,r,o){function n(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(c){try{u(o.next(c))}catch(d){i(d)}}function l(c){try{u(o.throw(c))}catch(d){i(d)}}function u(c){c.done?s(c.value):n(c.value).then(a,l)}u((o=o.apply(t,e||[])).next())})}var Jc=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var mo=class extends Error{constructor(e,r="FunctionsError",o){super(e),this.name=r,this.context=o}},bn=class extends mo{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},ho=class extends mo{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},po=class extends mo{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},_n;(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"})(_n||(_n={}));var wn=class{constructor(e,{headers:r={},customFetch:o,region:n=_n.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=Jc(o)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Ds(this,arguments,void 0,function*(r,o={}){var n;let s,i;try{let{headers:a,method:l,body:u,signal:c,timeout:d}=o,f={},{region:m}=o;m||(m=this.region);let h=new URL(`${this.url}/${r}`);m&&m!=="any"&&(f["x-region"]=m,h.searchParams.set("forceFunctionRegion",m));let g;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=u):typeof u=="string"?(f["Content-Type"]="text/plain",g=u):typeof FormData<"u"&&u instanceof FormData?g=u:(f["Content-Type"]="application/json",g=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?g=JSON.stringify(u):g=u;let y=c;d&&(i=new AbortController,s=setTimeout(()=>i.abort(),d),c?(y=i.signal,c.addEventListener("abort",()=>i.abort())):y=i.signal);let p=yield this.fetch(h.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:y}).catch(L=>{throw new bn(L)}),b=p.headers.get("x-relay-error");if(b&&b==="true")throw new ho(p);if(!p.ok)throw new po(p);let _=((n=p.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),v;return _==="application/json"?v=yield p.json():_==="application/octet-stream"||_==="application/pdf"?v=yield p.blob():_==="text/event-stream"?v=p:_==="multipart/form-data"?v=yield p.formData():v=yield p.text(),{data:v,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof po||a instanceof ho?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var Qc=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Oy=class{constructor(t){var e,r,o;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=(o=t.urlLengthLimit)!==null&&o!==void 0?o: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 o=this.fetch,n=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let i=null,a=null,l=null,u=s.status,c=s.statusText;if(s.ok){var d,f;if(r.method!=="HEAD"){var m;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let h=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(f=s.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");h&&g&&g.length>1&&(l=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(i={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,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let h=await s.text();try{i=JSON.parse(h),Array.isArray(i)&&s.status===404&&(a=[],i=null,u=200,c="OK")}catch{s.status===404&&h===""?(u=204,c="No Content"):i={message:h}}if(i&&r.shouldThrowOnError)throw new Qc(i)}return{error:i,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(n=n.catch(s=>{var i;let a="",l="",u="",c=s?.cause;if(c){var d,f,m,h;let p=(d=c?.message)!==null&&d!==void 0?d:"",b=(f=c?.code)!==null&&f!==void 0?f:"";a=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,a+=`
|
|
2
|
+
var xy=Object.create;var Rs=Object.defineProperty;var ky=Object.getOwnPropertyDescriptor;var Ty=Object.getOwnPropertyNames;var Cy=Object.getPrototypeOf,Ey=Object.prototype.hasOwnProperty;var Is=(t,e)=>()=>(t&&(e=t(t=0)),e);var ot=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Py=(t,e)=>{for(var r in e)Rs(t,r,{get:e[r],enumerable:!0})},Jc=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ty(e))!Ey.call(t,n)&&n!==r&&Rs(t,n,{get:()=>e[n],enumerable:!(o=ky(e,n))||o.enumerable});return t};var yn=(t,e,r)=>(r=t!=null?xy(Cy(t)):{},Jc(e||!t||!t.__esModule?Rs(r,"default",{value:t,enumerable:!0}):r,t)),Yc=t=>Jc(Rs({},"__esModule",{value:!0}),t);var pu=ot(hu=>{"use strict";hu.parse=Zw;hu.serialize=ev;var Gw=Object.prototype.toString,Kw=Object.prototype.hasOwnProperty,Jw=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Yw=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,Xw=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Qw=/^[\u0020-\u003A\u003D-\u007E]*$/;function Zw(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");var r={},o=t.length;if(o<2)return r;var n=e&&e.decode||tv,s=0,i=0,a=0;do{if(i=t.indexOf("=",s),i===-1)break;if(a=t.indexOf(";",s),a===-1)a=o;else if(i>a){s=t.lastIndexOf(";",i-1)+1;continue}var l=cm(t,s,i),u=dm(t,i,l),c=t.slice(l,u);if(!Kw.call(r,c)){var d=cm(t,i+1,a),f=dm(t,a,d);t.charCodeAt(d)===34&&t.charCodeAt(f-1)===34&&(d++,f--);var m=t.slice(d,f);r[c]=ov(m,n)}s=a+1}while(s<o);return r}function cm(t,e,r){do{var o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<r);return r}function dm(t,e,r){for(;e>r;){var o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return r}function ev(t,e,r){var o=r&&r.encode||encodeURIComponent;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!Jw.test(t))throw new TypeError("argument name is invalid");var n=o(e);if(!Yw.test(n))throw new TypeError("argument val is invalid");var s=t+"="+n;if(!r)return s;if(r.maxAge!=null){var i=Math.floor(r.maxAge);if(!isFinite(i))throw new TypeError("option maxAge is invalid");s+="; Max-Age="+i}if(r.domain){if(!Xw.test(r.domain))throw new TypeError("option domain is invalid");s+="; Domain="+r.domain}if(r.path){if(!Qw.test(r.path))throw new TypeError("option path is invalid");s+="; Path="+r.path}if(r.expires){var a=r.expires;if(!rv(a)||isNaN(a.valueOf()))throw new TypeError("option expires is invalid");s+="; Expires="+a.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority){var l=typeof r.priority=="string"?r.priority.toLowerCase():r.priority;switch(l){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(r.sameSite){var u=typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite;switch(u){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return s}function tv(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}function rv(t){return Gw.call(t)==="[object Date]"}function ov(t,e){try{return e(t)}catch{return t}}});var bm=ot((pI,ym)=>{"use strict";ym.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var km=ot((Sm,xm)=>{"use strict";var Ii=bm(),{hasOwnProperty:wm}=Object.prototype,{propertyIsEnumerable:uv}=Object,$o=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),cv=Sm,_m={concatArrays:!1,ignoreUndefined:!1},Di=t=>{let e=[];for(let r in t)wm.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let o of r)uv.call(t,o)&&e.push(o)}return e};function Bo(t){return Array.isArray(t)?dv(t):Ii(t)?fv(t):t}function dv(t){let e=t.slice(0,0);return Di(t).forEach(r=>{$o(e,r,Bo(t[r]))}),e}function fv(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return Di(t).forEach(r=>{$o(e,r,Bo(t[r]))}),e}var vm=(t,e,r,o)=>(r.forEach(n=>{typeof e[n]>"u"&&o.ignoreUndefined||(n in t&&t[n]!==Object.getPrototypeOf(t)?$o(t,n,Tu(t[n],e[n],o)):$o(t,n,Bo(e[n])))}),t),mv=(t,e,r)=>{let o=t.slice(0,0),n=0;return[t,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)wm.call(s,a)&&(i.push(String(a)),s===t?$o(o,n++,s[a]):$o(o,n++,Bo(s[a])));o=vm(o,s,Di(s).filter(a=>!i.includes(a)),r)}),o};function Tu(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?mv(t,e,r):!Ii(e)||!Ii(t)?Bo(e):vm(t,e,Di(e),r)}xm.exports=function(...t){let e=Tu(Bo(_m),this!==cv&&this||{},_m),r={_:{}};for(let o of t)if(o!==void 0){if(!Ii(o))throw new TypeError("`"+o+"` is not an Option Object");r=Tu(r,{_:o},e)}return r._}});var Tm,Cm,Em=Is(()=>{"use strict";Tm=yn(km(),1),Cm=Tm.default});function pv(t,e){let r=window.localStorage.getItem(t);if(r){let o=JSON.parse(r),n=JSON.parse(e),s=JSON.stringify(hv(o,n));window.localStorage.setItem(t,s)}else window.localStorage.setItem(t,e)}function qo(t,e){return new Promise((r,o)=>{try{let n=t();e?.(null,n),r(n)}catch(n){e?.(n),o(n)}})}function Li(t,e,r){return Promise.all(t).then(o=>{let n=r?.(o)??null;return e?.(null,n),Promise.resolve(n)},o=>(e?.(o),Promise.reject(o)))}var hv,fs,Zr,Cu=Is(()=>{"use strict";Em();hv=Cm.bind({concatArrays:!0,ignoreUndefined:!0});fs={getItem:(t,e)=>qo(()=>window.localStorage.getItem(t),e),setItem:(t,e,r)=>qo(()=>window.localStorage.setItem(t,e),r),removeItem:(t,e)=>qo(()=>window.localStorage.removeItem(t),e),mergeItem:(t,e,r)=>qo(()=>pv(t,e),r),clear:t=>qo(()=>window.localStorage.clear(),t),getAllKeys:t=>qo(()=>{let e=window.localStorage.length,r=[];for(let o=0;o<e;o+=1){let n=window.localStorage.key(o)||"";r.push(n)}return r},t),flushGetRequests:()=>{},multiGet:(t,e)=>{let r=t.map(n=>fs.getItem(n));return Li(r,e,n=>n.map((s,i)=>[t[i],s]))},multiSet:(t,e)=>{let r=t.map(o=>fs.setItem(o[0],o[1]));return Li(r,e)},multiRemove:(t,e)=>{let r=t.map(o=>fs.removeItem(o));return Li(r,e)},multiMerge:(t,e)=>{let r=t.map(o=>fs.mergeItem(o[0],o[1]));return Li(r,e)}},Zr=fs});function Pm(t){return{getItem:(...e)=>Zr.getItem(t,...e),setItem:(...e)=>Zr.setItem(t,...e),mergeItem:(...e)=>Zr.mergeItem(t,...e),removeItem:(...e)=>Zr.removeItem(t,...e)}}var Om=Is(()=>{"use strict";Cu()});var Eu={};Py(Eu,{default:()=>gv,useAsyncStorage:()=>Pm});var gv,Pu=Is(()=>{"use strict";Cu();Om();gv=Zr});var up=ot((wU,lp)=>{"use strict";lp.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var o,n,s;if(Array.isArray(e)){if(o=e.length,o!=r.length)return!1;for(n=o;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),o=s.length,o!==Object.keys(r).length)return!1;for(n=o;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=o;n--!==0;){var i=s[n];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var cc=ot((L$,Lp)=>{"use strict";Lp.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var jp=ot((N$,Np)=>{"use strict";Np.exports=function(e){return!e||typeof e=="string"?!1:e instanceof Array||Array.isArray(e)||e.length>=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&e.constructor.name!=="String")}});var Fp=ot((j$,Up)=>{"use strict";var Tx=jp(),Cx=Array.prototype.concat,Ex=Array.prototype.slice,Mp=Up.exports=function(e){for(var r=[],o=0,n=e.length;o<n;o++){var s=e[o];Tx(s)?r=Cx.call(r,Ex.call(s)):r.push(s)}return r};Mp.wrap=function(t){return function(){return t(Mp(arguments))}}});var Vp=ot((M$,qp)=>{"use strict";var Ts=cc(),Cs=Fp(),$p=Object.hasOwnProperty,Bp=Object.create(null);for(Ka in Ts)$p.call(Ts,Ka)&&(Bp[Ts[Ka]]=Ka);var Ka,Xe=qp.exports={to:{},get:{}};Xe.get=function(t){var e=t.substring(0,3).toLowerCase(),r,o;switch(e){case"hsl":r=Xe.get.hsl(t),o="hsl";break;case"hwb":r=Xe.get.hwb(t),o="hwb";break;default:r=Xe.get.rgb(t),o="rgb";break}return r?{model:o,value:r}:null};Xe.get.rgb=function(t){if(!t)return null;var e=/^#([a-f0-9]{3,4})$/i,r=/^#([a-f0-9]{6})([a-f0-9]{2})?$/i,o=/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,n=/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,s=/^(\w+)$/,i=[0,0,0,1],a,l,u;if(a=t.match(r)){for(u=a[2],a=a[1],l=0;l<3;l++){var c=l*2;i[l]=parseInt(a.slice(c,c+2),16)}u&&(i[3]=parseInt(u,16)/255)}else if(a=t.match(e)){for(a=a[1],u=a[3],l=0;l<3;l++)i[l]=parseInt(a[l]+a[l],16);u&&(i[3]=parseInt(u+u,16)/255)}else if(a=t.match(o)){for(l=0;l<3;l++)i[l]=parseInt(a[l+1],0);a[4]&&(a[5]?i[3]=parseFloat(a[4])*.01:i[3]=parseFloat(a[4]))}else if(a=t.match(n)){for(l=0;l<3;l++)i[l]=Math.round(parseFloat(a[l+1])*2.55);a[4]&&(a[5]?i[3]=parseFloat(a[4])*.01:i[3]=parseFloat(a[4]))}else return(a=t.match(s))?a[1]==="transparent"?[0,0,0,0]:$p.call(Ts,a[1])?(i=Ts[a[1]],i[3]=1,i):null:null;for(l=0;l<3;l++)i[l]=Tr(i[l],0,255);return i[3]=Tr(i[3],0,1),i};Xe.get.hsl=function(t){if(!t)return null;var e=/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){var o=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=Tr(parseFloat(r[2]),0,100),i=Tr(parseFloat(r[3]),0,100),a=Tr(isNaN(o)?1:o,0,1);return[n,s,i,a]}return null};Xe.get.hwb=function(t){if(!t)return null;var e=/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){var o=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=Tr(parseFloat(r[2]),0,100),i=Tr(parseFloat(r[3]),0,100),a=Tr(isNaN(o)?1:o,0,1);return[n,s,i,a]}return null};Xe.to.hex=function(){var t=Cs(arguments);return"#"+Ja(t[0])+Ja(t[1])+Ja(t[2])+(t[3]<1?Ja(Math.round(t[3]*255)):"")};Xe.to.rgb=function(){var t=Cs(arguments);return t.length<4||t[3]===1?"rgb("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+")":"rgba("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+", "+t[3]+")"};Xe.to.rgb.percent=function(){var t=Cs(arguments),e=Math.round(t[0]/255*100),r=Math.round(t[1]/255*100),o=Math.round(t[2]/255*100);return t.length<4||t[3]===1?"rgb("+e+"%, "+r+"%, "+o+"%)":"rgba("+e+"%, "+r+"%, "+o+"%, "+t[3]+")"};Xe.to.hsl=function(){var t=Cs(arguments);return t.length<4||t[3]===1?"hsl("+t[0]+", "+t[1]+"%, "+t[2]+"%)":"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+t[3]+")"};Xe.to.hwb=function(){var t=Cs(arguments),e="";return t.length>=4&&t[3]!==1&&(e=", "+t[3]),"hwb("+t[0]+", "+t[1]+"%, "+t[2]+"%"+e+")"};Xe.to.keyword=function(t){return Bp[t.slice(0,3)]};function Tr(t,e,r){return Math.min(Math.max(e,t),r)}function Ja(t){var e=Math.round(t).toString(16).toUpperCase();return e.length<2?"0"+e:e}});var dc=ot((U$,Hp)=>{"use strict";var Es=cc(),Wp={};for(let t of Object.keys(Es))Wp[Es[t]]=t;var E={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};Hp.exports=E;for(let t of Object.keys(E)){if(!("channels"in E[t]))throw new Error("missing channels property: "+t);if(!("labels"in E[t]))throw new Error("missing channel labels property: "+t);if(E[t].labels.length!==E[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:r}=E[t];delete E[t].channels,delete E[t].labels,Object.defineProperty(E[t],"channels",{value:e}),Object.defineProperty(E[t],"labels",{value:r})}E.rgb.hsl=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.min(e,r,o),s=Math.max(e,r,o),i=s-n,a,l;s===n?a=0:e===s?a=(r-o)/i:r===s?a=2+(o-e)/i:o===s&&(a=4+(e-r)/i),a=Math.min(a*60,360),a<0&&(a+=360);let u=(n+s)/2;return s===n?l=0:u<=.5?l=i/(s+n):l=i/(2-s-n),[a,l*100,u*100]};E.rgb.hsv=function(t){let e,r,o,n,s,i=t[0]/255,a=t[1]/255,l=t[2]/255,u=Math.max(i,a,l),c=u-Math.min(i,a,l),d=function(f){return(u-f)/6/c+1/2};return c===0?(n=0,s=0):(s=c/u,e=d(i),r=d(a),o=d(l),i===u?n=o-r:a===u?n=1/3+e-o:l===u&&(n=2/3+r-e),n<0?n+=1:n>1&&(n-=1)),[n*360,s*100,u*100]};E.rgb.hwb=function(t){let e=t[0],r=t[1],o=t[2],n=E.rgb.hsl(t)[0],s=1/255*Math.min(e,Math.min(r,o));return o=1-1/255*Math.max(e,Math.max(r,o)),[n,s*100,o*100]};E.rgb.cmyk=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.min(1-e,1-r,1-o),s=(1-e-n)/(1-n)||0,i=(1-r-n)/(1-n)||0,a=(1-o-n)/(1-n)||0;return[s*100,i*100,a*100,n*100]};function Px(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}E.rgb.keyword=function(t){let e=Wp[t];if(e)return e;let r=1/0,o;for(let n of Object.keys(Es)){let s=Es[n],i=Px(t,s);i<r&&(r=i,o=n)}return o};E.keyword.rgb=function(t){return Es[t]};E.rgb.xyz=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,o=o>.04045?((o+.055)/1.055)**2.4:o/12.92;let n=e*.4124+r*.3576+o*.1805,s=e*.2126+r*.7152+o*.0722,i=e*.0193+r*.1192+o*.9505;return[n*100,s*100,i*100]};E.rgb.lab=function(t){let e=E.rgb.xyz(t),r=e[0],o=e[1],n=e[2];r/=95.047,o/=100,n/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let s=116*o-16,i=500*(r-o),a=200*(o-n);return[s,i,a]};E.hsl.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,n,s,i;if(r===0)return i=o*255,[i,i,i];o<.5?n=o*(1+r):n=o+r-o*r;let a=2*o-n,l=[0,0,0];for(let u=0;u<3;u++)s=e+1/3*-(u-1),s<0&&s++,s>1&&s--,6*s<1?i=a+(n-a)*6*s:2*s<1?i=n:3*s<2?i=a+(n-a)*(2/3-s)*6:i=a,l[u]=i*255;return l};E.hsl.hsv=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,n=r,s=Math.max(o,.01);o*=2,r*=o<=1?o:2-o,n*=s<=1?s:2-s;let i=(o+r)/2,a=o===0?2*n/(s+n):2*r/(o+r);return[e,a*100,i*100]};E.hsv.rgb=function(t){let e=t[0]/60,r=t[1]/100,o=t[2]/100,n=Math.floor(e)%6,s=e-Math.floor(e),i=255*o*(1-r),a=255*o*(1-r*s),l=255*o*(1-r*(1-s));switch(o*=255,n){case 0:return[o,l,i];case 1:return[a,o,i];case 2:return[i,o,l];case 3:return[i,a,o];case 4:return[l,i,o];case 5:return[o,i,a]}};E.hsv.hsl=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,n=Math.max(o,.01),s,i;i=(2-r)*o;let a=(2-r)*n;return s=r*n,s/=a<=1?a:2-a,s=s||0,i/=2,[e,s*100,i*100]};E.hwb.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,n=r+o,s;n>1&&(r/=n,o/=n);let i=Math.floor(6*e),a=1-o;s=6*e-i,(i&1)!==0&&(s=1-s);let l=r+s*(a-r),u,c,d;switch(i){default:case 6:case 0:u=a,c=l,d=r;break;case 1:u=l,c=a,d=r;break;case 2:u=r,c=a,d=l;break;case 3:u=r,c=l,d=a;break;case 4:u=l,c=r,d=a;break;case 5:u=a,c=r,d=l;break}return[u*255,c*255,d*255]};E.cmyk.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,n=t[3]/100,s=1-Math.min(1,e*(1-n)+n),i=1-Math.min(1,r*(1-n)+n),a=1-Math.min(1,o*(1-n)+n);return[s*255,i*255,a*255]};E.xyz.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,n,s,i;return n=e*3.2406+r*-1.5372+o*-.4986,s=e*-.9689+r*1.8758+o*.0415,i=e*.0557+r*-.204+o*1.057,n=n>.0031308?1.055*n**(1/2.4)-.055:n*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,n=Math.min(Math.max(0,n),1),s=Math.min(Math.max(0,s),1),i=Math.min(Math.max(0,i),1),[n*255,s*255,i*255]};E.xyz.lab=function(t){let e=t[0],r=t[1],o=t[2];e/=95.047,r/=100,o/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116;let n=116*r-16,s=500*(e-r),i=200*(r-o);return[n,s,i]};E.lab.xyz=function(t){let e=t[0],r=t[1],o=t[2],n,s,i;s=(e+16)/116,n=r/500+s,i=s-o/200;let a=s**3,l=n**3,u=i**3;return s=a>.008856?a:(s-16/116)/7.787,n=l>.008856?l:(n-16/116)/7.787,i=u>.008856?u:(i-16/116)/7.787,n*=95.047,s*=100,i*=108.883,[n,s,i]};E.lab.lch=function(t){let e=t[0],r=t[1],o=t[2],n;n=Math.atan2(o,r)*360/2/Math.PI,n<0&&(n+=360);let i=Math.sqrt(r*r+o*o);return[e,i,n]};E.lch.lab=function(t){let e=t[0],r=t[1],n=t[2]/360*2*Math.PI,s=r*Math.cos(n),i=r*Math.sin(n);return[e,s,i]};E.rgb.ansi16=function(t,e=null){let[r,o,n]=t,s=e===null?E.rgb.hsv(t)[2]:e;if(s=Math.round(s/50),s===0)return 30;let i=30+(Math.round(n/255)<<2|Math.round(o/255)<<1|Math.round(r/255));return s===2&&(i+=60),i};E.hsv.ansi16=function(t){return E.rgb.ansi16(E.hsv.rgb(t),t[2])};E.rgb.ansi256=function(t){let e=t[0],r=t[1],o=t[2];return e===r&&r===o?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(o/255*5)};E.ansi16.rgb=function(t){let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let r=(~~(t>50)+1)*.5,o=(e&1)*r*255,n=(e>>1&1)*r*255,s=(e>>2&1)*r*255;return[o,n,s]};E.ansi256.rgb=function(t){if(t>=232){let s=(t-232)*10+8;return[s,s,s]}t-=16;let e,r=Math.floor(t/36)/5*255,o=Math.floor((e=t%36)/6)/5*255,n=e%6/5*255;return[r,o,n]};E.rgb.hex=function(t){let r=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return"000000".substring(r.length)+r};E.hex.rgb=function(t){let e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let r=e[0];e[0].length===3&&(r=r.split("").map(a=>a+a).join(""));let o=parseInt(r,16),n=o>>16&255,s=o>>8&255,i=o&255;return[n,s,i]};E.rgb.hcg=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.max(Math.max(e,r),o),s=Math.min(Math.min(e,r),o),i=n-s,a,l;return i<1?a=s/(1-i):a=0,i<=0?l=0:n===e?l=(r-o)/i%6:n===r?l=2+(o-e)/i:l=4+(e-r)/i,l/=6,l%=1,[l*360,i*100,a*100]};E.hsl.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=r<.5?2*e*r:2*e*(1-r),n=0;return o<1&&(n=(r-.5*o)/(1-o)),[t[0],o*100,n*100]};E.hsv.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=e*r,n=0;return o<1&&(n=(r-o)/(1-o)),[t[0],o*100,n*100]};E.hcg.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100;if(r===0)return[o*255,o*255,o*255];let n=[0,0,0],s=e%1*6,i=s%1,a=1-i,l=0;switch(Math.floor(s)){case 0:n[0]=1,n[1]=i,n[2]=0;break;case 1:n[0]=a,n[1]=1,n[2]=0;break;case 2:n[0]=0,n[1]=1,n[2]=i;break;case 3:n[0]=0,n[1]=a,n[2]=1;break;case 4:n[0]=i,n[1]=0,n[2]=1;break;default:n[0]=1,n[1]=0,n[2]=a}return l=(1-r)*o,[(r*n[0]+l)*255,(r*n[1]+l)*255,(r*n[2]+l)*255]};E.hcg.hsv=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e),n=0;return o>0&&(n=e/o),[t[0],n*100,o*100]};E.hcg.hsl=function(t){let e=t[1]/100,o=t[2]/100*(1-e)+.5*e,n=0;return o>0&&o<.5?n=e/(2*o):o>=.5&&o<1&&(n=e/(2*(1-o))),[t[0],n*100,o*100]};E.hcg.hwb=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e);return[t[0],(o-e)*100,(1-o)*100]};E.hwb.hcg=function(t){let e=t[1]/100,o=1-t[2]/100,n=o-e,s=0;return n<1&&(s=(o-n)/(1-n)),[t[0],n*100,s*100]};E.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};E.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};E.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};E.gray.hsl=function(t){return[0,0,t[0]]};E.gray.hsv=E.gray.hsl;E.gray.hwb=function(t){return[0,100,t[0]]};E.gray.cmyk=function(t){return[0,0,0,t[0]]};E.gray.lab=function(t){return[t[0],0,0]};E.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,o=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(o.length)+o};E.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var Gp=ot((F$,zp)=>{"use strict";var Ya=dc();function Ox(){let t={},e=Object.keys(Ya);for(let r=e.length,o=0;o<r;o++)t[e[o]]={distance:-1,parent:null};return t}function Ax(t){let e=Ox(),r=[t];for(e[t].distance=0;r.length;){let o=r.pop(),n=Object.keys(Ya[o]);for(let s=n.length,i=0;i<s;i++){let a=n[i],l=e[a];l.distance===-1&&(l.distance=e[o].distance+1,l.parent=o,r.unshift(a))}}return e}function Rx(t,e){return function(r){return e(t(r))}}function Ix(t,e){let r=[e[t].parent,t],o=Ya[e[t].parent][t],n=e[t].parent;for(;e[n].parent;)r.unshift(e[n].parent),o=Rx(Ya[e[n].parent][n],o),n=e[n].parent;return o.conversion=r,o}zp.exports=function(t){let e=Ax(t),r={},o=Object.keys(e);for(let n=o.length,s=0;s<n;s++){let i=o[s];e[i].parent!==null&&(r[i]=Ix(i,e))}return r}});var Jp=ot(($$,Kp)=>{"use strict";var fc=dc(),Dx=Gp(),rn={},Lx=Object.keys(fc);function Nx(t){let e=function(...r){let o=r[0];return o==null?o:(o.length>1&&(r=o),t(r))};return"conversion"in t&&(e.conversion=t.conversion),e}function jx(t){let e=function(...r){let o=r[0];if(o==null)return o;o.length>1&&(r=o);let n=t(r);if(typeof n=="object")for(let s=n.length,i=0;i<s;i++)n[i]=Math.round(n[i]);return n};return"conversion"in t&&(e.conversion=t.conversion),e}Lx.forEach(t=>{rn[t]={},Object.defineProperty(rn[t],"channels",{value:fc[t].channels}),Object.defineProperty(rn[t],"labels",{value:fc[t].labels});let e=Dx(t);Object.keys(e).forEach(o=>{let n=e[o];rn[t][o]=jx(n),rn[t][o].raw=Nx(n)})});Kp.exports=rn});var Qp=ot((B$,Xp)=>{"use strict";var on=Vp(),Qe=Jp(),Yp=["keyword","gray","hex"],mc={};for(let t of Object.keys(Qe))mc[[...Qe[t].labels].sort().join("")]=t;var Xa={};function Ee(t,e){if(!(this instanceof Ee))return new Ee(t,e);if(e&&e in Yp&&(e=null),e&&!(e in Qe))throw new Error("Unknown model: "+e);let r,o;if(t==null)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(t instanceof Ee)this.model=t.model,this.color=[...t.color],this.valpha=t.valpha;else if(typeof t=="string"){let n=on.get(t);if(n===null)throw new Error("Unable to parse color from string: "+t);this.model=n.model,o=Qe[this.model].channels,this.color=n.value.slice(0,o),this.valpha=typeof n.value[o]=="number"?n.value[o]:1}else if(t.length>0){this.model=e||"rgb",o=Qe[this.model].channels;let n=Array.prototype.slice.call(t,0,o);this.color=hc(n,o),this.valpha=typeof t[o]=="number"?t[o]:1}else if(typeof t=="number")this.model="rgb",this.color=[t>>16&255,t>>8&255,t&255],this.valpha=1;else{this.valpha=1;let n=Object.keys(t);"alpha"in t&&(n.splice(n.indexOf("alpha"),1),this.valpha=typeof t.alpha=="number"?t.alpha:0);let s=n.sort().join("");if(!(s in mc))throw new Error("Unable to parse color from object: "+JSON.stringify(t));this.model=mc[s];let{labels:i}=Qe[this.model],a=[];for(r=0;r<i.length;r++)a.push(t[i[r]]);this.color=hc(a)}if(Xa[this.model])for(o=Qe[this.model].channels,r=0;r<o;r++){let n=Xa[this.model][r];n&&(this.color[r]=n(this.color[r]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}Ee.prototype={toString(){return this.string()},toJSON(){return this[this.model]()},string(t){let e=this.model in on.to?this:this.rgb();e=e.round(typeof t=="number"?t:1);let r=e.valpha===1?e.color:[...e.color,this.valpha];return on.to[e.model](r)},percentString(t){let e=this.rgb().round(typeof t=="number"?t:1),r=e.valpha===1?e.color:[...e.color,this.valpha];return on.to.rgb.percent(r)},array(){return this.valpha===1?[...this.color]:[...this.color,this.valpha]},object(){let t={},{channels:e}=Qe[this.model],{labels:r}=Qe[this.model];for(let o=0;o<e;o++)t[r[o]]=this.color[o];return this.valpha!==1&&(t.alpha=this.valpha),t},unitArray(){let t=this.rgb().color;return t[0]/=255,t[1]/=255,t[2]/=255,this.valpha!==1&&t.push(this.valpha),t},unitObject(){let t=this.rgb().object();return t.r/=255,t.g/=255,t.b/=255,this.valpha!==1&&(t.alpha=this.valpha),t},round(t){return t=Math.max(t||0,0),new Ee([...this.color.map(Ux(t)),this.valpha],this.model)},alpha(t){return t!==void 0?new Ee([...this.color,Math.max(0,Math.min(1,t))],this.model):this.valpha},red:de("rgb",0,Se(255)),green:de("rgb",1,Se(255)),blue:de("rgb",2,Se(255)),hue:de(["hsl","hsv","hsl","hwb","hcg"],0,t=>(t%360+360)%360),saturationl:de("hsl",1,Se(100)),lightness:de("hsl",2,Se(100)),saturationv:de("hsv",1,Se(100)),value:de("hsv",2,Se(100)),chroma:de("hcg",1,Se(100)),gray:de("hcg",2,Se(100)),white:de("hwb",1,Se(100)),wblack:de("hwb",2,Se(100)),cyan:de("cmyk",0,Se(100)),magenta:de("cmyk",1,Se(100)),yellow:de("cmyk",2,Se(100)),black:de("cmyk",3,Se(100)),x:de("xyz",0,Se(95.047)),y:de("xyz",1,Se(100)),z:de("xyz",2,Se(108.833)),l:de("lab",0,Se(100)),a:de("lab",1),b:de("lab",2),keyword(t){return t!==void 0?new Ee(t):Qe[this.model].keyword(this.color)},hex(t){return t!==void 0?new Ee(t):on.to.hex(this.rgb().round().color)},hexa(t){if(t!==void 0)return new Ee(t);let e=this.rgb().round().color,r=Math.round(this.valpha*255).toString(16).toUpperCase();return r.length===1&&(r="0"+r),on.to.hex(e)+r},rgbNumber(){let t=this.rgb().color;return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255},luminosity(){let t=this.rgb().color,e=[];for(let[r,o]of t.entries()){let n=o/255;e[r]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return .2126*e[0]+.7152*e[1]+.0722*e[2]},contrast(t){let e=this.luminosity(),r=t.luminosity();return e>r?(e+.05)/(r+.05):(r+.05)/(e+.05)},level(t){let e=this.contrast(t);return e>=7?"AAA":e>=4.5?"AA":""},isDark(){let t=this.rgb().color;return(t[0]*2126+t[1]*7152+t[2]*722)/1e4<128},isLight(){return!this.isDark()},negate(){let t=this.rgb();for(let e=0;e<3;e++)t.color[e]=255-t.color[e];return t},lighten(t){let e=this.hsl();return e.color[2]+=e.color[2]*t,e},darken(t){let e=this.hsl();return e.color[2]-=e.color[2]*t,e},saturate(t){let e=this.hsl();return e.color[1]+=e.color[1]*t,e},desaturate(t){let e=this.hsl();return e.color[1]-=e.color[1]*t,e},whiten(t){let e=this.hwb();return e.color[1]+=e.color[1]*t,e},blacken(t){let e=this.hwb();return e.color[2]+=e.color[2]*t,e},grayscale(){let t=this.rgb().color,e=t[0]*.3+t[1]*.59+t[2]*.11;return Ee.rgb(e,e,e)},fade(t){return this.alpha(this.valpha-this.valpha*t)},opaquer(t){return this.alpha(this.valpha+this.valpha*t)},rotate(t){let e=this.hsl(),r=e.color[0];return r=(r+t)%360,r=r<0?360+r:r,e.color[0]=r,e},mix(t,e){if(!t||!t.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof t);let r=t.rgb(),o=this.rgb(),n=e===void 0?.5:e,s=2*n-1,i=r.alpha()-o.alpha(),a=((s*i===-1?s:(s+i)/(1+s*i))+1)/2,l=1-a;return Ee.rgb(a*r.red()+l*o.red(),a*r.green()+l*o.green(),a*r.blue()+l*o.blue(),r.alpha()*n+o.alpha()*(1-n))}};for(let t of Object.keys(Qe)){if(Yp.includes(t))continue;let{channels:e}=Qe[t];Ee.prototype[t]=function(...r){return this.model===t?new Ee(this):r.length>0?new Ee(r,t):new Ee([...Fx(Qe[this.model][t].raw(this.color)),this.valpha],t)},Ee[t]=function(...r){let o=r[0];return typeof o=="number"&&(o=hc(r,e)),new Ee(o,t)}}function Mx(t,e){return Number(t.toFixed(e))}function Ux(t){return function(e){return Mx(e,t)}}function de(t,e,r){t=Array.isArray(t)?t:[t];for(let o of t)(Xa[o]||(Xa[o]=[]))[e]=r;return t=t[0],function(o){let n;return o!==void 0?(r&&(o=r(o)),n=this[t](),n.color[e]=o,n):(n=this[t]().color[e],r&&(n=r(n)),n)}}function Se(t){return function(e){return Math.max(0,Math.min(t,e))}}function Fx(t){return Array.isArray(t)?t:[t]}function hc(t,e){for(let r=0;r<e;r++)typeof t[r]!="number"&&(t[r]=0);return t}Xp.exports=Ee});import{usePathname as TC}from"next/navigation";import{useCallback as Cr,useEffect as lr,useMemo as Ze,useRef as ar,useState as Er}from"react";import{create as NS}from"zustand";function Be(t,e){var r={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,o=Object.getOwnPropertySymbols(t);n<o.length;n++)e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(r[o[n]]=t[o[n]]);return r}function Ds(t,e,r,o){function n(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(c){try{u(o.next(c))}catch(d){i(d)}}function l(c){try{u(o.throw(c))}catch(d){i(d)}}function u(c){c.done?s(c.value):n(c.value).then(a,l)}u((o=o.apply(t,e||[])).next())})}var Xc=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var mo=class extends Error{constructor(e,r="FunctionsError",o){super(e),this.name=r,this.context=o}},bn=class extends mo{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},ho=class extends mo{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},po=class extends mo{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},_n;(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"})(_n||(_n={}));var wn=class{constructor(e,{headers:r={},customFetch:o,region:n=_n.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=Xc(o)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Ds(this,arguments,void 0,function*(r,o={}){var n;let s,i;try{let{headers:a,method:l,body:u,signal:c,timeout:d}=o,f={},{region:m}=o;m||(m=this.region);let h=new URL(`${this.url}/${r}`);m&&m!=="any"&&(f["x-region"]=m,h.searchParams.set("forceFunctionRegion",m));let g;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=u):typeof u=="string"?(f["Content-Type"]="text/plain",g=u):typeof FormData<"u"&&u instanceof FormData?g=u:(f["Content-Type"]="application/json",g=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?g=JSON.stringify(u):g=u;let y=c;d&&(i=new AbortController,s=setTimeout(()=>i.abort(),d),c?(y=i.signal,c.addEventListener("abort",()=>i.abort())):y=i.signal);let p=yield this.fetch(h.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:y}).catch(L=>{throw new bn(L)}),b=p.headers.get("x-relay-error");if(b&&b==="true")throw new ho(p);if(!p.ok)throw new po(p);let _=((n=p.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),v;return _==="application/json"?v=yield p.json():_==="application/octet-stream"||_==="application/pdf"?v=yield p.blob():_==="text/event-stream"?v=p:_==="multipart/form-data"?v=yield p.formData():v=yield p.text(),{data:v,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof po||a instanceof ho?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var ed=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Oy=class{constructor(t){var e,r,o;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=(o=t.urlLengthLimit)!==null&&o!==void 0?o: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 o=this.fetch,n=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let i=null,a=null,l=null,u=s.status,c=s.statusText;if(s.ok){var d,f;if(r.method!=="HEAD"){var m;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let h=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(f=s.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");h&&g&&g.length>1&&(l=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(i={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,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let h=await s.text();try{i=JSON.parse(h),Array.isArray(i)&&s.status===404&&(a=[],i=null,u=200,c="OK")}catch{s.status===404&&h===""?(u=204,c="No Content"):i={message:h}}if(i&&r.shouldThrowOnError)throw new ed(i)}return{error:i,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(n=n.catch(s=>{var i;let a="",l="",u="",c=s?.cause;if(c){var d,f,m,h;let p=(d=c?.message)!==null&&d!==void 0?d:"",b=(f=c?.code)!==null&&f!==void 0?f:"";a=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,a+=`
|
|
3
3
|
|
|
4
4
|
Caused by: ${(h=c?.name)!==null&&h!==void 0?h:"Error"}: ${p}`,b&&(a+=` (${b})`),c?.stack&&(a+=`
|
|
5
|
-
${c.stack}`)}else{var g;a=(g=s?.stack)!==null&&g!==void 0?g:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${y} 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.`)):(c?.name==="HeadersOverflowError"||c?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(l+=`. Your request URL is ${y} 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:`${(i=s?.name)!==null&&i!==void 0?i:"FetchError"}: ${s?.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},Ay=class extends Oy{select(t){let e=!1,r=(t??"*").split("").map(o=>/\s/.test(o)&&!e?"":(o==='"'&&(e=!e),o)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:o,referencedTable:n=o}={}){let s=n?`${n}.order`:"order",i=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(o,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:o=r}={}){let n=typeof o>"u"?"offset":`${o}.offset`,s=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(s,`${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.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:o=!1,wal:n=!1,format:s="text"}={}){var i;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,o?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="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}},Yc=new RegExp("[,()]"),go=class extends Ay{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(o=>typeof o=="string"&&Yc.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Yc.test(o)?`"${o}"`:`${o}`).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:o}={}){let n="";o==="plain"?n="pl":o==="phrase"?n="ph":o==="websearch"&&(n="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).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 o=r?`${r}.or`:"or";return this.url.searchParams.append(o,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Ry=class{constructor(t,{headers:e={},schema:r,fetch:o,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=o,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:o}=e??{},n=r?"HEAD":"GET",s=!1,i=(t??"*").split("").map(u=>/\s/.test(u)&&!s?"":(u==='"'&&(s=!s),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",i),o&&l.append("Prefer",`count=${o}`),new go({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var o;let n="POST",{url:s,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){let l=[...new Set(a)].map(u=>`"${u}"`);s.searchParams.set("columns",l.join(","))}}return new go({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:o,defaultToNull:n=!0}={}){var s;let i="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),o&&l.append("Prefer",`count=${o}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let u=t.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(u.length>0){let c=[...new Set(u)].map(d=>`"${d}"`);a.searchParams.set("columns",c.join(","))}}return new go({method:i,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let o="PATCH",{url:n,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new go({method:o,url:n,headers:s,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:o,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new go({method:r,url:o,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function vn(t){"@babel/helpers - typeof";return vn=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},vn(t)}function Iy(t,e){if(vn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(vn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Dy(t){var e=Iy(t,"string");return vn(e)=="symbol"?e:e+""}function Ly(t,e,r){return(e=Dy(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Xc(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function Ls(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Xc(Object(r),!0).forEach(function(o){Ly(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Xc(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var Zc=class ed{constructor(e,{headers:r={},schema:o,fetch:n,timeout:s,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=o,this.urlLengthLimit=i;let a=n??globalThis.fetch;s!==void 0&&s>0?this.fetch=(l,u)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),s),f=u?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,u);let m=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",m,{once:!0}),a(l,Ls(Ls({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",m)})}return a(l,Ls(Ls({},u),{},{signal:c.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 Ry(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new ed(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:o=!1,get:n=!1,count:s}={}){var i;let a,l=new URL(`${this.url}/rpc/${e}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),d=o&&Object.values(r).some(c);d?(a="POST",u=r):o||n?(a=o?"HEAD":"GET",Object.entries(r).filter(([m,h])=>h!==void 0).map(([m,h])=>[m,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([m,h])=>{l.searchParams.append(m,h)})):(a="POST",u=r);let f=new Headers(this.headers);return d?f.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&f.set("Prefer",`count=${s}`),new go({method:a,url:l,headers:f,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};var pl=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 o=r.versions;if(o&&o.node){let n=o.node,s=parseInt(n.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
5
|
+
${c.stack}`)}else{var g;a=(g=s?.stack)!==null&&g!==void 0?g:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${y} 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.`)):(c?.name==="HeadersOverflowError"||c?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(l+=`. Your request URL is ${y} 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:`${(i=s?.name)!==null&&i!==void 0?i:"FetchError"}: ${s?.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},Ay=class extends Oy{select(t){let e=!1,r=(t??"*").split("").map(o=>/\s/.test(o)&&!e?"":(o==='"'&&(e=!e),o)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:o,referencedTable:n=o}={}){let s=n?`${n}.order`:"order",i=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(o,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:o=r}={}){let n=typeof o>"u"?"offset":`${o}.offset`,s=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(s,`${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.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:o=!1,wal:n=!1,format:s="text"}={}){var i;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,o?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="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}},Qc=new RegExp("[,()]"),go=class extends Ay{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(o=>typeof o=="string"&&Qc.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Qc.test(o)?`"${o}"`:`${o}`).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:o}={}){let n="";o==="plain"?n="pl":o==="phrase"?n="ph":o==="websearch"&&(n="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).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 o=r?`${r}.or`:"or";return this.url.searchParams.append(o,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Ry=class{constructor(t,{headers:e={},schema:r,fetch:o,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=o,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:o}=e??{},n=r?"HEAD":"GET",s=!1,i=(t??"*").split("").map(u=>/\s/.test(u)&&!s?"":(u==='"'&&(s=!s),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",i),o&&l.append("Prefer",`count=${o}`),new go({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var o;let n="POST",{url:s,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){let l=[...new Set(a)].map(u=>`"${u}"`);s.searchParams.set("columns",l.join(","))}}return new go({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:o,defaultToNull:n=!0}={}){var s;let i="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),o&&l.append("Prefer",`count=${o}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let u=t.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(u.length>0){let c=[...new Set(u)].map(d=>`"${d}"`);a.searchParams.set("columns",c.join(","))}}return new go({method:i,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let o="PATCH",{url:n,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new go({method:o,url:n,headers:s,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:o,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new go({method:r,url:o,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function vn(t){"@babel/helpers - typeof";return vn=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},vn(t)}function Iy(t,e){if(vn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(vn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Dy(t){var e=Iy(t,"string");return vn(e)=="symbol"?e:e+""}function Ly(t,e,r){return(e=Dy(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Zc(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function Ls(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Zc(Object(r),!0).forEach(function(o){Ly(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Zc(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var td=class rd{constructor(e,{headers:r={},schema:o,fetch:n,timeout:s,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=o,this.urlLengthLimit=i;let a=n??globalThis.fetch;s!==void 0&&s>0?this.fetch=(l,u)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),s),f=u?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,u);let m=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",m,{once:!0}),a(l,Ls(Ls({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",m)})}return a(l,Ls(Ls({},u),{},{signal:c.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 Ry(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new rd(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:o=!1,get:n=!1,count:s}={}){var i;let a,l=new URL(`${this.url}/rpc/${e}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),d=o&&Object.values(r).some(c);d?(a="POST",u=r):o||n?(a=o?"HEAD":"GET",Object.entries(r).filter(([m,h])=>h!==void 0).map(([m,h])=>[m,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([m,h])=>{l.searchParams.append(m,h)})):(a="POST",u=r);let f=new Headers(this.headers);return d?f.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&f.set("Prefer",`count=${s}`),new go({method:a,url:l,headers:f,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};var yl=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 o=r.versions;if(o&&o.node){let n=o.node,s=parseInt(n.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
6
6
|
import ws from "ws"
|
|
7
7
|
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+=`
|
|
8
8
|
|
|
9
|
-
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},gl=pl;var td="2.100.1";var rd=`realtime-js/${td}`,od="1.0.0",yl="2.0.0",nd=yl;var sd=1e4;var id=100;var Pt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ns={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var Sn={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var xn=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 o=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(o))}_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,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,o){var n,s;let i=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",u=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(c).length===0?"":JSON.stringify(c);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(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.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+i.length+u.length+d.length,m=new ArrayBuffer(this.HEADER_LENGTH+f),h=new DataView(m),g=0;h.setUint8(g++,this.KINDS.userBroadcastPush),h.setUint8(g++,l.length),h.setUint8(g++,a.length),h.setUint8(g++,i.length),h.setUint8(g++,u.length),h.setUint8(g++,d.length),h.setUint8(g++,r),Array.from(l,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(i,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(u,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>h.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(m.byteLength+o.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(o),m.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let o=this._binaryDecode(e);return r(o)}if(typeof e=="string"){let o=JSON.parse(e),[n,s,i,a,l]=o;return r({join_ref:n,ref:s,topic:i,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),o=r.getUint8(0),n=new TextDecoder;if(o===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,o){let n=r.getUint8(1),s=r.getUint8(2),i=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,u=o.decode(e.slice(l,l+n));l=l+n;let c=o.decode(e.slice(l,l+s));l=l+s;let d=o.decode(e.slice(l,l+i));l=l+i;let f=e.slice(l,e.byteLength),m=a===this.JSON_ENCODING?JSON.parse(o.decode(f)):f,h={type:this.BROADCAST_EVENT,event:c,payload:m};return i>0&&(h.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:h}}_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(([o])=>r.includes(o)))}};var te;(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"})(te||(te={}));var _l=(t,e,r={})=>{var o;let n=(o=r.skipTypes)!==null&&o!==void 0?o:[];return e?Object.keys(e).reduce((s,i)=>(s[i]=Ny(i,t,e,n),s),{}):{}},Ny=(t,e,r,o)=>{let n=e.find(a=>a.name===t),s=n?.type,i=r[t];return s&&!o.includes(s)?ad(s,i):bl(i)},ad=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Fy(e,r)}switch(t){case te.bool:return jy(e);case te.float4:case te.float8:case te.int2:case te.int4:case te.int8:case te.numeric:case te.oid:return My(e);case te.json:case te.jsonb:return Uy(e);case te.timestamp:return $y(e);case te.abstime:case te.date:case te.daterange:case te.int4range:case te.int8range:case te.money:case te.reltime:case te.text:case te.time:case te.timestamptz:case te.timetz:case te.tsrange:case te.tstzrange:return bl(e);default:return bl(e)}},bl=t=>t,jy=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},My=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Uy=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Fy=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,o=t[r];if(t[0]==="{"&&o==="}"){let s,i=t.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map(a=>ad(e,a))}return t},$y=t=>typeof t=="string"?t.replace(" ","T"):t,js=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};var Tn=t=>typeof t=="function"?t:function(){return t},qy=typeof self<"u"?self:null,bo=typeof window<"u"?window:null,Ot=qy||bo||globalThis,Vy="2.0.0",Wy=1e4,Hy=1e3,At={connecting:0,open:1,closing:2,closed:3},qe={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Gt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},wl={longpoll:"longpoll",websocket:"websocket"},zy={complete:4},vl="base64url.bearer.phx.",Ms=class{constructor(t,e,r,o){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=o,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),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()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(o=>o.status===t).forEach(o=>o.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},ld=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Gy=class{constructor(t,e,r){this.state=qe.closed,this.topic=t,this.params=Tn(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Ms(this,Gt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ld(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=qe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this.joinPush.receive("error",o=>{this.state=qe.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,o),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=qe.closed,this.socket.remove(this)}),this.onError(o=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,o),this.isJoining()&&this.joinPush.reset(),this.state=qe.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Ms(this,Gt.leave,Tn({}),this.timeout).send(),this.state=qe.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Gt.reply,(o,n)=>{this.trigger(this.replyEventName(n),o)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=qe.closed,this.bindings=[]}onClose(t){this.on(Gt.close,t)}onError(t){return this.on(Gt.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let o=new Ms(this,t,function(){return e},r);return this.canPush()?o.send():(o.startTimeout(),this.pushBuffer.push(o)),o}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=qe.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Gt.close,"leave")},r=new Ms(this,Gt.leave,Tn({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,o){return this.topic!==t?!1:o&&o!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:o}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=qe.joining,this.joinPush.resend(t))}trigger(t,e,r,o){let n=this.onMessage(t,e,r,o);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(i=>i.event===t&&this.filterBindings(i,e,r));for(let i=0;i<s.length;i++)s[i].callback(n,r,o||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===qe.closed}isErrored(){return this.state===qe.errored}isJoined(){return this.state===qe.joined}isJoining(){return this.state===qe.joining}isLeaving(){return this.state===qe.leaving}},Fs=class{static request(t,e,r,o,n,s,i){if(Ot.XDomainRequest){let a=new Ot.XDomainRequest;return this.xdomainRequest(a,t,e,o,n,s,i)}else if(Ot.XMLHttpRequest){let a=new Ot.XMLHttpRequest;return this.xhrRequest(a,t,e,r,o,n,s,i)}else{if(Ot.fetch&&Ot.AbortController)return this.fetchRequest(t,e,r,o,n,s,i);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,o,n,s,i){let a={method:t,headers:r,body:o},l=null;if(n){l=new AbortController;let u=setTimeout(()=>l.abort(),n);a.signal=l.signal}return Ot.fetch(e,a).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>i&&i(u)).catch(u=>{u.name==="AbortError"&&s?s():i&&i(null)}),l}static xdomainRequest(t,e,r,o,n,s,i){return t.timeout=n,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);i&&i(a)},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(o),t}static xhrRequest(t,e,r,o,n,s,i,a){t.open(e,r,!0),t.timeout=s;for(let[l,u]of Object.entries(o))t.setRequestHeader(l,u);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===zy.complete&&a){let l=this.parseJSON(t.responseText);a(l)}},i&&(t.ontimeout=i),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=e?`${e}[${o}]`:o,s=t[o];typeof s=="object"?r.push(this.serialize(s,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(s))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},Ky=t=>{let e="",r=new Uint8Array(t),o=r.byteLength;for(let n=0;n<o;n++)e+=String.fromCharCode(r[n]);return btoa(e)},yo=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(vl)&&(this.authToken=atob(e[1].slice(vl.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=At.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+wl.websocket),"$1/"+wl.longpoll)}endpointURL(){return Fs.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=At.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===At.open||this.readyState===At.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:o,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=o}else r=0;switch(r){case 200:n.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=At.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=Ky(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
10
|
-
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=At.closed;let o=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",o)):this.onclose(o)}ajax(t,e,r,o,n){let s,i=()=>{this.reqs.delete(s),o()};s=Fs.request(t,this.endpointURL(),e,r,this.timeout,i,a=>{this.reqs.delete(s),this.isActive()&&n(a)}),this.reqs.add(s)}},$s=class kn{constructor(e,r={}){let o=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(o.state,n=>{let{onJoin:s,onLeave:i,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=kn.syncState(this.state,n,s,i),this.pendingDiffs.forEach(l=>{this.state=kn.syncDiff(this.state,l,s,i)}),this.pendingDiffs=[],a()}),this.channel.on(o.diff,n=>{let{onJoin:s,onLeave:i,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=kn.syncDiff(this.state,n,s,i),a())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return kn.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,o,n){let s=this.clone(e),i={},a={};return this.map(s,(l,u)=>{r[l]||(a[l]=u)}),this.map(r,(l,u)=>{let c=s[l];if(c){let d=u.metas.map(g=>g.phx_ref),f=c.metas.map(g=>g.phx_ref),m=u.metas.filter(g=>f.indexOf(g.phx_ref)<0),h=c.metas.filter(g=>d.indexOf(g.phx_ref)<0);m.length>0&&(i[l]=u,i[l].metas=m),h.length>0&&(a[l]=this.clone(c),a[l].metas=h)}else i[l]=u}),this.syncDiff(s,{joins:i,leaves:a},o,n)}static syncDiff(e,r,o,n){let{joins:s,leaves:i}=this.clone(r);return o||(o=function(){}),n||(n=function(){}),this.map(s,(a,l)=>{let u=e[a];if(e[a]=this.clone(l),u){let c=e[a].metas.map(f=>f.phx_ref),d=u.metas.filter(f=>c.indexOf(f.phx_ref)<0);e[a].metas.unshift(...d)}o(a,u,l)}),this.map(i,(a,l)=>{let u=e[a];if(!u)return;let c=l.metas.map(d=>d.phx_ref);u.metas=u.metas.filter(d=>c.indexOf(d.phx_ref)<0),n(a,u,l),u.metas.length===0&&delete e[a]}),e}static list(e,r){return r||(r=function(o,n){return n}),this.map(e,(o,n)=>r(o,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(o=>r(o,e[o]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Us={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,o,n,s,i]=JSON.parse(t);return e({join_ref:r,ref:o,topic:n,event:s,payload:i})}},binaryEncode(t){let{join_ref:e,ref:r,event:o,topic:n,payload:s}=t,i=this.META_LENGTH+e.length+r.length+n.length+o.length,a=new ArrayBuffer(this.HEADER_LENGTH+i),l=new DataView(a),u=0;l.setUint8(u++,this.KINDS.push),l.setUint8(u++,e.length),l.setUint8(u++,r.length),l.setUint8(u++,n.length),l.setUint8(u++,o.length),Array.from(e,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(o,d=>l.setUint8(u++,d.charCodeAt(0)));var c=new Uint8Array(a.byteLength+s.byteLength);return c.set(new Uint8Array(a),0),c.set(new Uint8Array(s),a.byteLength),c.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),o=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,o);case this.KINDS.reply:return this.decodeReply(t,e,o);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,o)}},decodePush(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=e.getUint8(3),i=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(i,i+o));i=i+o;let l=r.decode(t.slice(i,i+n));i=i+n;let u=r.decode(t.slice(i,i+s));i=i+s;let c=t.slice(i,t.byteLength);return{join_ref:a,ref:null,topic:l,event:u,payload:c}},decodeReply(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=e.getUint8(3),i=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+o));a=a+o;let u=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+i));a=a+i;let f=t.slice(a,t.byteLength),m={status:d,response:f};return{join_ref:l,ref:u,topic:c,event:Gt.reply,payload:m}},decodeBroadcast(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=this.HEADER_LENGTH+2,i=r.decode(t.slice(s,s+o));s=s+o;let a=r.decode(t.slice(s,s+n));s=s+n;let l=t.slice(s,t.byteLength);return{join_ref:null,ref:null,topic:i,event:a,payload:l}}},Bs=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Wy,this.transport=e.transport||Ot.WebSocket||yo,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||Ot&&Ot.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Us.encode.bind(Us),this.defaultDecoder=Us.decode.bind(Us),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==yo?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;bo&&bo.addEventListener&&(bo.addEventListener("pagehide",o=>{this.conn&&(this.disconnect(),r=this.connectClock)}),bo.addEventListener("pageshow",o=>{r===this.connectClock&&(r=null,this.connect())}),bo.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=o=>e.rejoinAfterMs?e.rejoinAfterMs(o):[1e3,2e3,5e3][o-1]||1e4,this.reconnectAfterMs=o=>e.reconnectAfterMs?e.reconnectAfterMs(o):[10,50,100,150,200,250,500,1e3,2e3][o-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(o,n,s)=>{console.log(`${o}: ${n}`,s)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Tn(e.params||{}),this.endPoint=`${t}/${wl.websocket}`,this.vsn=e.vsn||Vy,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ld(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return yo}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Fs.appendParams(Fs.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Tn(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==yo?this.connectWithFallback(yo,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let o=this.onMessage(n=>{n.ref===e&&(this.off([o]),t(Date.now()-r))});return!0}transportName(t){return t===yo?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${vl}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,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)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,o=!0,n,s,i=this.transportName(t),a=l=>{this.log("transport",`falling back to ${i}...`,l),this.off([n,s]),o=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${i}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(l=>{this.log("transport","error",l),o&&!r&&(clearTimeout(this.fallbackTimer),a(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!o){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Hy,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();let o=this.conn;this.waitForBufferDone(o,()=>{e?o.close(e,r||""):o.close(),this.waitForSocketClosed(o,()=>{this.conn===o&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===At.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Gt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case At.connecting:return"connecting";case At.open:return"open";case At.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new Gy(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:o,ref:n,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${n})`,o)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:o,payload:n,ref:s,join_ref:i}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",a)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${o} ${s&&"("+s+")"||""}`.trim(),n);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(r,o,n,i)&&l.trigger(o,n,s,i)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,o])=>{try{o(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};var Cn=class t{constructor(e,r){let o=Yy(r);this.presence=new $s(e.getChannel(),o),this.presence.onJoin((n,s,i)=>{let a=t.onJoinPayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,s,i)=>{let a=t.onLeavePayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Jy(e),Object.getOwnPropertyNames(e).reduce((r,o)=>{let n=e[o];return r[o]=qs(n),r},{})}static onJoinPayload(e,r,o){let n=ud(r),s=qs(o);return{event:"join",key:e,currentPresences:n,newPresences:s}}static onLeavePayload(e,r,o){let n=ud(r),s=qs(o);return{event:"leave",key:e,currentPresences:n,leftPresences:s}}};function qs(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Jy(t){return JSON.parse(JSON.stringify(t))}function Yy(t){return t?.events&&{events:t.events}}function ud(t){return t?.metas?qs(t):[]}var Sl;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Sl||(Sl={}));var _o=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Cn(this.channel.channelAdapter,r)}};var En=class{constructor(e,r,o){let n=Xy(o);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,o){let n;try{n=this.channel.push(e,r,o)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>id){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===Pt.joined}isJoined(){return this.state===Pt.joined}isJoining(){return this.state===Pt.joining}isClosed(){return this.state===Pt.closed}isLeaving(){return this.state===Pt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function Xy(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var xl;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(xl||(xl={}));var wo;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(wo||(wo={}));var Rt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Rt||(Rt={}));var vo=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},o){var n,s;if(this.topic=e,this.params=r,this.socket=o,this.bindings={},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.channelAdapter=new En(this.socket.socketAdapter,e,this.params),this.presence=new _o(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=js(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||s===void 0)&&s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var o,n,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:l}}=this.params,u=(n=(o=this.bindings.postgres_changes)===null||o===void 0?void 0:o.map(m=>m.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[wo.PRESENCE]&&this.bindings[wo.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},f={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(Rt.CHANNEL_ERROR,m)}),this._onClose(()=>e?.(Rt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(Rt.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=Pt.errored,e?.(Rt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{e?.(Rt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var o;let n=this.bindings.postgres_changes,s=(o=n?.length)!==null&&o!==void 0?o:0,i=[];for(let a=0;a<s;a++){let l=n[a],{filter:{event:u,schema:c,table:d,filter:f}}=l,m=e&&e[a];if(m&&m.event===u&&t.isFilterValueEqual(m.schema,c)&&t.isFilterValueEqual(m.table,d)&&t.isFilterValueEqual(m.filter,f))i.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=Pt.errored,r?.(Rt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=Pt.errored&&r&&r(Rt.SUBSCRIBED)}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,o){if(this.channelAdapter.isJoined()&&e===wo.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,o)}async httpSend(e,r,o={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=o.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var o,n;if(!this.channelAdapter.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:s,payload:i}=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:s,payload:i,private:this.private}]})};try{let u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(o=r.timeout)!==null&&o!==void 0?o:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var i,a,l;let u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(i=this.params)===null||i===void 0?void 0:i.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,o){let n=new AbortController,s=setTimeout(()=>n.abort(),o),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(s),i}_on(e,r,o){let n=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,o),i={type:n,filter:r,callback:o,ref:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,o)=>{var n,s,i,a,l,u,c;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,o))return!1;let f=(n=this.bindings[d])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in f){let m=f.id,h=(s=f.filter)===null||s===void 0?void 0:s.event;return m&&((i=r.ids)===null||i===void 0?void 0:i.includes(m))&&(h==="*"||h?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let m=(u=(l=f?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((c=r?.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:o,error:n,leave:s,join:i}=Ns;return r&&[o,n,s,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,o)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:s,table:i,commit_timestamp:a,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:s,table:i,commit_timestamp:a,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=_l(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=_l(e.columns,e.old_record)),r}};var Pn=class{constructor(e,r){this.socket=new Bs(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,o,n=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),n),this.socket.disconnect(()=>{e(),s("ok")},r,o)})}push(e){this.socket.push(e)}log(e,r,o){this.socket.log(e,r,o)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Sn.connecting}isDisconnecting(){return this.socket.connectionState()==Sn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var Qy={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Zy=[1e3,2e3,5e3,1e4],eb=1e4,tb=`
|
|
9
|
+
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},bl=yl;var od="2.100.1";var nd=`realtime-js/${od}`,sd="1.0.0",_l="2.0.0",id=_l;var ad=1e4;var ld=100;var Pt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ns={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var Sn={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var xn=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 o=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(o))}_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,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,o){var n,s;let i=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",u=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(c).length===0?"":JSON.stringify(c);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(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.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+i.length+u.length+d.length,m=new ArrayBuffer(this.HEADER_LENGTH+f),h=new DataView(m),g=0;h.setUint8(g++,this.KINDS.userBroadcastPush),h.setUint8(g++,l.length),h.setUint8(g++,a.length),h.setUint8(g++,i.length),h.setUint8(g++,u.length),h.setUint8(g++,d.length),h.setUint8(g++,r),Array.from(l,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(i,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(u,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>h.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(m.byteLength+o.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(o),m.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let o=this._binaryDecode(e);return r(o)}if(typeof e=="string"){let o=JSON.parse(e),[n,s,i,a,l]=o;return r({join_ref:n,ref:s,topic:i,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),o=r.getUint8(0),n=new TextDecoder;if(o===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,o){let n=r.getUint8(1),s=r.getUint8(2),i=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,u=o.decode(e.slice(l,l+n));l=l+n;let c=o.decode(e.slice(l,l+s));l=l+s;let d=o.decode(e.slice(l,l+i));l=l+i;let f=e.slice(l,e.byteLength),m=a===this.JSON_ENCODING?JSON.parse(o.decode(f)):f,h={type:this.BROADCAST_EVENT,event:c,payload:m};return i>0&&(h.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:h}}_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(([o])=>r.includes(o)))}};var te;(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"})(te||(te={}));var vl=(t,e,r={})=>{var o;let n=(o=r.skipTypes)!==null&&o!==void 0?o:[];return e?Object.keys(e).reduce((s,i)=>(s[i]=Ny(i,t,e,n),s),{}):{}},Ny=(t,e,r,o)=>{let n=e.find(a=>a.name===t),s=n?.type,i=r[t];return s&&!o.includes(s)?ud(s,i):wl(i)},ud=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Fy(e,r)}switch(t){case te.bool:return jy(e);case te.float4:case te.float8:case te.int2:case te.int4:case te.int8:case te.numeric:case te.oid:return My(e);case te.json:case te.jsonb:return Uy(e);case te.timestamp:return $y(e);case te.abstime:case te.date:case te.daterange:case te.int4range:case te.int8range:case te.money:case te.reltime:case te.text:case te.time:case te.timestamptz:case te.timetz:case te.tsrange:case te.tstzrange:return wl(e);default:return wl(e)}},wl=t=>t,jy=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},My=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Uy=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Fy=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,o=t[r];if(t[0]==="{"&&o==="}"){let s,i=t.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map(a=>ud(e,a))}return t},$y=t=>typeof t=="string"?t.replace(" ","T"):t,js=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};var Tn=t=>typeof t=="function"?t:function(){return t},qy=typeof self<"u"?self:null,bo=typeof window<"u"?window:null,Ot=qy||bo||globalThis,Vy="2.0.0",Wy=1e4,Hy=1e3,At={connecting:0,open:1,closing:2,closed:3},qe={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Gt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Sl={longpoll:"longpoll",websocket:"websocket"},zy={complete:4},xl="base64url.bearer.phx.",Ms=class{constructor(t,e,r,o){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=o,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),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()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(o=>o.status===t).forEach(o=>o.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},cd=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Gy=class{constructor(t,e,r){this.state=qe.closed,this.topic=t,this.params=Tn(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Ms(this,Gt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new cd(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=qe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this.joinPush.receive("error",o=>{this.state=qe.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,o),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=qe.closed,this.socket.remove(this)}),this.onError(o=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,o),this.isJoining()&&this.joinPush.reset(),this.state=qe.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Ms(this,Gt.leave,Tn({}),this.timeout).send(),this.state=qe.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Gt.reply,(o,n)=>{this.trigger(this.replyEventName(n),o)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=qe.closed,this.bindings=[]}onClose(t){this.on(Gt.close,t)}onError(t){return this.on(Gt.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let o=new Ms(this,t,function(){return e},r);return this.canPush()?o.send():(o.startTimeout(),this.pushBuffer.push(o)),o}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=qe.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Gt.close,"leave")},r=new Ms(this,Gt.leave,Tn({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,o){return this.topic!==t?!1:o&&o!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:o}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=qe.joining,this.joinPush.resend(t))}trigger(t,e,r,o){let n=this.onMessage(t,e,r,o);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(i=>i.event===t&&this.filterBindings(i,e,r));for(let i=0;i<s.length;i++)s[i].callback(n,r,o||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===qe.closed}isErrored(){return this.state===qe.errored}isJoined(){return this.state===qe.joined}isJoining(){return this.state===qe.joining}isLeaving(){return this.state===qe.leaving}},Fs=class{static request(t,e,r,o,n,s,i){if(Ot.XDomainRequest){let a=new Ot.XDomainRequest;return this.xdomainRequest(a,t,e,o,n,s,i)}else if(Ot.XMLHttpRequest){let a=new Ot.XMLHttpRequest;return this.xhrRequest(a,t,e,r,o,n,s,i)}else{if(Ot.fetch&&Ot.AbortController)return this.fetchRequest(t,e,r,o,n,s,i);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,o,n,s,i){let a={method:t,headers:r,body:o},l=null;if(n){l=new AbortController;let u=setTimeout(()=>l.abort(),n);a.signal=l.signal}return Ot.fetch(e,a).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>i&&i(u)).catch(u=>{u.name==="AbortError"&&s?s():i&&i(null)}),l}static xdomainRequest(t,e,r,o,n,s,i){return t.timeout=n,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);i&&i(a)},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(o),t}static xhrRequest(t,e,r,o,n,s,i,a){t.open(e,r,!0),t.timeout=s;for(let[l,u]of Object.entries(o))t.setRequestHeader(l,u);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===zy.complete&&a){let l=this.parseJSON(t.responseText);a(l)}},i&&(t.ontimeout=i),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=e?`${e}[${o}]`:o,s=t[o];typeof s=="object"?r.push(this.serialize(s,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(s))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},Ky=t=>{let e="",r=new Uint8Array(t),o=r.byteLength;for(let n=0;n<o;n++)e+=String.fromCharCode(r[n]);return btoa(e)},yo=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(xl)&&(this.authToken=atob(e[1].slice(xl.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=At.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Sl.websocket),"$1/"+Sl.longpoll)}endpointURL(){return Fs.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=At.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===At.open||this.readyState===At.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:o,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=o}else r=0;switch(r){case 200:n.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=At.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=Ky(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
10
|
+
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=At.closed;let o=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",o)):this.onclose(o)}ajax(t,e,r,o,n){let s,i=()=>{this.reqs.delete(s),o()};s=Fs.request(t,this.endpointURL(),e,r,this.timeout,i,a=>{this.reqs.delete(s),this.isActive()&&n(a)}),this.reqs.add(s)}},$s=class kn{constructor(e,r={}){let o=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(o.state,n=>{let{onJoin:s,onLeave:i,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=kn.syncState(this.state,n,s,i),this.pendingDiffs.forEach(l=>{this.state=kn.syncDiff(this.state,l,s,i)}),this.pendingDiffs=[],a()}),this.channel.on(o.diff,n=>{let{onJoin:s,onLeave:i,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=kn.syncDiff(this.state,n,s,i),a())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return kn.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,o,n){let s=this.clone(e),i={},a={};return this.map(s,(l,u)=>{r[l]||(a[l]=u)}),this.map(r,(l,u)=>{let c=s[l];if(c){let d=u.metas.map(g=>g.phx_ref),f=c.metas.map(g=>g.phx_ref),m=u.metas.filter(g=>f.indexOf(g.phx_ref)<0),h=c.metas.filter(g=>d.indexOf(g.phx_ref)<0);m.length>0&&(i[l]=u,i[l].metas=m),h.length>0&&(a[l]=this.clone(c),a[l].metas=h)}else i[l]=u}),this.syncDiff(s,{joins:i,leaves:a},o,n)}static syncDiff(e,r,o,n){let{joins:s,leaves:i}=this.clone(r);return o||(o=function(){}),n||(n=function(){}),this.map(s,(a,l)=>{let u=e[a];if(e[a]=this.clone(l),u){let c=e[a].metas.map(f=>f.phx_ref),d=u.metas.filter(f=>c.indexOf(f.phx_ref)<0);e[a].metas.unshift(...d)}o(a,u,l)}),this.map(i,(a,l)=>{let u=e[a];if(!u)return;let c=l.metas.map(d=>d.phx_ref);u.metas=u.metas.filter(d=>c.indexOf(d.phx_ref)<0),n(a,u,l),u.metas.length===0&&delete e[a]}),e}static list(e,r){return r||(r=function(o,n){return n}),this.map(e,(o,n)=>r(o,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(o=>r(o,e[o]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Us={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,o,n,s,i]=JSON.parse(t);return e({join_ref:r,ref:o,topic:n,event:s,payload:i})}},binaryEncode(t){let{join_ref:e,ref:r,event:o,topic:n,payload:s}=t,i=this.META_LENGTH+e.length+r.length+n.length+o.length,a=new ArrayBuffer(this.HEADER_LENGTH+i),l=new DataView(a),u=0;l.setUint8(u++,this.KINDS.push),l.setUint8(u++,e.length),l.setUint8(u++,r.length),l.setUint8(u++,n.length),l.setUint8(u++,o.length),Array.from(e,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(o,d=>l.setUint8(u++,d.charCodeAt(0)));var c=new Uint8Array(a.byteLength+s.byteLength);return c.set(new Uint8Array(a),0),c.set(new Uint8Array(s),a.byteLength),c.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),o=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,o);case this.KINDS.reply:return this.decodeReply(t,e,o);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,o)}},decodePush(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=e.getUint8(3),i=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(i,i+o));i=i+o;let l=r.decode(t.slice(i,i+n));i=i+n;let u=r.decode(t.slice(i,i+s));i=i+s;let c=t.slice(i,t.byteLength);return{join_ref:a,ref:null,topic:l,event:u,payload:c}},decodeReply(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=e.getUint8(3),i=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+o));a=a+o;let u=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+i));a=a+i;let f=t.slice(a,t.byteLength),m={status:d,response:f};return{join_ref:l,ref:u,topic:c,event:Gt.reply,payload:m}},decodeBroadcast(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=this.HEADER_LENGTH+2,i=r.decode(t.slice(s,s+o));s=s+o;let a=r.decode(t.slice(s,s+n));s=s+n;let l=t.slice(s,t.byteLength);return{join_ref:null,ref:null,topic:i,event:a,payload:l}}},Bs=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Wy,this.transport=e.transport||Ot.WebSocket||yo,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||Ot&&Ot.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Us.encode.bind(Us),this.defaultDecoder=Us.decode.bind(Us),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==yo?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;bo&&bo.addEventListener&&(bo.addEventListener("pagehide",o=>{this.conn&&(this.disconnect(),r=this.connectClock)}),bo.addEventListener("pageshow",o=>{r===this.connectClock&&(r=null,this.connect())}),bo.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=o=>e.rejoinAfterMs?e.rejoinAfterMs(o):[1e3,2e3,5e3][o-1]||1e4,this.reconnectAfterMs=o=>e.reconnectAfterMs?e.reconnectAfterMs(o):[10,50,100,150,200,250,500,1e3,2e3][o-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(o,n,s)=>{console.log(`${o}: ${n}`,s)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Tn(e.params||{}),this.endPoint=`${t}/${Sl.websocket}`,this.vsn=e.vsn||Vy,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new cd(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return yo}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Fs.appendParams(Fs.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Tn(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==yo?this.connectWithFallback(yo,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let o=this.onMessage(n=>{n.ref===e&&(this.off([o]),t(Date.now()-r))});return!0}transportName(t){return t===yo?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${xl}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,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)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,o=!0,n,s,i=this.transportName(t),a=l=>{this.log("transport",`falling back to ${i}...`,l),this.off([n,s]),o=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${i}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(l=>{this.log("transport","error",l),o&&!r&&(clearTimeout(this.fallbackTimer),a(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!o){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Hy,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();let o=this.conn;this.waitForBufferDone(o,()=>{e?o.close(e,r||""):o.close(),this.waitForSocketClosed(o,()=>{this.conn===o&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===At.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Gt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case At.connecting:return"connecting";case At.open:return"open";case At.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new Gy(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:o,ref:n,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${n})`,o)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:o,payload:n,ref:s,join_ref:i}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",a)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${o} ${s&&"("+s+")"||""}`.trim(),n);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(r,o,n,i)&&l.trigger(o,n,s,i)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,o])=>{try{o(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};var Cn=class t{constructor(e,r){let o=Yy(r);this.presence=new $s(e.getChannel(),o),this.presence.onJoin((n,s,i)=>{let a=t.onJoinPayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,s,i)=>{let a=t.onLeavePayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Jy(e),Object.getOwnPropertyNames(e).reduce((r,o)=>{let n=e[o];return r[o]=qs(n),r},{})}static onJoinPayload(e,r,o){let n=dd(r),s=qs(o);return{event:"join",key:e,currentPresences:n,newPresences:s}}static onLeavePayload(e,r,o){let n=dd(r),s=qs(o);return{event:"leave",key:e,currentPresences:n,leftPresences:s}}};function qs(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Jy(t){return JSON.parse(JSON.stringify(t))}function Yy(t){return t?.events&&{events:t.events}}function dd(t){return t?.metas?qs(t):[]}var kl;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(kl||(kl={}));var _o=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Cn(this.channel.channelAdapter,r)}};var En=class{constructor(e,r,o){let n=Xy(o);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,o){let n;try{n=this.channel.push(e,r,o)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>ld){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===Pt.joined}isJoined(){return this.state===Pt.joined}isJoining(){return this.state===Pt.joining}isClosed(){return this.state===Pt.closed}isLeaving(){return this.state===Pt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function Xy(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Tl;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Tl||(Tl={}));var wo;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(wo||(wo={}));var Rt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Rt||(Rt={}));var vo=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},o){var n,s;if(this.topic=e,this.params=r,this.socket=o,this.bindings={},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.channelAdapter=new En(this.socket.socketAdapter,e,this.params),this.presence=new _o(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=js(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||s===void 0)&&s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var o,n,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:l}}=this.params,u=(n=(o=this.bindings.postgres_changes)===null||o===void 0?void 0:o.map(m=>m.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[wo.PRESENCE]&&this.bindings[wo.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},f={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(Rt.CHANNEL_ERROR,m)}),this._onClose(()=>e?.(Rt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(Rt.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=Pt.errored,e?.(Rt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{e?.(Rt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var o;let n=this.bindings.postgres_changes,s=(o=n?.length)!==null&&o!==void 0?o:0,i=[];for(let a=0;a<s;a++){let l=n[a],{filter:{event:u,schema:c,table:d,filter:f}}=l,m=e&&e[a];if(m&&m.event===u&&t.isFilterValueEqual(m.schema,c)&&t.isFilterValueEqual(m.table,d)&&t.isFilterValueEqual(m.filter,f))i.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=Pt.errored,r?.(Rt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=Pt.errored&&r&&r(Rt.SUBSCRIBED)}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,o){if(this.channelAdapter.isJoined()&&e===wo.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,o)}async httpSend(e,r,o={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=o.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var o,n;if(!this.channelAdapter.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:s,payload:i}=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:s,payload:i,private:this.private}]})};try{let u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(o=r.timeout)!==null&&o!==void 0?o:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var i,a,l;let u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(i=this.params)===null||i===void 0?void 0:i.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,o){let n=new AbortController,s=setTimeout(()=>n.abort(),o),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(s),i}_on(e,r,o){let n=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,o),i={type:n,filter:r,callback:o,ref:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,o)=>{var n,s,i,a,l,u,c;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,o))return!1;let f=(n=this.bindings[d])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in f){let m=f.id,h=(s=f.filter)===null||s===void 0?void 0:s.event;return m&&((i=r.ids)===null||i===void 0?void 0:i.includes(m))&&(h==="*"||h?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let m=(u=(l=f?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((c=r?.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:o,error:n,leave:s,join:i}=Ns;return r&&[o,n,s,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,o)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:s,table:i,commit_timestamp:a,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:s,table:i,commit_timestamp:a,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=vl(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=vl(e.columns,e.old_record)),r}};var Pn=class{constructor(e,r){this.socket=new Bs(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,o,n=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),n),this.socket.disconnect(()=>{e(),s("ok")},r,o)})}push(e){this.socket.push(e)}log(e,r,o){this.socket.log(e,r,o)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Sn.connecting}isDisconnecting(){return this.socket.connectionState()==Sn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var Qy={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Zy=[1e3,2e3,5e3,1e4],eb=1e4,tb=`
|
|
11
11
|
addEventListener("message", (e) => {
|
|
12
12
|
if (e.data.event === "start") {
|
|
13
13
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
@@ -25,9 +25,9 @@ Option 2: Install and provide the "ws" package:
|
|
|
25
25
|
const client = new RealtimeClient(url, {
|
|
26
26
|
...options,
|
|
27
27
|
transport: ws
|
|
28
|
-
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async o=>{let n=await o.unsubscribe();return o.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,o){this.socketAdapter.log(e,r,o)}connectionState(){return this.socketAdapter.connectionState()||Sn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let o=`realtime:${e}`,n=this.getChannels().find(s=>s.topic===o);if(n)return n;{let s=new vo(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,o=!1;if(e)r=e,o=!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;o?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let s={access_token:r,version:rd};r&&n.updateJoinPayload(s),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Ns.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)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,o)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,o)}}_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.disconnect()},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)}_workerObjectUrl(e){let r;if(e)r=e;else{let o=new Blob([tb],{type:"application/javascript"});r=URL.createObjectURL(o)}return r}_initializeOptions(e){var r,o,n,s,i,a,l,u,c;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null;let d={};d.timeout=(n=e?.timeout)!==null&&n!==void 0?n:sd,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Qy.HEARTBEAT_INTERVAL,d.transport=(i=e?.transport)!==null&&i!==void 0?i:gl.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(g=>Zy[g-1]||eb);let f,m,h=(l=e?.vsn)!==null&&l!==void 0?l:nd;switch(h){case od:f=(g,y)=>y(JSON.stringify(g)),m=(g,y)=>y(JSON.parse(g));break;case yl:f=this.serializer.encode.bind(this.serializer),m=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=h,d.encode=(u=e?.encode)!==null&&u!==void 0?u:f,d.decode=(c=e?.decode)!==null&&c!==void 0?c:m,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var On=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 rb(t,e,r){let o=new URL(e,t);if(r)for(let[n,s]of Object.entries(r))s!==void 0&&o.searchParams.set(n,s);return o.toString()}async function ob(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 nb(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:o,query:n,body:s,headers:i}){let a=rb(t.baseUrl,o,n),l=await ob(t.auth),u=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...i},body:s?JSON.stringify(s):void 0}),c=await u.text(),d=(u.headers.get("content-type")||"").includes("application/json"),f=d&&c?JSON.parse(c):c;if(!u.ok){let m=d?f:void 0,h=m?.error;throw new On(h?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:h?.type,icebergCode:h?.code,details:m})}return{status:u.status,headers:u.headers,data:f}}}}function Vs(t){return t.join("")}var sb=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:Vs(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(o=>({namespace:o}))}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/${Vs(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Vs(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Vs(t.namespace)}`}),!0}catch(e){if(e instanceof On&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof On&&r.status===409)return;throw r}}};function xo(t){return t.join("")}var ib=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/${xo(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/${xo(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/${xo(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/${xo(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/${xo(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/${xo(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof On&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof On&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Ws=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=nb({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new sb(this.client,e),this.tableOps=new ib(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 Hs=class extends Error{constructor(t,e="storage",r,o){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=o}};function zs(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var kl=class extends Hs{constructor(t,e,r,o="storage"){super(t,o,e,r),this.name=o==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},md=class extends Hs{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var ab=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),lb=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)},Tl=t=>{if(Array.isArray(t))return t.map(r=>Tl(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,o])=>{let n=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[n]=Tl(o)}),e},ub=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function Rn(t){"@babel/helpers - typeof";return Rn=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},Rn(t)}function cb(t,e){if(Rn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Rn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function db(t){var e=cb(t,"string");return Rn(e)=="symbol"?e:e+""}function fb(t,e,r){return(e=db(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function cd(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function I(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?cd(Object(r),!0).forEach(function(o){fb(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):cd(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var dd=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)},mb=async(t,e,r,o)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let n=t,s=parseInt(n.status,10);Number.isFinite(s)||(s=500),n.json().then(i=>{let a=i?.statusCode||i?.code||s+"";e(new kl(dd(i),s,a,o))}).catch(()=>{let i=s+"";e(new kl(n.statusText||`HTTP ${s} error`,s,i,o))})}else e(new md(dd(t),t,o))},hb=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!o?I(I({},n),r):(lb(o)?(n.headers=I({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(o)):n.body=o,e?.duplex&&(n.duplex=e.duplex),I(I({},n),r))};async function An(t,e,r,o,n,s,i){return new Promise((a,l)=>{t(r,hb(e,o,n,s)).then(u=>{if(!u.ok)throw u;if(o?.noResolveJson)return u;if(i==="vectors"){let c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>mb(u,l,o,i))})}function hd(t="storage"){return{get:async(e,r,o,n)=>An(e,"GET",r,o,n,void 0,t),post:async(e,r,o,n,s)=>An(e,"POST",r,n,s,o,t),put:async(e,r,o,n,s)=>An(e,"PUT",r,n,s,o,t),head:async(e,r,o,n)=>An(e,"HEAD",r,I(I({},o),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,o,n,s)=>An(e,"DELETE",r,n,s,o,t)}}var pb=hd("storage"),{get:In,post:gt,put:Cl,head:gb,remove:El}=pb,Ge=hd("vectors"),ko=class{constructor(t,e={},r,o="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=ab(r),this.namespace=o}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=I(I({},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(zs(r))return{data:null,error:r};throw r}}},yb=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(zs(e))return{data:null,error:e};throw e}}},pd;pd=Symbol.toStringTag;var bb=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[pd]="BlobDownloadBuilder",this.promise=null}asStream(){return new yb(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(zs(e))return{data:null,error:e};throw e}}},_b={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},fd={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},wb=class extends ko{constructor(t,e={},r,o){super(t,e,o,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,o){var n=this;return n.handleOperation(async()=>{let s,i=I(I({},fd),o),a=I(I({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)}),l=i.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",i.cacheControl),l&&s.append("metadata",n.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",i.cacheControl),l&&!s.has("metadata")&&s.append("metadata",n.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${i.cacheControl}`,a["content-type"]=i.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!i.duplex&&(i.duplex="half")),o?.headers&&(a=I(I({},a),o.headers));let u=n._removeEmptyFolders(e),c=n._getFinalPath(u),d=await(t=="PUT"?Cl:gt)(n.fetch,`${n.url}/object/${c}`,s,I({headers:a},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,o){var n=this;let s=n._removeEmptyFolders(t),i=n._getFinalPath(s),a=new URL(n.url+`/object/upload/sign/${i}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,u=I(I({},fd),o),c=I(I({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:s,fullPath:(await Cl(n.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let o=r._getFinalPath(t),n=I({},r.headers);e?.upsert&&(n["x-upsert"]="true");let s=await gt(r.fetch,`${r.url}/object/upload/sign/${o}`,{},{headers:n}),i=new URL(r.url+s.url),a=i.searchParams.get("token");if(!a)throw new Hs("No token returned by API");return{signedUrl:i.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var o=this;return o.handleOperation(async()=>await gt(o.fetch,`${o.url}/object/move`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers}))}async copy(t,e,r){var o=this;return o.handleOperation(async()=>({path:(await gt(o.fetch,`${o.url}/object/copy`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers})).Key}))}async createSignedUrl(t,e,r){var o=this;return o.handleOperation(async()=>{let n=o._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,i=await gt(o.fetch,`${o.url}/object/sign/${n}`,I({expiresIn:e},s?{transform:r.transform}:{}),{headers:o.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",l=s&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${o.url}${l}${a}`)}})}async createSignedUrls(t,e,r){var o=this;return o.handleOperation(async()=>{let n=await gt(o.fetch,`${o.url}/object/sign/${o.bucketId}`,{expiresIn:e,paths:t},{headers:o.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(i=>I(I({},i),{},{signedUrl:i.signedURL?encodeURI(`${o.url}${i.signedURL}${s}`):null}))})}download(t,e,r){let o=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),s=n?`?${n}`:"",i=this._getFinalPath(t),a=()=>In(this.fetch,`${this.url}/${o}/${i}${s}`,{headers:this.headers,noResolveJson:!0},r);return new bb(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>Tl(await In(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await gb(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(zs(n)){var o;let s=n instanceof kl?n.status:n instanceof md?(o=n.originalError)===null||o===void 0?void 0:o.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),o=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&o.push(n);let s=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&o.push(i);let a=o.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await El(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var o=this;return o.handleOperation(async()=>{let n=I(I(I({},_b),e),{},{prefix:t||""});return await gt(o.fetch,`${o.url}/object/list/${o.bucketId}`,n,{headers:o.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let o=I({},t);return await gt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,o,{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("&")}},vb="2.100.1",Dn={"X-Client-Info":`storage-js/${vb}`},Sb=class extends ko{constructor(t,e={},r,o){let n=new URL(t);o?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let s=n.href.replace(/\/$/,""),i=I(I({},Dn),e);super(s,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await In(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await In(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await gt(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 Cl(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 gt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await El(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():""}},xb=class extends ko{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},Dn),e);super(o,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await gt(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 o=r.toString(),n=o?`${e.url}/bucket?${o}`:`${e.url}/bucket`;return await In(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await El(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!ub(t))throw new Hs("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 Ws({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),o=this.shouldThrowOnError;return new Proxy(r,{get(n,s){let i=n[s];return typeof i!="function"?i:async(...a)=>{try{return{data:await i.apply(n,a),error:null}}catch(l){if(o)throw l;return{data:null,error:l}}}}})}},kb=class extends ko{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},Dn),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ge.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ge.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Tb=class extends ko{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},Dn),{},{"Content-Type":"application/json"},e);super(o,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 Ge.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ge.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 Ge.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ge.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 Ge.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Cb=class extends ko{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},Dn),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Eb=class extends Cb{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Pb(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)}},Pb=class extends kb{constructor(t,e,r,o){super(t,e,o),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,I(I({},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 Ob(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Ob=class extends Tb{constructor(t,e,r,o,n){super(t,e,n),this.vectorBucketName=r,this.indexName=o}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},gd=class extends Sb{constructor(t,e={},r,o){super(t,e,r,o)}from(t){return new wb(this.url,this.headers,t,this.fetch)}get vectors(){return new Eb(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new xb(this.url+"/iceberg",this.headers,this.fetch)}};var Gs="2.100.1";var Ar=30*1e3,Ks=3,Js=Ks*Ar,yd="http://localhost:9999",bd="supabase.auth.token";var _d={"X-Client-Info":`gotrue-js/${Gs}`};var Ln="X-Supabase-Api-Version",Pl={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},wd=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,vd=600*1e3;var fr=class extends Error{constructor(e,r,o){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=o}};function k(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Ys=class extends fr{constructor(e,r,o){super(e,r,o),this.name="AuthApiError",this.status=r,this.code=o}};function Sd(t){return k(t)&&t.name==="AuthApiError"}var nt=class extends fr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},yt=class extends fr{constructor(e,r,o,n){super(e,o,n),this.name=r,this.status=o}},Pe=class extends yt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function Qs(t){return k(t)&&t.name==="AuthSessionMissingError"}var Kt=class extends yt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Rr=class extends yt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Ir=class extends yt{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}}};function xd(t){return k(t)&&t.name==="AuthImplicitGrantRedirectError"}var Nn=class extends yt{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}}},Xs=class extends yt{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")}};var To=class extends yt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function Zs(t){return k(t)&&t.name==="AuthRetryableFetchError"}var jn=class extends yt{constructor(e,r,o){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=o}};var Dr=class extends yt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),kd=`
|
|
29
|
-
\r=`.split(""),Ab=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<kd.length;e+=1)t[kd[e].charCodeAt(0)]=-2;for(let e=0;e<ei.length;e+=1)t[ei[e].charCodeAt(0)]=e;return t})();function Td(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(ei[o]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(ei[o]),e.queuedBits-=6}}function Cd(t,e,r){let o=Ab[t];if(o>-1)for(e.queue=e.queue<<6|o,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(o===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Ol(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},s=i=>{Db(i,o,r)};for(let i=0;i<t.length;i+=1)Cd(t.charCodeAt(i),n,s);return e.join("")}function Rb(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 Ib(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}Rb(o,e)}}function Db(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;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 mr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)Cd(t.charCodeAt(n),r,o);return new Uint8Array(e)}function Ed(t){let e=[];return Ib(t,r=>e.push(r)),new Uint8Array(e)}function Jt(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};return t.forEach(n=>Td(n,r,o)),Td(null,r,o),e.join("")}function Pd(t){return Math.round(Date.now()/1e3)+t}function Od(){return Symbol("auth-callback")}var be=()=>typeof window<"u"&&typeof document<"u",Lr={tested:!1,writable:!1},ti=()=>{if(!be())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Lr.tested)return Lr.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Lr.tested=!0,Lr.writable=!0}catch{Lr.tested=!0,Lr.writable=!1}return Lr.writable};function Ad(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,s)=>{e[s]=n})}catch{}return r.searchParams.forEach((o,n)=>{e[n]=o}),e}var ri=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Rd=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Nr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},hr=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Te=async(t,e)=>{await t.removeItem(e)},Mn=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};Mn.promiseConstructor=Promise;function Un(t){let e=t.split(".");if(e.length!==3)throw new Dr("Invalid JWT structure");for(let o=0;o<e.length;o++)if(!wd.test(e[o]))throw new Dr("JWT not in base64url format");return{header:JSON.parse(Ol(e[0])),payload:JSON.parse(Ol(e[1])),signature:mr(e[2]),raw:{header:e[0],payload:e[1]}}}async function Id(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Dd(t,e){return new Promise((o,n)=>{(async()=>{for(let s=0;s<1/0;s++)try{let i=await t(s);if(!e(s,null,i)){o(i);return}}catch(i){if(!e(s,i)){n(i);return}}})()})}function Lb(t){return("0"+t.toString(16)).substr(-2)}function Nb(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=r.length,n="";for(let s=0;s<56;s++)n+=r.charAt(Math.floor(Math.random()*o));return n}return crypto.getRandomValues(e),Array.from(e,Lb).join("")}async function jb(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(o);return Array.from(n).map(s=>String.fromCharCode(s)).join("")}async function Mb(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 jb(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function jr(t,e,r=!1){let o=Nb(),n=o;r&&(n+="/PASSWORD_RECOVERY"),await Nr(t,`${e}-code-verifier`,n);let s=await Mb(o);return[s,o===s?"plain":"s256"]}var Ub=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ld(t){let e=t.headers.get(Ln);if(!e||!e.match(Ub))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Nd(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 jd(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 Fb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Mr(t){if(!Fb.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function oi(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let o=r.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="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 Md(t,e){return new Proxy(t,{get:(r,o,n)=>{if(o==="__isInsecureUserWarningProxy")return!0;if(typeof o=="symbol"){let s=o.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,o,n)}return!e.value&&typeof o=="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,o,n)}})}function Al(t){return JSON.parse(JSON.stringify(t))}var Ur=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),$b=[502,503,504];async function Ud(t){var e;if(!Rd(t))throw new To(Ur(t),0);if($b.includes(t.status))throw new To(Ur(t),t.status);let r;try{r=await t.json()}catch(s){throw new nt(Ur(s),s)}let o,n=Ld(t);if(n&&n.getTime()>=Pl["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?o=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(o=r.error_code),o){if(o==="weak_password")throw new jn(Ur(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(o==="session_not_found")throw new Pe}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((s,i)=>s&&typeof i=="string",!0))throw new jn(Ur(r),t.status,r.weak_password.reasons);throw new Ys(Ur(r),t.status||500,o)}var Bb=(t,e,r,o)=>{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(o),Object.assign(Object.assign({},n),r))};async function O(t,e,r,o){var n;let s=Object.assign({},o?.headers);s[Ln]||(s[Ln]=Pl["2024-01-01"].name),o?.jwt&&(s.Authorization=`Bearer ${o.jwt}`);let i=(n=o?.query)!==null&&n!==void 0?n:{};o?.redirectTo&&(i.redirect_to=o.redirectTo);let a=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await qb(t,e,r+a,{headers:s,noResolveJson:o?.noResolveJson},{},o?.body);return o?.xform?o?.xform(l):{data:Object.assign({},l),error:null}}async function qb(t,e,r,o,n,s){let i=Bb(e,o,n,s),a;try{a=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new To(Ur(l),0)}if(a.ok||await Ud(a),o?.noResolveJson)return a;try{return await a.json()}catch(l){await Ud(l)}}function st(t){var e;let r=null;Vb(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Pd(t.expires_in)));let o=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:o},error:null}}function Rl(t){let e=st(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,o)=>r&&typeof o=="string",!0)&&(e.data.weak_password=t.weak_password),e}function It(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Fd(t){return{data:t,error:null}}function $d(t){let{action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s}=t,i=Be(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s},l=Object.assign({},i);return{data:{properties:a,user:l},error:null}}function Il(t){return t}function Vb(t){return t.access_token&&t.refresh_token&&t.expires_in}var ni=["global","local","others"];var Fr=class{constructor({url:e="",headers:r={},fetch:o}){this.url=e,this.headers=r,this.fetch=ri(o),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)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,r=ni[0]){if(ni.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ni.join(", ")}`);try{return await O(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(o){if(k(o))return{data:null,error:o};throw o}}async inviteUserByEmail(e,r={}){try{return await O(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:It})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async generateLink(e){try{let{options:r}=e,o=Be(e,["options"]),n=Object.assign(Object.assign({},o),r);return"newEmail"in o&&(n.new_email=o?.newEmail,delete n.newEmail),await O(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:$d,redirectTo:r?.redirectTo})}catch(r){if(k(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await O(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:It})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await O(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:Il});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(k(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Mr(e);try{return await O(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:It})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Mr(e);try{return await O(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:It})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async deleteUser(e,r=!1){Mr(e);try{return await O(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:It})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async _listFactors(e){Mr(e.userId);try{let{data:r,error:o}=await O(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:o}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Mr(e.userId),Mr(e.id);try{return{data:await O(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await O(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:Il});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(k(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await O(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await O(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await O(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(k(o))return{data:null,error:o};throw o}}async _deleteOAuthClient(e){try{return await O(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await O(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await O(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:o=>{var n;return{data:{providers:(n=o?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(k(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await O(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await O(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await O(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(k(o))return{data:null,error:o};throw o}}async _deleteCustomProvider(e){try{return await O(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}};function Dl(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var bt={debug:!!(globalThis&&ti()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Co=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Fn=class extends Co{},Ll=class extends Co{};async function Nl(t,e,r){bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let o=new globalThis.AbortController,n;e>0&&(n=setTimeout(()=>{o.abort(),bt.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:o.signal},async s=>{if(s){clearTimeout(n),bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Fn(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(bt.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"),clearTimeout(n),await r()}})}catch(s){if(e>0&&clearTimeout(n),s?.name==="AbortError"&&e>0){if(o.signal.aborted)return bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async i=>{if(i){bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Fn(`Lock "${t}" was released because another request stole it`)}throw s}}var Bd={};async function jl(t,e,r){var o;let n=(o=Bd[t])!==null&&o!==void 0?o:Promise.resolve(),s=(async()=>{try{return await n,null}catch{return null}})(),i=(async()=>{let a=null;try{let l=e>=0?new Promise((u,c)=>{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.`),c(new Ll(`Acquiring process lock with name "${t}" timed out`))},e)}):null;await Promise.race([s,l].filter(u=>u)),a!==null&&clearTimeout(a)}catch(l){if(a!==null&&clearTimeout(a),l&&l.isAcquireTimeout)throw l}return await r()})();return Bd[t]=(async()=>{try{return await i}catch(a){if(a&&a.isAcquireTimeout){try{await n}catch{}return null}throw a}})(),await i}function qd(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function Ml(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Vd(t){return parseInt(t,16)}function Wd(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}function Hd(t){var e;let{chainId:r,domain:o,expirationTime:n,issuedAt:s=new Date,nonce:i,notBefore:a,requestId:l,resources:u,scheme:c,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(!o)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);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(`
|
|
30
|
-
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let m=
|
|
28
|
+
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async o=>{let n=await o.unsubscribe();return o.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,o){this.socketAdapter.log(e,r,o)}connectionState(){return this.socketAdapter.connectionState()||Sn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let o=`realtime:${e}`,n=this.getChannels().find(s=>s.topic===o);if(n)return n;{let s=new vo(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,o=!1;if(e)r=e,o=!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;o?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let s={access_token:r,version:nd};r&&n.updateJoinPayload(s),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Ns.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)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,o)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,o)}}_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.disconnect()},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)}_workerObjectUrl(e){let r;if(e)r=e;else{let o=new Blob([tb],{type:"application/javascript"});r=URL.createObjectURL(o)}return r}_initializeOptions(e){var r,o,n,s,i,a,l,u,c;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null;let d={};d.timeout=(n=e?.timeout)!==null&&n!==void 0?n:ad,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Qy.HEARTBEAT_INTERVAL,d.transport=(i=e?.transport)!==null&&i!==void 0?i:bl.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(g=>Zy[g-1]||eb);let f,m,h=(l=e?.vsn)!==null&&l!==void 0?l:id;switch(h){case sd:f=(g,y)=>y(JSON.stringify(g)),m=(g,y)=>y(JSON.parse(g));break;case _l:f=this.serializer.encode.bind(this.serializer),m=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=h,d.encode=(u=e?.encode)!==null&&u!==void 0?u:f,d.decode=(c=e?.decode)!==null&&c!==void 0?c:m,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var On=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 rb(t,e,r){let o=new URL(e,t);if(r)for(let[n,s]of Object.entries(r))s!==void 0&&o.searchParams.set(n,s);return o.toString()}async function ob(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 nb(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:o,query:n,body:s,headers:i}){let a=rb(t.baseUrl,o,n),l=await ob(t.auth),u=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...i},body:s?JSON.stringify(s):void 0}),c=await u.text(),d=(u.headers.get("content-type")||"").includes("application/json"),f=d&&c?JSON.parse(c):c;if(!u.ok){let m=d?f:void 0,h=m?.error;throw new On(h?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:h?.type,icebergCode:h?.code,details:m})}return{status:u.status,headers:u.headers,data:f}}}}function Vs(t){return t.join("")}var sb=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:Vs(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(o=>({namespace:o}))}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/${Vs(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Vs(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Vs(t.namespace)}`}),!0}catch(e){if(e instanceof On&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof On&&r.status===409)return;throw r}}};function xo(t){return t.join("")}var ib=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/${xo(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/${xo(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/${xo(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/${xo(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/${xo(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/${xo(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof On&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof On&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Ws=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=nb({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new sb(this.client,e),this.tableOps=new ib(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 Hs=class extends Error{constructor(t,e="storage",r,o){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=o}};function zs(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Cl=class extends Hs{constructor(t,e,r,o="storage"){super(t,o,e,r),this.name=o==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},pd=class extends Hs{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var ab=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),lb=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)},El=t=>{if(Array.isArray(t))return t.map(r=>El(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,o])=>{let n=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[n]=El(o)}),e},ub=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function Rn(t){"@babel/helpers - typeof";return Rn=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},Rn(t)}function cb(t,e){if(Rn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Rn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function db(t){var e=cb(t,"string");return Rn(e)=="symbol"?e:e+""}function fb(t,e,r){return(e=db(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function fd(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function I(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?fd(Object(r),!0).forEach(function(o){fb(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):fd(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var md=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)},mb=async(t,e,r,o)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let n=t,s=parseInt(n.status,10);Number.isFinite(s)||(s=500),n.json().then(i=>{let a=i?.statusCode||i?.code||s+"";e(new Cl(md(i),s,a,o))}).catch(()=>{let i=s+"";e(new Cl(n.statusText||`HTTP ${s} error`,s,i,o))})}else e(new pd(md(t),t,o))},hb=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!o?I(I({},n),r):(lb(o)?(n.headers=I({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(o)):n.body=o,e?.duplex&&(n.duplex=e.duplex),I(I({},n),r))};async function An(t,e,r,o,n,s,i){return new Promise((a,l)=>{t(r,hb(e,o,n,s)).then(u=>{if(!u.ok)throw u;if(o?.noResolveJson)return u;if(i==="vectors"){let c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>mb(u,l,o,i))})}function gd(t="storage"){return{get:async(e,r,o,n)=>An(e,"GET",r,o,n,void 0,t),post:async(e,r,o,n,s)=>An(e,"POST",r,n,s,o,t),put:async(e,r,o,n,s)=>An(e,"PUT",r,n,s,o,t),head:async(e,r,o,n)=>An(e,"HEAD",r,I(I({},o),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,o,n,s)=>An(e,"DELETE",r,n,s,o,t)}}var pb=gd("storage"),{get:In,post:gt,put:Pl,head:gb,remove:Ol}=pb,Ge=gd("vectors"),ko=class{constructor(t,e={},r,o="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=ab(r),this.namespace=o}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=I(I({},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(zs(r))return{data:null,error:r};throw r}}},yb=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(zs(e))return{data:null,error:e};throw e}}},yd;yd=Symbol.toStringTag;var bb=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[yd]="BlobDownloadBuilder",this.promise=null}asStream(){return new yb(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(zs(e))return{data:null,error:e};throw e}}},_b={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},hd={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},wb=class extends ko{constructor(t,e={},r,o){super(t,e,o,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,o){var n=this;return n.handleOperation(async()=>{let s,i=I(I({},hd),o),a=I(I({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)}),l=i.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",i.cacheControl),l&&s.append("metadata",n.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",i.cacheControl),l&&!s.has("metadata")&&s.append("metadata",n.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${i.cacheControl}`,a["content-type"]=i.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!i.duplex&&(i.duplex="half")),o?.headers&&(a=I(I({},a),o.headers));let u=n._removeEmptyFolders(e),c=n._getFinalPath(u),d=await(t=="PUT"?Pl:gt)(n.fetch,`${n.url}/object/${c}`,s,I({headers:a},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,o){var n=this;let s=n._removeEmptyFolders(t),i=n._getFinalPath(s),a=new URL(n.url+`/object/upload/sign/${i}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,u=I(I({},hd),o),c=I(I({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:s,fullPath:(await Pl(n.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let o=r._getFinalPath(t),n=I({},r.headers);e?.upsert&&(n["x-upsert"]="true");let s=await gt(r.fetch,`${r.url}/object/upload/sign/${o}`,{},{headers:n}),i=new URL(r.url+s.url),a=i.searchParams.get("token");if(!a)throw new Hs("No token returned by API");return{signedUrl:i.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var o=this;return o.handleOperation(async()=>await gt(o.fetch,`${o.url}/object/move`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers}))}async copy(t,e,r){var o=this;return o.handleOperation(async()=>({path:(await gt(o.fetch,`${o.url}/object/copy`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers})).Key}))}async createSignedUrl(t,e,r){var o=this;return o.handleOperation(async()=>{let n=o._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,i=await gt(o.fetch,`${o.url}/object/sign/${n}`,I({expiresIn:e},s?{transform:r.transform}:{}),{headers:o.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",l=s&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${o.url}${l}${a}`)}})}async createSignedUrls(t,e,r){var o=this;return o.handleOperation(async()=>{let n=await gt(o.fetch,`${o.url}/object/sign/${o.bucketId}`,{expiresIn:e,paths:t},{headers:o.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(i=>I(I({},i),{},{signedUrl:i.signedURL?encodeURI(`${o.url}${i.signedURL}${s}`):null}))})}download(t,e,r){let o=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),s=n?`?${n}`:"",i=this._getFinalPath(t),a=()=>In(this.fetch,`${this.url}/${o}/${i}${s}`,{headers:this.headers,noResolveJson:!0},r);return new bb(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>El(await In(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await gb(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(zs(n)){var o;let s=n instanceof Cl?n.status:n instanceof pd?(o=n.originalError)===null||o===void 0?void 0:o.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),o=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&o.push(n);let s=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&o.push(i);let a=o.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await Ol(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var o=this;return o.handleOperation(async()=>{let n=I(I(I({},_b),e),{},{prefix:t||""});return await gt(o.fetch,`${o.url}/object/list/${o.bucketId}`,n,{headers:o.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let o=I({},t);return await gt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,o,{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("&")}},vb="2.100.1",Dn={"X-Client-Info":`storage-js/${vb}`},Sb=class extends ko{constructor(t,e={},r,o){let n=new URL(t);o?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let s=n.href.replace(/\/$/,""),i=I(I({},Dn),e);super(s,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await In(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await In(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await gt(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 Pl(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 gt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ol(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():""}},xb=class extends ko{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},Dn),e);super(o,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await gt(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 o=r.toString(),n=o?`${e.url}/bucket?${o}`:`${e.url}/bucket`;return await In(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ol(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!ub(t))throw new Hs("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 Ws({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),o=this.shouldThrowOnError;return new Proxy(r,{get(n,s){let i=n[s];return typeof i!="function"?i:async(...a)=>{try{return{data:await i.apply(n,a),error:null}}catch(l){if(o)throw l;return{data:null,error:l}}}}})}},kb=class extends ko{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},Dn),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ge.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ge.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Tb=class extends ko{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},Dn),{},{"Content-Type":"application/json"},e);super(o,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 Ge.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ge.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 Ge.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ge.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 Ge.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Cb=class extends ko{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},Dn),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ge.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Eb=class extends Cb{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Pb(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)}},Pb=class extends kb{constructor(t,e,r,o){super(t,e,o),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,I(I({},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 Ob(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Ob=class extends Tb{constructor(t,e,r,o,n){super(t,e,n),this.vectorBucketName=r,this.indexName=o}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},bd=class extends Sb{constructor(t,e={},r,o){super(t,e,r,o)}from(t){return new wb(this.url,this.headers,t,this.fetch)}get vectors(){return new Eb(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new xb(this.url+"/iceberg",this.headers,this.fetch)}};var Gs="2.100.1";var Ar=30*1e3,Ks=3,Js=Ks*Ar,_d="http://localhost:9999",wd="supabase.auth.token";var vd={"X-Client-Info":`gotrue-js/${Gs}`};var Ln="X-Supabase-Api-Version",Al={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Sd=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,xd=600*1e3;var fr=class extends Error{constructor(e,r,o){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=o}};function k(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Ys=class extends fr{constructor(e,r,o){super(e,r,o),this.name="AuthApiError",this.status=r,this.code=o}};function kd(t){return k(t)&&t.name==="AuthApiError"}var nt=class extends fr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},yt=class extends fr{constructor(e,r,o,n){super(e,o,n),this.name=r,this.status=o}},Pe=class extends yt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function Qs(t){return k(t)&&t.name==="AuthSessionMissingError"}var Kt=class extends yt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Rr=class extends yt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Ir=class extends yt{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}}};function Td(t){return k(t)&&t.name==="AuthImplicitGrantRedirectError"}var Nn=class extends yt{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}}},Xs=class extends yt{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")}};var To=class extends yt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function Zs(t){return k(t)&&t.name==="AuthRetryableFetchError"}var jn=class extends yt{constructor(e,r,o){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=o}};var Dr=class extends yt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Cd=`
|
|
29
|
+
\r=`.split(""),Ab=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Cd.length;e+=1)t[Cd[e].charCodeAt(0)]=-2;for(let e=0;e<ei.length;e+=1)t[ei[e].charCodeAt(0)]=e;return t})();function Ed(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(ei[o]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(ei[o]),e.queuedBits-=6}}function Pd(t,e,r){let o=Ab[t];if(o>-1)for(e.queue=e.queue<<6|o,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(o===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Rl(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},s=i=>{Db(i,o,r)};for(let i=0;i<t.length;i+=1)Pd(t.charCodeAt(i),n,s);return e.join("")}function Rb(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 Ib(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}Rb(o,e)}}function Db(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;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 mr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)Pd(t.charCodeAt(n),r,o);return new Uint8Array(e)}function Od(t){let e=[];return Ib(t,r=>e.push(r)),new Uint8Array(e)}function Jt(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};return t.forEach(n=>Ed(n,r,o)),Ed(null,r,o),e.join("")}function Ad(t){return Math.round(Date.now()/1e3)+t}function Rd(){return Symbol("auth-callback")}var be=()=>typeof window<"u"&&typeof document<"u",Lr={tested:!1,writable:!1},ti=()=>{if(!be())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Lr.tested)return Lr.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Lr.tested=!0,Lr.writable=!0}catch{Lr.tested=!0,Lr.writable=!1}return Lr.writable};function Id(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,s)=>{e[s]=n})}catch{}return r.searchParams.forEach((o,n)=>{e[n]=o}),e}var ri=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Dd=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Nr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},hr=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Te=async(t,e)=>{await t.removeItem(e)},Mn=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};Mn.promiseConstructor=Promise;function Un(t){let e=t.split(".");if(e.length!==3)throw new Dr("Invalid JWT structure");for(let o=0;o<e.length;o++)if(!Sd.test(e[o]))throw new Dr("JWT not in base64url format");return{header:JSON.parse(Rl(e[0])),payload:JSON.parse(Rl(e[1])),signature:mr(e[2]),raw:{header:e[0],payload:e[1]}}}async function Ld(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Nd(t,e){return new Promise((o,n)=>{(async()=>{for(let s=0;s<1/0;s++)try{let i=await t(s);if(!e(s,null,i)){o(i);return}}catch(i){if(!e(s,i)){n(i);return}}})()})}function Lb(t){return("0"+t.toString(16)).substr(-2)}function Nb(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=r.length,n="";for(let s=0;s<56;s++)n+=r.charAt(Math.floor(Math.random()*o));return n}return crypto.getRandomValues(e),Array.from(e,Lb).join("")}async function jb(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(o);return Array.from(n).map(s=>String.fromCharCode(s)).join("")}async function Mb(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 jb(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function jr(t,e,r=!1){let o=Nb(),n=o;r&&(n+="/PASSWORD_RECOVERY"),await Nr(t,`${e}-code-verifier`,n);let s=await Mb(o);return[s,o===s?"plain":"s256"]}var Ub=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function jd(t){let e=t.headers.get(Ln);if(!e||!e.match(Ub))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Md(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 Ud(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 Fb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Mr(t){if(!Fb.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function oi(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let o=r.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="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 Fd(t,e){return new Proxy(t,{get:(r,o,n)=>{if(o==="__isInsecureUserWarningProxy")return!0;if(typeof o=="symbol"){let s=o.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,o,n)}return!e.value&&typeof o=="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,o,n)}})}function Il(t){return JSON.parse(JSON.stringify(t))}var Ur=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),$b=[502,503,504];async function $d(t){var e;if(!Dd(t))throw new To(Ur(t),0);if($b.includes(t.status))throw new To(Ur(t),t.status);let r;try{r=await t.json()}catch(s){throw new nt(Ur(s),s)}let o,n=jd(t);if(n&&n.getTime()>=Al["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?o=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(o=r.error_code),o){if(o==="weak_password")throw new jn(Ur(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(o==="session_not_found")throw new Pe}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((s,i)=>s&&typeof i=="string",!0))throw new jn(Ur(r),t.status,r.weak_password.reasons);throw new Ys(Ur(r),t.status||500,o)}var Bb=(t,e,r,o)=>{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(o),Object.assign(Object.assign({},n),r))};async function O(t,e,r,o){var n;let s=Object.assign({},o?.headers);s[Ln]||(s[Ln]=Al["2024-01-01"].name),o?.jwt&&(s.Authorization=`Bearer ${o.jwt}`);let i=(n=o?.query)!==null&&n!==void 0?n:{};o?.redirectTo&&(i.redirect_to=o.redirectTo);let a=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await qb(t,e,r+a,{headers:s,noResolveJson:o?.noResolveJson},{},o?.body);return o?.xform?o?.xform(l):{data:Object.assign({},l),error:null}}async function qb(t,e,r,o,n,s){let i=Bb(e,o,n,s),a;try{a=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new To(Ur(l),0)}if(a.ok||await $d(a),o?.noResolveJson)return a;try{return await a.json()}catch(l){await $d(l)}}function st(t){var e;let r=null;Vb(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Ad(t.expires_in)));let o=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:o},error:null}}function Dl(t){let e=st(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,o)=>r&&typeof o=="string",!0)&&(e.data.weak_password=t.weak_password),e}function It(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Bd(t){return{data:t,error:null}}function qd(t){let{action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s}=t,i=Be(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s},l=Object.assign({},i);return{data:{properties:a,user:l},error:null}}function Ll(t){return t}function Vb(t){return t.access_token&&t.refresh_token&&t.expires_in}var ni=["global","local","others"];var Fr=class{constructor({url:e="",headers:r={},fetch:o}){this.url=e,this.headers=r,this.fetch=ri(o),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)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,r=ni[0]){if(ni.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ni.join(", ")}`);try{return await O(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(o){if(k(o))return{data:null,error:o};throw o}}async inviteUserByEmail(e,r={}){try{return await O(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:It})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async generateLink(e){try{let{options:r}=e,o=Be(e,["options"]),n=Object.assign(Object.assign({},o),r);return"newEmail"in o&&(n.new_email=o?.newEmail,delete n.newEmail),await O(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:qd,redirectTo:r?.redirectTo})}catch(r){if(k(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await O(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:It})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await O(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:Ll});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(k(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Mr(e);try{return await O(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:It})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Mr(e);try{return await O(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:It})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async deleteUser(e,r=!1){Mr(e);try{return await O(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:It})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async _listFactors(e){Mr(e.userId);try{let{data:r,error:o}=await O(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:o}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Mr(e.userId),Mr(e.id);try{return{data:await O(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await O(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:Ll});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(k(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await O(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await O(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await O(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(k(o))return{data:null,error:o};throw o}}async _deleteOAuthClient(e){try{return await O(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await O(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await O(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:o=>{var n;return{data:{providers:(n=o?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(k(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await O(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await O(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await O(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(k(o))return{data:null,error:o};throw o}}async _deleteCustomProvider(e){try{return await O(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}};function Nl(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var bt={debug:!!(globalThis&&ti()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Co=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Fn=class extends Co{},jl=class extends Co{};async function Ml(t,e,r){bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let o=new globalThis.AbortController,n;e>0&&(n=setTimeout(()=>{o.abort(),bt.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:o.signal},async s=>{if(s){clearTimeout(n),bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Fn(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(bt.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"),clearTimeout(n),await r()}})}catch(s){if(e>0&&clearTimeout(n),s?.name==="AbortError"&&e>0){if(o.signal.aborted)return bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async i=>{if(i){bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw bt.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Fn(`Lock "${t}" was released because another request stole it`)}throw s}}var Vd={};async function Ul(t,e,r){var o;let n=(o=Vd[t])!==null&&o!==void 0?o:Promise.resolve(),s=(async()=>{try{return await n,null}catch{return null}})(),i=(async()=>{let a=null;try{let l=e>=0?new Promise((u,c)=>{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.`),c(new jl(`Acquiring process lock with name "${t}" timed out`))},e)}):null;await Promise.race([s,l].filter(u=>u)),a!==null&&clearTimeout(a)}catch(l){if(a!==null&&clearTimeout(a),l&&l.isAcquireTimeout)throw l}return await r()})();return Vd[t]=(async()=>{try{return await i}catch(a){if(a&&a.isAcquireTimeout){try{await n}catch{}return null}throw a}})(),await i}function Wd(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function Fl(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Hd(t){return parseInt(t,16)}function zd(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}function Gd(t){var e;let{chainId:r,domain:o,expirationTime:n,issuedAt:s=new Date,nonce:i,notBefore:a,requestId:l,resources:u,scheme:c,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(!o)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);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(`
|
|
30
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let m=Fl(t.address),h=c?`${c}://${o}`:o,g=t.statement?`${t.statement}
|
|
31
31
|
`:"",y=`${h} wants you to sign in with your Ethereum account:
|
|
32
32
|
${m}
|
|
33
33
|
|
|
@@ -41,15 +41,15 @@ Not Before: ${a.toISOString()}`),l&&(p+=`
|
|
|
41
41
|
Request ID: ${l}`),u){let b=`
|
|
42
42
|
Resources:`;for(let _ of u){if(!_||typeof _!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${_}`);b+=`
|
|
43
43
|
- ${_}`}p+=b}return`${y}
|
|
44
|
-
${p}`}var se=class extends Error{constructor({message:e,code:r,cause:o,name:n}){var s;super(e,{cause:o}),this.__isWebAuthnError=!0,this.name=(s=n??(o instanceof Error?o.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},$r=class extends se{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function zd({error:t,options:e}){var r,o,n;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new se({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new se({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((o=s.authenticatorSelection)===null||o===void 0?void 0:o.userVerification)==="required")return new se({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=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new se({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 se({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new se({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new se({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new se({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 i=window.location.hostname;if(Ul(i)){if(s.rp.id!==i)return new se({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new se({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new se({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 se({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 se({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Gd({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 se({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new se({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Ul(o)){if(r.rpId!==o)return new se({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new se({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new se({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 se({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var Fl=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}}},Wb=new Fl;function Jd(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:o}=t,n=Be(t,["challenge","user","excludeCredentials"]),s=mr(e).buffer,i=Object.assign(Object.assign({},r),{id:mr(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:s,user:i});if(o&&o.length>0){a.excludeCredentials=new Array(o.length);for(let l=0;l<o.length;l++){let u=o[l];a.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:mr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function Yd(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,o=Be(t,["challenge","allowCredentials"]),n=mr(e).buffer,s=Object.assign(Object.assign({},o),{challenge:n});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){let a=r[i];s.allowCredentials[i]=Object.assign(Object.assign({},a),{id:mr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function Xd(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:Jt(new Uint8Array(t.response.attestationObject)),clientDataJSON:Jt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Qd(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,o=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Jt(new Uint8Array(n.authenticatorData)),clientDataJSON:Jt(new Uint8Array(n.clientDataJSON)),signature:Jt(new Uint8Array(n.signature)),userHandle:n.userHandle?Jt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:o,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Ul(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Kd(){var t,e;return!!(be()&&"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 Hb(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new $r("Browser returned unexpected credential type",e)}:{data:null,error:new $r("Empty credential response",e)}}catch(e){return{data:null,error:zd({error:e,options:t})}}}async function zb(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new $r("Browser returned unexpected credential type",e)}:{data:null,error:new $r("Empty credential response",e)}}catch(e){return{data:null,error:Gd({error:e,options:t})}}}var Gb={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Kb={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function si(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),o={};for(let n of t)if(n)for(let s in n){let i=n[s];if(i!==void 0)if(Array.isArray(i))o[s]=i;else if(r(i))o[s]=i;else if(e(i)){let a=o[s];e(a)?o[s]=si(a,i):o[s]=si(i)}else o[s]=i}return o}function Jb(t,e){return si(Gb,t,e||{})}function Yb(t,e){return si(Kb,t,e||{})}var ii=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:o,signal:n},s){var i;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let u=n??Wb.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){let d=o;if(d)c.name=`${c.id}:${d}`;else{let m=(await this.client.getUser()).data.user,h=((i=m?.user_metadata)===null||i===void 0?void 0:i.name)||m?.email||m?.id||"User";c.name=`${c.id}:${h}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{let c=Jb(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:f}=await Hb({publicKey:c,signal:u});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 c=Yb(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:f}=await zb(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));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 k(a)?{data:null,error:a}:{data:null,error:new nt("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:o}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:o})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new fr("rpId is required for WebAuthn authentication")};try{if(!Kd())return{data:null,error:new nt("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:o},signal:n},{request:s});if(!i)return{data:null,error:a};let{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:o,credential_response:l.credential_response}})}catch(i){return k(i)?{data:null,error:i}:{data:null,error:new nt("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new fr("rpId is required for WebAuthn registration")};try{if(!Kd())return{data:null,error:new nt("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(c=>{var d;return(d=c.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};let{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:o},signal:n},{create:s});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:o,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return k(i)?{data:null,error:i}:{data:null,error:new nt("Unexpected error in register",i)}}}};qd();var Xb={url:yd,storageKey:bd,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:_d,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Zd(t,e,r){return await r()}var Eo={},ai=class t{get jwks(){var e,r;return(r=(e=Eo[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Eo[this.storageKey]=Object.assign(Object.assign({},Eo[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Eo[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Eo[this.storageKey]=Object.assign(Object.assign({},Eo[this.storageKey]),{cachedAt:e})}constructor(e){var r,o,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 s=Object.assign(Object.assign({},Xb),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&be()){let i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Fr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=ri(s.fetch),this.lock=s.lock||Zd,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&be()&&(!((o=globalThis?.navigator)===null||o===void 0)&&o.locks)?this.lock=Nl:this.lock=Zd,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 ii(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?(s.storage?this.storage=s.storage:ti()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Dl(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Dl(this.memoryStorage)),be()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Gs}) ${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={},o="none";if(be()&&(r=Ad(window.location.href),this._isImplicitGrantCallback(r)?o="implicit":await this._isPKCECallback(r)&&(o="pkce")),be()&&this.detectSessionInUrl&&o!=="none"){let{data:n,error:s}=await this._getSessionFromURL(r,o);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),xd(s)){let l=(e=s.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:s}}return{error:s}}let{session:i,redirectType:a}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return k(r)?this._returnResult({error:r}):this._returnResult({error:new nt("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,o,n;try{let s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(o=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&o!==void 0?o:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:st}),{data:i,error:a}=s;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(k(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,o,n;try{let s;if("email"in e){let{email:c,password:d,options:f}=e,m=null,h=null;this.flowType==="pkce"&&([m,h]=await jr(this.storage,this.storageKey)),s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:h},xform:st})}else if("phone"in e){let{phone:c,password:d,options:f}=e;s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(o=f?.data)!==null&&o!==void 0?o:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:st})}else throw new Rr("You must provide either an email or phone number and a password");let{data:i,error:a}=s;if(a||!i)return await Te(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:i,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Rl})}else if("phone"in e){let{phone:s,password:i,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Rl})}else throw new Rr("You must provide either an email or phone number and a password");let{data:o,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!o||!o.session||!o.user){let s=new Kt;return this._returnResult({data:{user:null,session:null},error:s})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign({user:o.user,session:o.session},o.weak_password?{weakPassword:o.weak_password}:null),error:n})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,o,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.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,o,n,s,i,a,l,u,c,d,f;let m,h;if("message"in e)m=e.message,h=e.signature;else{let{chain:g,wallet:y,statement:p,options:b}=e,_;if(be())if(typeof y=="object")_=y;else{let F=window;if("ethereum"in F&&typeof F.ethereum=="object"&&"request"in F.ethereum&&typeof F.ethereum.request=="function")_=F.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=y}let v=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),L=await _.request({method:"eth_requestAccounts"}).then(F=>F).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!L||L.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let x=Ml(L[0]),P=(o=b?.signInWithEthereum)===null||o===void 0?void 0:o.chainId;if(!P){let F=await _.request({method:"eth_chainId"});P=Vd(F)}let X={domain:v.host,address:x,statement:p,uri:v.href,version:"1",chainId:P,nonce:(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=Hd(X),h=await _.request({method:"personal_sign",params:[Wd(m),x]})}try{let{data:g,error:y}=await O(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:h},!((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:st});if(y)throw y;if(!g||!g.session||!g.user){let p=new Kt;return this._returnResult({data:{user:null,session:null},error:p})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(k(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,o,n,s,i,a,l,u,c,d,f,m;let h,g;if("message"in e)h=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:b,options:_}=e,v;if(be())if(typeof p=="object")v=p;else{let x=window;if("solana"in x&&typeof x.solana=="object"&&("signIn"in x.solana&&typeof x.solana.signIn=="function"||"signMessage"in x.solana&&typeof x.solana.signMessage=="function"))v=x.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 p!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=p}let L=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in v&&v.signIn){let x=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:L.host,uri:L.href}),b?{statement:b}:null)),P;if(Array.isArray(x)&&x[0]&&typeof x[0]=="object")P=x[0];else if(x&&typeof x=="object"&&"signedMessage"in x&&"signature"in x)P=x;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)h=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),g=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in v)||typeof v.signMessage!="function"||!("publicKey"in v)||typeof v!="object"||!v.publicKey||!("toBase58"in v.publicKey)||typeof v.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");h=[`${L.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${L.href}`,`Issued At: ${(n=(o=_?.signInWithSolana)===null||o===void 0?void 0:o.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((s=_?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((d=(c=_?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
45
|
-
`);let x=await v.signMessage(new TextEncoder().encode(h),"utf8");if(!x||!(x instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=x}}try{let{data:y,error:p}=await O(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:Jt(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:st});if(p)throw p;if(!y||!y.session||!y.user){let b=new Kt;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:p})}catch(y){if(k(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){let r=await hr(this.storage,`${this.storageKey}-code-verifier`),[o,n]=(r??"").split("/");try{if(!o&&this.flowType==="pkce")throw new Xs;let{data:s,error:i}=await O(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:st});if(await Te(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let a=new Kt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:n??null}),error:i})}catch(s){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:o,token:n,access_token:s,nonce:i}=e,a=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:o,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:st}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new Kt;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,o,n,s,i;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await jr(this.storage,this.storageKey));let{error:d}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(o=l?.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new Rr("You must provide either an email or phone number.")}catch(a){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,o;try{let n,s;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(o=e.options)===null||o===void 0?void 0:o.captchaToken);let{data:i,error:a}=await O(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:st});if(a)throw a;if(!i)throw new Error("An error occurred on token verification.");let l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(k(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,o,n,s,i;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await jr(this.storage,this.storageKey));let u=await O(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:(o=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&o!==void 0?o: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:Fd});return!((s=u.data)===null||s===void 0)&&s.url&&be()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(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:o}=e;if(o)throw o;if(!r)throw new Pe;let{error:n}=await O(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(k(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:o,type:n,options:s}=e,{error:i}=await O(this.fetch,"POST",r,{headers:this.headers,body:{email:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){let{phone:o,type:n,options:s}=e,{data:i,error:a}=await O(this.fetch,"POST",r,{headers:this.headers,body:{phone:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:a})}throw new Rr("You must provide either an email or phone number and a type")}catch(r){if(k(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 o=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await o,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 o=r();for(this.pendingInLock.push((async()=>{try{await o}catch{}})()),await o;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await o}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 hr(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 o=e.expires_at?e.expires_at*1e3-Date.now()<Js:!1;if(this._debug("#__loadSession()",`session has${o?"":" not"} expired`,"expires_at",e.expires_at),!o){if(this.userStorage){let i=await hr(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=oi()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let i={value:this.suppressGetSessionWarning};e.user=Md(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):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 O(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:It}):await this._useSession(async r=>{var o,n,s;let{data:i,error:a}=r;if(a)throw a;return!(!((o=i.session)===null||o===void 0)&&o.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Pe}:await O(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0,xform:It})})}catch(r){if(k(r))return Qs(r)&&(await this._removeSession(),await Te(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 o=>{let{data:n,error:s}=o;if(s)throw s;if(!n.session)throw new Pe;let i=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await jr(this.storage,this.storageKey));let{data:u,error:c}=await O(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:i.access_token,xform:It});if(c)throw c;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(o){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(o))return this._returnResult({data:{user:null},error:o});throw o}}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 Pe;let r=Date.now()/1e3,o=r,n=!0,s=null,{payload:i}=Un(e.access_token);if(i.exp&&(o=i.exp,n=o<=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};s=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});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:o-r,expires_at:o},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(k(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 o;if(!e){let{data:i,error:a}=r;if(a)throw a;e=(o=i.session)!==null&&o!==void 0?o:void 0}if(!e?.refresh_token)throw new Pe;let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!be())throw new Ir("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ir(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 Nn("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ir("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 Nn("No code detected.");let{data:b,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;let v=new URL(window.location.href);return v.searchParams.delete("code"),window.history.replaceState(window.history.state,"",v.toString()),{data:{session:b.session,redirectType:null},error:null}}let{provider_token:o,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:a,expires_at:l,token_type:u}=e;if(!s||!a||!i||!u)throw new Ir("No session defined in URL");let c=Math.round(Date.now()/1e3),d=parseInt(a),f=c+d;l&&(f=parseInt(l));let m=f-c;m*1e3<=Ar&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);let h=f-d;c-h>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,f,c):c-h<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,f,c);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:o,provider_refresh_token:n,access_token:s,expires_in:d,expires_at:f,refresh_token:i,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(o){if(k(o))return this._returnResult({data:{session:null,redirectType:null},error:o});throw o}}_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 hr(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 o;let{data:n,error:s}=r;if(s&&!Qs(s))return this._returnResult({error:s});let i=(o=n.session)===null||o===void 0?void 0:o.access_token;if(i){let{error:a}=await this.admin.signOut(i,e);if(a&&!(Sd(a)&&(a.status===404||a.status===401||a.status===403)||Qs(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await Te(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Od(),o={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,o),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:o}}}async _emitInitialSession(e){return await this._useSession(async r=>{var o,n;try{let{data:{session:s},error:i}=r;if(i)throw i;await((o=this.stateChangeEmitters.get(e))===null||o===void 0?void 0:o.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){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",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let o=null,n=null;this.flowType==="pkce"&&([o,n]=await jr(this.storage,this.storageKey,!0));try{return await O(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:o,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:o}=await this.getUser();if(o)throw o;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(k(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:o,error:n}=await this._useSession(async s=>{var i,a,l,u,c;let{data:d,error:f}=s;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.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 O(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;return be()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(o?.url),this._returnResult({data:{provider:e.provider,url:o?.url},error:null})}catch(o){if(k(o))return this._returnResult({data:{provider:e.provider,url:null},error:o});throw o}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var o;try{let{error:n,data:{session:s}}=r;if(n)throw n;let{options:i,provider:a,token:l,access_token:u,nonce:c}=e,d=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(o=s?.access_token)!==null&&o!==void 0?o:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:st}),{data:f,error:m}=d;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new Kt}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(n){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)throw i;return await O(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(o=s.session)===null||o===void 0?void 0:o.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(k(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 o=Date.now();return await Dd(async n=>(n>0&&await Id(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await O(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:st})),(n,s)=>{let i=200*Math.pow(2,n);return s&&Zs(s)&&Date.now()+i-o<Ar})}catch(o){if(this._debug(r,"error",o),k(o))return this._returnResult({data:{session:null,user:null},error:o});throw o}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 o=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",o),be()&&!r.skipBrowserRedirect&&window.location.assign(o),{data:{provider:e,url:o},error:null}}async _recoverAndRefresh(){var e,r;let o="#_recoverAndRefresh()";this._debug(o,"begin");try{let n=await hr(this.storage,this.storageKey);if(n&&this.userStorage){let i=await hr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Nr(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:oi()}else if(n&&!n.user&&!n.user){let i=await hr(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await Te(this.storage,this.storageKey+"-user"),await Nr(this.storage,this.storageKey,n)):n.user=oi()}if(this._debug(o,"session from storage",n),!this._isValidSession(n)){this._debug(o,"session is not valid"),n!==null&&await this._removeSession();return}let s=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Js;if(this._debug(o,`session has${s?"":" not"} expired with margin of ${Js}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Zs(i)||(this._debug(o,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:a}=await this._getUser(n.access_token);!a&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(o,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(o,"error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(o,"error",n),console.error(n);return}finally{this._debug(o,"end")}}async _callRefreshToken(e){var r,o;if(!e)throw new Pe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Mn;let{data:s,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!s.session)throw new Pe;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(n,"error",s),k(s)){let i={data:null,error:s};return Zs(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(o=this.refreshingDeferred)===null||o===void 0||o.reject(s),s}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,o=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${o}`);try{this.broadcastChannel&&o&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){s.push(l)}});if(await Promise.all(i),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Te(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),o=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!o&&r.user&&await Nr(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let s=Al(n);await Nr(this.storage,this.storageKey,s)}else{let n=Al(r);await Nr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Te(this.storage,this.storageKey),await Te(this.storage,this.storageKey+"-code-verifier"),await Te(this.storage,this.storageKey+"-user"),this.userStorage&&await Te(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&be()&&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(),Ar);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:o}}=r;if(!o||!o.refresh_token||!o.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((o.expires_at*1e3-e)/Ar);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Ar}ms, refresh threshold is ${Ks} ticks`),n<=Ks&&await this._callRefreshToken(o.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 Co)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!be()||!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,o){let n=[`provider=${encodeURIComponent(r)}`];if(o?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(o.redirectTo)}`),o?.scopes&&n.push(`scopes=${encodeURIComponent(o.scopes)}`),this.flowType==="pkce"){let[s,i]=await jr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(a.toString())}if(o?.queryParams){let s=new URLSearchParams(o.queryParams);n.push(s.toString())}return o?.skipBrowserRedirect&&n.push(`skip_http_redirect=${o.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;return s?this._returnResult({data:null,error:s}):await O(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});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:u}=await O(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(o=s?.session)===null||o===void 0?void 0:o.access_token});return u?this._returnResult({data:null,error:u}):(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(k(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 o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Xd(e.webauthn.credential_response):Qd(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.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(k(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 o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token});if(i.error)return i;let{data:a}=i;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:Jd(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:Yd(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:o}=await this._challenge({factorId:e.factorId});return o?this._returnResult({data:null,error:o}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:o}=await this.getUser();if(o)return{data:null,error:o};let n={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(s),s.status==="verified"&&n[s.factor_type].push(s);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,o,n,s;if(e)try{let{payload:m}=Un(e),h=null;m.aal&&(h=m.aal);let g=h,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((o=(r=y?.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(g="aal2");let _=m.amr||[];return{data:{currentLevel:h,nextLevel:g,currentAuthenticationMethods:_},error:null}}catch(m){if(k(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:i},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=Un(i.access_token),u=null;l.aal&&(u=l.aal);let c=u;((s=(n=i.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let f=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?await O(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:o.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Pe})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Pe});let i=await O(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 i.data&&i.data.redirect_url&&be()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}async _denyAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Pe});let i=await O(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 i.data&&i.data.redirect_url&&be()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:o}=e;return o?this._returnResult({data:null,error:o}):r?await O(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 Pe})})}catch(e){if(k(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?(await O(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:o.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Pe})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let o=r.keys.find(a=>a.kid===e);if(o)return o;let n=Date.now();if(o=this.jwks.keys.find(a=>a.kid===e),o&&this.jwks_cached_at+vd>n)return o;let{data:s,error:i}=await O(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=n,o=s.keys.find(a=>a.kid===e),!o)?null:o}async getClaims(e,r={}){try{let o=e;if(!o){let{data:m,error:h}=await this.getSession();if(h||!m.session)return this._returnResult({data:null,error:h});o=m.session.access_token}let{header:n,payload:s,signature:i,raw:{header:a,payload:l}}=Un(o);r?.allowExpired||Nd(s.exp);let u=!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(!u){let{error:m}=await this.getUser(o);if(m)throw m;return{data:{claims:s,header:n,signature:i},error:null}}let c=jd(n.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,i,Ed(`${a}.${l}`)))throw new Dr("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}};ai.nextInstanceID={};var $l=ai;var Qb=$l,Bl=Qb;var Zb="2.100.1",$n="";typeof Deno<"u"?$n="deno":typeof document<"u"?$n="web":typeof navigator<"u"&&navigator.product==="ReactNative"?$n="react-native":$n="node";var e_={"X-Client-Info":`supabase-js-${$n}/${Zb}`},t_={headers:e_},r_={schema:"public"},o_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},n_={};function Bn(t){"@babel/helpers - typeof";return Bn=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},Bn(t)}function s_(t,e){if(Bn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Bn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function i_(t){var e=s_(t,"string");return Bn(e)=="symbol"?e:e+""}function a_(t,e,r){return(e=i_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ef(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function le(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?ef(Object(r),!0).forEach(function(o){a_(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):ef(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var l_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),u_=()=>Headers,c_=(t,e,r)=>{let o=l_(r),n=u_();return async(s,i)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),o(s,le(le({},i),{},{headers:u}))}};function d_(t){return t.endsWith("/")?t:t+"/"}function f_(t,e){var r,o;let{db:n,auth:s,realtime:i,global:a}=t,{db:l,auth:u,realtime:c,global:d}=e,f={db:le(le({},l),n),auth:le(le({},u),s),realtime:le(le({},c),i),storage:{},global:le(le(le({},d),a),{},{headers:le(le({},(r=d?.headers)!==null&&r!==void 0?r:{}),(o=a?.headers)!==null&&o!==void 0?o:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function m_(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(d_(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var h_=class extends Bl{constructor(t){super(t)}},p_=class{constructor(t,e,r){var o,n;this.supabaseUrl=t,this.supabaseKey=e;let s=m_(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:r_,realtime:n_,auth:le(le({},o_),{},{storageKey:i}),global:t_},l=f_(r??{},a);if(this.storageKey=(o=l.auth.storageKey)!==null&&o!==void 0?o:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,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 u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=c_(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(le({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new Zc(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new gd(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new wn(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:o}=await t.auth.getSession();return(e=(r=o.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:o,userStorage:n,storageKey:s,flowType:i,lock:a,debug:l,throwOnError:u},c,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new h_({url:this.authUrl.href,headers:le(le({},f),c),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,flowType:i,lock:a,debug:l,throwOnError:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new So(this.realtimeUrl.href,le(le({},t),{},{params:le(le({},{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)}},tf=(t,e,r)=>new p_(t,e,r);function g_(){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}g_()&&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 rf=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var Po=class extends Error{constructor(e,r="FunctionsError",o){super(e),this.name=r,this.context=o}},qn=class extends Po{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Oo=class extends Po{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ao=class extends Po{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Vn;(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"})(Vn||(Vn={}));var Wn=class{constructor(e,{headers:r={},customFetch:o,region:n=Vn.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=rf(o)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Ds(this,arguments,void 0,function*(r,o={}){var n;let s,i;try{let{headers:a,method:l,body:u,signal:c,timeout:d}=o,f={},{region:m}=o;m||(m=this.region);let h=new URL(`${this.url}/${r}`);m&&m!=="any"&&(f["x-region"]=m,h.searchParams.set("forceFunctionRegion",m));let g;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=u):typeof u=="string"?(f["Content-Type"]="text/plain",g=u):typeof FormData<"u"&&u instanceof FormData?g=u:(f["Content-Type"]="application/json",g=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?g=JSON.stringify(u):g=u;let y=c;d&&(i=new AbortController,s=setTimeout(()=>i.abort(),d),c?(y=i.signal,c.addEventListener("abort",()=>i.abort())):y=i.signal);let p=yield this.fetch(h.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:y}).catch(L=>{throw new qn(L)}),b=p.headers.get("x-relay-error");if(b&&b==="true")throw new Oo(p);if(!p.ok)throw new Ao(p);let _=((n=p.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),v;return _==="application/json"?v=yield p.json():_==="application/octet-stream"||_==="application/pdf"?v=yield p.blob():_==="text/event-stream"?v=p:_==="multipart/form-data"?v=yield p.formData():v=yield p.text(),{data:v,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof Ao||a instanceof Oo?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var sf=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},y_=class{constructor(t){var e,r,o;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=(o=t.urlLengthLimit)!==null&&o!==void 0?o: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 o=this.fetch,n=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let i=null,a=null,l=null,u=s.status,c=s.statusText;if(s.ok){var d,f;if(r.method!=="HEAD"){var m;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let h=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(f=s.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");h&&g&&g.length>1&&(l=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(i={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,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let h=await s.text();try{i=JSON.parse(h),Array.isArray(i)&&s.status===404&&(a=[],i=null,u=200,c="OK")}catch{s.status===404&&h===""?(u=204,c="No Content"):i={message:h}}if(i&&r.shouldThrowOnError)throw new sf(i)}return{error:i,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(n=n.catch(s=>{var i;let a="",l="",u="",c=s?.cause;if(c){var d,f,m,h;let p=(d=c?.message)!==null&&d!==void 0?d:"",b=(f=c?.code)!==null&&f!==void 0?f:"";a=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,a+=`
|
|
44
|
+
${p}`}var se=class extends Error{constructor({message:e,code:r,cause:o,name:n}){var s;super(e,{cause:o}),this.__isWebAuthnError=!0,this.name=(s=n??(o instanceof Error?o.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},$r=class extends se{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function Kd({error:t,options:e}){var r,o,n;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new se({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new se({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((o=s.authenticatorSelection)===null||o===void 0?void 0:o.userVerification)==="required")return new se({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=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new se({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 se({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new se({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new se({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new se({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 i=window.location.hostname;if($l(i)){if(s.rp.id!==i)return new se({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new se({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new se({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 se({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 se({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Jd({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 se({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new se({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if($l(o)){if(r.rpId!==o)return new se({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new se({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new se({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 se({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var Bl=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}}},Wb=new Bl;function Xd(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:o}=t,n=Be(t,["challenge","user","excludeCredentials"]),s=mr(e).buffer,i=Object.assign(Object.assign({},r),{id:mr(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:s,user:i});if(o&&o.length>0){a.excludeCredentials=new Array(o.length);for(let l=0;l<o.length;l++){let u=o[l];a.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:mr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function Qd(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,o=Be(t,["challenge","allowCredentials"]),n=mr(e).buffer,s=Object.assign(Object.assign({},o),{challenge:n});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){let a=r[i];s.allowCredentials[i]=Object.assign(Object.assign({},a),{id:mr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function Zd(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:Jt(new Uint8Array(t.response.attestationObject)),clientDataJSON:Jt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function ef(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,o=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Jt(new Uint8Array(n.authenticatorData)),clientDataJSON:Jt(new Uint8Array(n.clientDataJSON)),signature:Jt(new Uint8Array(n.signature)),userHandle:n.userHandle?Jt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:o,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function $l(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Yd(){var t,e;return!!(be()&&"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 Hb(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new $r("Browser returned unexpected credential type",e)}:{data:null,error:new $r("Empty credential response",e)}}catch(e){return{data:null,error:Kd({error:e,options:t})}}}async function zb(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new $r("Browser returned unexpected credential type",e)}:{data:null,error:new $r("Empty credential response",e)}}catch(e){return{data:null,error:Jd({error:e,options:t})}}}var Gb={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Kb={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function si(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),o={};for(let n of t)if(n)for(let s in n){let i=n[s];if(i!==void 0)if(Array.isArray(i))o[s]=i;else if(r(i))o[s]=i;else if(e(i)){let a=o[s];e(a)?o[s]=si(a,i):o[s]=si(i)}else o[s]=i}return o}function Jb(t,e){return si(Gb,t,e||{})}function Yb(t,e){return si(Kb,t,e||{})}var ii=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:o,signal:n},s){var i;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let u=n??Wb.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){let d=o;if(d)c.name=`${c.id}:${d}`;else{let m=(await this.client.getUser()).data.user,h=((i=m?.user_metadata)===null||i===void 0?void 0:i.name)||m?.email||m?.id||"User";c.name=`${c.id}:${h}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{let c=Jb(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:f}=await Hb({publicKey:c,signal:u});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 c=Yb(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:f}=await zb(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));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 k(a)?{data:null,error:a}:{data:null,error:new nt("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:o}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:o})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new fr("rpId is required for WebAuthn authentication")};try{if(!Yd())return{data:null,error:new nt("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:o},signal:n},{request:s});if(!i)return{data:null,error:a};let{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:o,credential_response:l.credential_response}})}catch(i){return k(i)?{data:null,error:i}:{data:null,error:new nt("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new fr("rpId is required for WebAuthn registration")};try{if(!Yd())return{data:null,error:new nt("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(c=>{var d;return(d=c.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};let{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:o},signal:n},{create:s});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:o,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return k(i)?{data:null,error:i}:{data:null,error:new nt("Unexpected error in register",i)}}}};Wd();var Xb={url:_d,storageKey:wd,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:vd,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function tf(t,e,r){return await r()}var Eo={},ai=class t{get jwks(){var e,r;return(r=(e=Eo[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Eo[this.storageKey]=Object.assign(Object.assign({},Eo[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Eo[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Eo[this.storageKey]=Object.assign(Object.assign({},Eo[this.storageKey]),{cachedAt:e})}constructor(e){var r,o,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 s=Object.assign(Object.assign({},Xb),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&be()){let i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Fr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=ri(s.fetch),this.lock=s.lock||tf,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&be()&&(!((o=globalThis?.navigator)===null||o===void 0)&&o.locks)?this.lock=Ml:this.lock=tf,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 ii(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?(s.storage?this.storage=s.storage:ti()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Nl(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Nl(this.memoryStorage)),be()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Gs}) ${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={},o="none";if(be()&&(r=Id(window.location.href),this._isImplicitGrantCallback(r)?o="implicit":await this._isPKCECallback(r)&&(o="pkce")),be()&&this.detectSessionInUrl&&o!=="none"){let{data:n,error:s}=await this._getSessionFromURL(r,o);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),Td(s)){let l=(e=s.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:s}}return{error:s}}let{session:i,redirectType:a}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return k(r)?this._returnResult({error:r}):this._returnResult({error:new nt("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,o,n;try{let s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(o=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&o!==void 0?o:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:st}),{data:i,error:a}=s;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(k(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,o,n;try{let s;if("email"in e){let{email:c,password:d,options:f}=e,m=null,h=null;this.flowType==="pkce"&&([m,h]=await jr(this.storage,this.storageKey)),s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:h},xform:st})}else if("phone"in e){let{phone:c,password:d,options:f}=e;s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(o=f?.data)!==null&&o!==void 0?o:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:st})}else throw new Rr("You must provide either an email or phone number and a password");let{data:i,error:a}=s;if(a||!i)return await Te(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:i,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Dl})}else if("phone"in e){let{phone:s,password:i,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Dl})}else throw new Rr("You must provide either an email or phone number and a password");let{data:o,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!o||!o.session||!o.user){let s=new Kt;return this._returnResult({data:{user:null,session:null},error:s})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign({user:o.user,session:o.session},o.weak_password?{weakPassword:o.weak_password}:null),error:n})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,o,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.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,o,n,s,i,a,l,u,c,d,f;let m,h;if("message"in e)m=e.message,h=e.signature;else{let{chain:g,wallet:y,statement:p,options:b}=e,_;if(be())if(typeof y=="object")_=y;else{let F=window;if("ethereum"in F&&typeof F.ethereum=="object"&&"request"in F.ethereum&&typeof F.ethereum.request=="function")_=F.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=y}let v=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),L=await _.request({method:"eth_requestAccounts"}).then(F=>F).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!L||L.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let x=Fl(L[0]),P=(o=b?.signInWithEthereum)===null||o===void 0?void 0:o.chainId;if(!P){let F=await _.request({method:"eth_chainId"});P=Hd(F)}let X={domain:v.host,address:x,statement:p,uri:v.href,version:"1",chainId:P,nonce:(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=Gd(X),h=await _.request({method:"personal_sign",params:[zd(m),x]})}try{let{data:g,error:y}=await O(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:h},!((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:st});if(y)throw y;if(!g||!g.session||!g.user){let p=new Kt;return this._returnResult({data:{user:null,session:null},error:p})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(k(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,o,n,s,i,a,l,u,c,d,f,m;let h,g;if("message"in e)h=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:b,options:_}=e,v;if(be())if(typeof p=="object")v=p;else{let x=window;if("solana"in x&&typeof x.solana=="object"&&("signIn"in x.solana&&typeof x.solana.signIn=="function"||"signMessage"in x.solana&&typeof x.solana.signMessage=="function"))v=x.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 p!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=p}let L=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in v&&v.signIn){let x=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:L.host,uri:L.href}),b?{statement:b}:null)),P;if(Array.isArray(x)&&x[0]&&typeof x[0]=="object")P=x[0];else if(x&&typeof x=="object"&&"signedMessage"in x&&"signature"in x)P=x;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)h=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),g=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in v)||typeof v.signMessage!="function"||!("publicKey"in v)||typeof v!="object"||!v.publicKey||!("toBase58"in v.publicKey)||typeof v.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");h=[`${L.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${L.href}`,`Issued At: ${(n=(o=_?.signInWithSolana)===null||o===void 0?void 0:o.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((s=_?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((d=(c=_?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
45
|
+
`);let x=await v.signMessage(new TextEncoder().encode(h),"utf8");if(!x||!(x instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=x}}try{let{data:y,error:p}=await O(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:Jt(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:st});if(p)throw p;if(!y||!y.session||!y.user){let b=new Kt;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:p})}catch(y){if(k(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){let r=await hr(this.storage,`${this.storageKey}-code-verifier`),[o,n]=(r??"").split("/");try{if(!o&&this.flowType==="pkce")throw new Xs;let{data:s,error:i}=await O(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:st});if(await Te(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let a=new Kt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:n??null}),error:i})}catch(s){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:o,token:n,access_token:s,nonce:i}=e,a=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:o,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:st}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new Kt;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,o,n,s,i;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await jr(this.storage,this.storageKey));let{error:d}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(o=l?.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new Rr("You must provide either an email or phone number.")}catch(a){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,o;try{let n,s;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(o=e.options)===null||o===void 0?void 0:o.captchaToken);let{data:i,error:a}=await O(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:st});if(a)throw a;if(!i)throw new Error("An error occurred on token verification.");let l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(k(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,o,n,s,i;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await jr(this.storage,this.storageKey));let u=await O(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:(o=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&o!==void 0?o: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:Bd});return!((s=u.data)===null||s===void 0)&&s.url&&be()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(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:o}=e;if(o)throw o;if(!r)throw new Pe;let{error:n}=await O(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(k(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:o,type:n,options:s}=e,{error:i}=await O(this.fetch,"POST",r,{headers:this.headers,body:{email:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){let{phone:o,type:n,options:s}=e,{data:i,error:a}=await O(this.fetch,"POST",r,{headers:this.headers,body:{phone:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:a})}throw new Rr("You must provide either an email or phone number and a type")}catch(r){if(k(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 o=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await o,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 o=r();for(this.pendingInLock.push((async()=>{try{await o}catch{}})()),await o;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await o}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 hr(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 o=e.expires_at?e.expires_at*1e3-Date.now()<Js:!1;if(this._debug("#__loadSession()",`session has${o?"":" not"} expired`,"expires_at",e.expires_at),!o){if(this.userStorage){let i=await hr(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=oi()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let i={value:this.suppressGetSessionWarning};e.user=Fd(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):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 O(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:It}):await this._useSession(async r=>{var o,n,s;let{data:i,error:a}=r;if(a)throw a;return!(!((o=i.session)===null||o===void 0)&&o.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Pe}:await O(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0,xform:It})})}catch(r){if(k(r))return Qs(r)&&(await this._removeSession(),await Te(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 o=>{let{data:n,error:s}=o;if(s)throw s;if(!n.session)throw new Pe;let i=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await jr(this.storage,this.storageKey));let{data:u,error:c}=await O(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:i.access_token,xform:It});if(c)throw c;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(o){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(o))return this._returnResult({data:{user:null},error:o});throw o}}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 Pe;let r=Date.now()/1e3,o=r,n=!0,s=null,{payload:i}=Un(e.access_token);if(i.exp&&(o=i.exp,n=o<=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};s=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});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:o-r,expires_at:o},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(k(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 o;if(!e){let{data:i,error:a}=r;if(a)throw a;e=(o=i.session)!==null&&o!==void 0?o:void 0}if(!e?.refresh_token)throw new Pe;let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!be())throw new Ir("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ir(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 Nn("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ir("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 Nn("No code detected.");let{data:b,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;let v=new URL(window.location.href);return v.searchParams.delete("code"),window.history.replaceState(window.history.state,"",v.toString()),{data:{session:b.session,redirectType:null},error:null}}let{provider_token:o,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:a,expires_at:l,token_type:u}=e;if(!s||!a||!i||!u)throw new Ir("No session defined in URL");let c=Math.round(Date.now()/1e3),d=parseInt(a),f=c+d;l&&(f=parseInt(l));let m=f-c;m*1e3<=Ar&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);let h=f-d;c-h>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,f,c):c-h<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,f,c);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:o,provider_refresh_token:n,access_token:s,expires_in:d,expires_at:f,refresh_token:i,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(o){if(k(o))return this._returnResult({data:{session:null,redirectType:null},error:o});throw o}}_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 hr(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 o;let{data:n,error:s}=r;if(s&&!Qs(s))return this._returnResult({error:s});let i=(o=n.session)===null||o===void 0?void 0:o.access_token;if(i){let{error:a}=await this.admin.signOut(i,e);if(a&&!(kd(a)&&(a.status===404||a.status===401||a.status===403)||Qs(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await Te(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Rd(),o={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,o),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:o}}}async _emitInitialSession(e){return await this._useSession(async r=>{var o,n;try{let{data:{session:s},error:i}=r;if(i)throw i;await((o=this.stateChangeEmitters.get(e))===null||o===void 0?void 0:o.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){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",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let o=null,n=null;this.flowType==="pkce"&&([o,n]=await jr(this.storage,this.storageKey,!0));try{return await O(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:o,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:o}=await this.getUser();if(o)throw o;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(k(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:o,error:n}=await this._useSession(async s=>{var i,a,l,u,c;let{data:d,error:f}=s;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.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 O(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;return be()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(o?.url),this._returnResult({data:{provider:e.provider,url:o?.url},error:null})}catch(o){if(k(o))return this._returnResult({data:{provider:e.provider,url:null},error:o});throw o}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var o;try{let{error:n,data:{session:s}}=r;if(n)throw n;let{options:i,provider:a,token:l,access_token:u,nonce:c}=e,d=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(o=s?.access_token)!==null&&o!==void 0?o:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:st}),{data:f,error:m}=d;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new Kt}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(n){if(await Te(this.storage,`${this.storageKey}-code-verifier`),k(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)throw i;return await O(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(o=s.session)===null||o===void 0?void 0:o.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(k(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 o=Date.now();return await Nd(async n=>(n>0&&await Ld(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await O(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:st})),(n,s)=>{let i=200*Math.pow(2,n);return s&&Zs(s)&&Date.now()+i-o<Ar})}catch(o){if(this._debug(r,"error",o),k(o))return this._returnResult({data:{session:null,user:null},error:o});throw o}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 o=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",o),be()&&!r.skipBrowserRedirect&&window.location.assign(o),{data:{provider:e,url:o},error:null}}async _recoverAndRefresh(){var e,r;let o="#_recoverAndRefresh()";this._debug(o,"begin");try{let n=await hr(this.storage,this.storageKey);if(n&&this.userStorage){let i=await hr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Nr(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:oi()}else if(n&&!n.user&&!n.user){let i=await hr(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await Te(this.storage,this.storageKey+"-user"),await Nr(this.storage,this.storageKey,n)):n.user=oi()}if(this._debug(o,"session from storage",n),!this._isValidSession(n)){this._debug(o,"session is not valid"),n!==null&&await this._removeSession();return}let s=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Js;if(this._debug(o,`session has${s?"":" not"} expired with margin of ${Js}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Zs(i)||(this._debug(o,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:a}=await this._getUser(n.access_token);!a&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(o,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(o,"error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(o,"error",n),console.error(n);return}finally{this._debug(o,"end")}}async _callRefreshToken(e){var r,o;if(!e)throw new Pe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Mn;let{data:s,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!s.session)throw new Pe;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(n,"error",s),k(s)){let i={data:null,error:s};return Zs(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(o=this.refreshingDeferred)===null||o===void 0||o.reject(s),s}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,o=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${o}`);try{this.broadcastChannel&&o&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){s.push(l)}});if(await Promise.all(i),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Te(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),o=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!o&&r.user&&await Nr(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let s=Il(n);await Nr(this.storage,this.storageKey,s)}else{let n=Il(r);await Nr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Te(this.storage,this.storageKey),await Te(this.storage,this.storageKey+"-code-verifier"),await Te(this.storage,this.storageKey+"-user"),this.userStorage&&await Te(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&be()&&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(),Ar);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:o}}=r;if(!o||!o.refresh_token||!o.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((o.expires_at*1e3-e)/Ar);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Ar}ms, refresh threshold is ${Ks} ticks`),n<=Ks&&await this._callRefreshToken(o.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 Co)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!be()||!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,o){let n=[`provider=${encodeURIComponent(r)}`];if(o?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(o.redirectTo)}`),o?.scopes&&n.push(`scopes=${encodeURIComponent(o.scopes)}`),this.flowType==="pkce"){let[s,i]=await jr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(a.toString())}if(o?.queryParams){let s=new URLSearchParams(o.queryParams);n.push(s.toString())}return o?.skipBrowserRedirect&&n.push(`skip_http_redirect=${o.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;return s?this._returnResult({data:null,error:s}):await O(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});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:u}=await O(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(o=s?.session)===null||o===void 0?void 0:o.access_token});return u?this._returnResult({data:null,error:u}):(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(k(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 o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Zd(e.webauthn.credential_response):ef(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.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(k(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 o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token});if(i.error)return i;let{data:a}=i;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:Xd(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:Qd(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:o}=await this._challenge({factorId:e.factorId});return o?this._returnResult({data:null,error:o}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:o}=await this.getUser();if(o)return{data:null,error:o};let n={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(s),s.status==="verified"&&n[s.factor_type].push(s);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,o,n,s;if(e)try{let{payload:m}=Un(e),h=null;m.aal&&(h=m.aal);let g=h,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((o=(r=y?.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(g="aal2");let _=m.amr||[];return{data:{currentLevel:h,nextLevel:g,currentAuthenticationMethods:_},error:null}}catch(m){if(k(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:i},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=Un(i.access_token),u=null;l.aal&&(u=l.aal);let c=u;((s=(n=i.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let f=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?await O(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:o.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Pe})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Pe});let i=await O(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 i.data&&i.data.redirect_url&&be()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}async _denyAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Pe});let i=await O(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 i.data&&i.data.redirect_url&&be()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:o}=e;return o?this._returnResult({data:null,error:o}):r?await O(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 Pe})})}catch(e){if(k(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?(await O(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:o.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Pe})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let o=r.keys.find(a=>a.kid===e);if(o)return o;let n=Date.now();if(o=this.jwks.keys.find(a=>a.kid===e),o&&this.jwks_cached_at+xd>n)return o;let{data:s,error:i}=await O(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=n,o=s.keys.find(a=>a.kid===e),!o)?null:o}async getClaims(e,r={}){try{let o=e;if(!o){let{data:m,error:h}=await this.getSession();if(h||!m.session)return this._returnResult({data:null,error:h});o=m.session.access_token}let{header:n,payload:s,signature:i,raw:{header:a,payload:l}}=Un(o);r?.allowExpired||Md(s.exp);let u=!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(!u){let{error:m}=await this.getUser(o);if(m)throw m;return{data:{claims:s,header:n,signature:i},error:null}}let c=Ud(n.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,i,Od(`${a}.${l}`)))throw new Dr("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}};ai.nextInstanceID={};var ql=ai;var Qb=ql,Vl=Qb;var Zb="2.100.1",$n="";typeof Deno<"u"?$n="deno":typeof document<"u"?$n="web":typeof navigator<"u"&&navigator.product==="ReactNative"?$n="react-native":$n="node";var e_={"X-Client-Info":`supabase-js-${$n}/${Zb}`},t_={headers:e_},r_={schema:"public"},o_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},n_={};function Bn(t){"@babel/helpers - typeof";return Bn=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},Bn(t)}function s_(t,e){if(Bn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Bn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function i_(t){var e=s_(t,"string");return Bn(e)=="symbol"?e:e+""}function a_(t,e,r){return(e=i_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function rf(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function le(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?rf(Object(r),!0).forEach(function(o){a_(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):rf(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var l_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),u_=()=>Headers,c_=(t,e,r)=>{let o=l_(r),n=u_();return async(s,i)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),o(s,le(le({},i),{},{headers:u}))}};function d_(t){return t.endsWith("/")?t:t+"/"}function f_(t,e){var r,o;let{db:n,auth:s,realtime:i,global:a}=t,{db:l,auth:u,realtime:c,global:d}=e,f={db:le(le({},l),n),auth:le(le({},u),s),realtime:le(le({},c),i),storage:{},global:le(le(le({},d),a),{},{headers:le(le({},(r=d?.headers)!==null&&r!==void 0?r:{}),(o=a?.headers)!==null&&o!==void 0?o:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function m_(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(d_(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var h_=class extends Vl{constructor(t){super(t)}},p_=class{constructor(t,e,r){var o,n;this.supabaseUrl=t,this.supabaseKey=e;let s=m_(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:r_,realtime:n_,auth:le(le({},o_),{},{storageKey:i}),global:t_},l=f_(r??{},a);if(this.storageKey=(o=l.auth.storageKey)!==null&&o!==void 0?o:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,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 u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=c_(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(le({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new td(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new bd(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new wn(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:o}=await t.auth.getSession();return(e=(r=o.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:o,userStorage:n,storageKey:s,flowType:i,lock:a,debug:l,throwOnError:u},c,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new h_({url:this.authUrl.href,headers:le(le({},f),c),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,flowType:i,lock:a,debug:l,throwOnError:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new So(this.realtimeUrl.href,le(le({},t),{},{params:le(le({},{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)}},of=(t,e,r)=>new p_(t,e,r);function g_(){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}g_()&&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 nf=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var Po=class extends Error{constructor(e,r="FunctionsError",o){super(e),this.name=r,this.context=o}},qn=class extends Po{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Oo=class extends Po{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ao=class extends Po{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Vn;(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"})(Vn||(Vn={}));var Wn=class{constructor(e,{headers:r={},customFetch:o,region:n=Vn.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=nf(o)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Ds(this,arguments,void 0,function*(r,o={}){var n;let s,i;try{let{headers:a,method:l,body:u,signal:c,timeout:d}=o,f={},{region:m}=o;m||(m=this.region);let h=new URL(`${this.url}/${r}`);m&&m!=="any"&&(f["x-region"]=m,h.searchParams.set("forceFunctionRegion",m));let g;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=u):typeof u=="string"?(f["Content-Type"]="text/plain",g=u):typeof FormData<"u"&&u instanceof FormData?g=u:(f["Content-Type"]="application/json",g=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?g=JSON.stringify(u):g=u;let y=c;d&&(i=new AbortController,s=setTimeout(()=>i.abort(),d),c?(y=i.signal,c.addEventListener("abort",()=>i.abort())):y=i.signal);let p=yield this.fetch(h.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:y}).catch(L=>{throw new qn(L)}),b=p.headers.get("x-relay-error");if(b&&b==="true")throw new Oo(p);if(!p.ok)throw new Ao(p);let _=((n=p.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),v;return _==="application/json"?v=yield p.json():_==="application/octet-stream"||_==="application/pdf"?v=yield p.blob():_==="text/event-stream"?v=p:_==="multipart/form-data"?v=yield p.formData():v=yield p.text(),{data:v,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof Ao||a instanceof Oo?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var lf=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},y_=class{constructor(t){var e,r,o;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=(o=t.urlLengthLimit)!==null&&o!==void 0?o: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 o=this.fetch,n=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let i=null,a=null,l=null,u=s.status,c=s.statusText;if(s.ok){var d,f;if(r.method!=="HEAD"){var m;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let h=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(f=s.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");h&&g&&g.length>1&&(l=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(i={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,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let h=await s.text();try{i=JSON.parse(h),Array.isArray(i)&&s.status===404&&(a=[],i=null,u=200,c="OK")}catch{s.status===404&&h===""?(u=204,c="No Content"):i={message:h}}if(i&&r.shouldThrowOnError)throw new lf(i)}return{error:i,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(n=n.catch(s=>{var i;let a="",l="",u="",c=s?.cause;if(c){var d,f,m,h;let p=(d=c?.message)!==null&&d!==void 0?d:"",b=(f=c?.code)!==null&&f!==void 0?f:"";a=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,a+=`
|
|
46
46
|
|
|
47
47
|
Caused by: ${(h=c?.name)!==null&&h!==void 0?h:"Error"}: ${p}`,b&&(a+=` (${b})`),c?.stack&&(a+=`
|
|
48
|
-
${c.stack}`)}else{var g;a=(g=s?.stack)!==null&&g!==void 0?g:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${y} 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.`)):(c?.name==="HeadersOverflowError"||c?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(l+=`. Your request URL is ${y} 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:`${(i=s?.name)!==null&&i!==void 0?i:"FetchError"}: ${s?.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},b_=class extends y_{select(t){let e=!1,r=(t??"*").split("").map(o=>/\s/.test(o)&&!e?"":(o==='"'&&(e=!e),o)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:o,referencedTable:n=o}={}){let s=n?`${n}.order`:"order",i=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(o,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:o=r}={}){let n=typeof o>"u"?"offset":`${o}.offset`,s=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(s,`${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.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:o=!1,wal:n=!1,format:s="text"}={}){var i;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,o?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="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}},of=new RegExp("[,()]"),Ro=class extends b_{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(o=>typeof o=="string"&&of.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&of.test(o)?`"${o}"`:`${o}`).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:o}={}){let n="";o==="plain"?n="pl":o==="phrase"?n="ph":o==="websearch"&&(n="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).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 o=r?`${r}.or`:"or";return this.url.searchParams.append(o,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},__=class{constructor(t,{headers:e={},schema:r,fetch:o,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=o,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:o}=e??{},n=r?"HEAD":"GET",s=!1,i=(t??"*").split("").map(u=>/\s/.test(u)&&!s?"":(u==='"'&&(s=!s),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",i),o&&l.append("Prefer",`count=${o}`),new Ro({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var o;let n="POST",{url:s,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){let l=[...new Set(a)].map(u=>`"${u}"`);s.searchParams.set("columns",l.join(","))}}return new Ro({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:o,defaultToNull:n=!0}={}){var s;let i="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),o&&l.append("Prefer",`count=${o}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let u=t.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(u.length>0){let c=[...new Set(u)].map(d=>`"${d}"`);a.searchParams.set("columns",c.join(","))}}return new Ro({method:i,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let o="PATCH",{url:n,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Ro({method:o,url:n,headers:s,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:o,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Ro({method:r,url:o,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Hn(t){"@babel/helpers - typeof";return Hn=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},Hn(t)}function w_(t,e){if(Hn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Hn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function v_(t){var e=w_(t,"string");return Hn(e)=="symbol"?e:e+""}function S_(t,e,r){return(e=v_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function nf(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function li(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?nf(Object(r),!0).forEach(function(o){S_(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):nf(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var af=class lf{constructor(e,{headers:r={},schema:o,fetch:n,timeout:s,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=o,this.urlLengthLimit=i;let a=n??globalThis.fetch;s!==void 0&&s>0?this.fetch=(l,u)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),s),f=u?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,u);let m=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",m,{once:!0}),a(l,li(li({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",m)})}return a(l,li(li({},u),{},{signal:c.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 __(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new lf(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:o=!1,get:n=!1,count:s}={}){var i;let a,l=new URL(`${this.url}/rpc/${e}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),d=o&&Object.values(r).some(c);d?(a="POST",u=r):o||n?(a=o?"HEAD":"GET",Object.entries(r).filter(([m,h])=>h!==void 0).map(([m,h])=>[m,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([m,h])=>{l.searchParams.append(m,h)})):(a="POST",u=r);let f=new Headers(this.headers);return d?f.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&f.set("Prefer",`count=${s}`),new Ro({method:a,url:l,headers:f,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};var ql=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 o=r.versions;if(o&&o.node){let n=o.node,s=parseInt(n.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
48
|
+
${c.stack}`)}else{var g;a=(g=s?.stack)!==null&&g!==void 0?g:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${y} 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.`)):(c?.name==="HeadersOverflowError"||c?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(l+=`. Your request URL is ${y} 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:`${(i=s?.name)!==null&&i!==void 0?i:"FetchError"}: ${s?.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},b_=class extends y_{select(t){let e=!1,r=(t??"*").split("").map(o=>/\s/.test(o)&&!e?"":(o==='"'&&(e=!e),o)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:o,referencedTable:n=o}={}){let s=n?`${n}.order`:"order",i=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(o,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:o=r}={}){let n=typeof o>"u"?"offset":`${o}.offset`,s=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(s,`${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.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:o=!1,wal:n=!1,format:s="text"}={}){var i;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,o?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="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}},sf=new RegExp("[,()]"),Ro=class extends b_{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(o=>typeof o=="string"&&sf.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&sf.test(o)?`"${o}"`:`${o}`).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:o}={}){let n="";o==="plain"?n="pl":o==="phrase"?n="ph":o==="websearch"&&(n="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).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 o=r?`${r}.or`:"or";return this.url.searchParams.append(o,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},__=class{constructor(t,{headers:e={},schema:r,fetch:o,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=o,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:o}=e??{},n=r?"HEAD":"GET",s=!1,i=(t??"*").split("").map(u=>/\s/.test(u)&&!s?"":(u==='"'&&(s=!s),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",i),o&&l.append("Prefer",`count=${o}`),new Ro({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var o;let n="POST",{url:s,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){let l=[...new Set(a)].map(u=>`"${u}"`);s.searchParams.set("columns",l.join(","))}}return new Ro({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:o,defaultToNull:n=!0}={}){var s;let i="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),o&&l.append("Prefer",`count=${o}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let u=t.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(u.length>0){let c=[...new Set(u)].map(d=>`"${d}"`);a.searchParams.set("columns",c.join(","))}}return new Ro({method:i,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let o="PATCH",{url:n,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Ro({method:o,url:n,headers:s,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:o,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Ro({method:r,url:o,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Hn(t){"@babel/helpers - typeof";return Hn=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},Hn(t)}function w_(t,e){if(Hn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Hn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function v_(t){var e=w_(t,"string");return Hn(e)=="symbol"?e:e+""}function S_(t,e,r){return(e=v_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function af(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function li(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?af(Object(r),!0).forEach(function(o){S_(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):af(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var uf=class cf{constructor(e,{headers:r={},schema:o,fetch:n,timeout:s,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=o,this.urlLengthLimit=i;let a=n??globalThis.fetch;s!==void 0&&s>0?this.fetch=(l,u)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),s),f=u?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,u);let m=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",m,{once:!0}),a(l,li(li({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",m)})}return a(l,li(li({},u),{},{signal:c.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 __(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new cf(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:o=!1,get:n=!1,count:s}={}){var i;let a,l=new URL(`${this.url}/rpc/${e}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),d=o&&Object.values(r).some(c);d?(a="POST",u=r):o||n?(a=o?"HEAD":"GET",Object.entries(r).filter(([m,h])=>h!==void 0).map(([m,h])=>[m,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([m,h])=>{l.searchParams.append(m,h)})):(a="POST",u=r);let f=new Headers(this.headers);return d?f.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&f.set("Prefer",`count=${s}`),new Ro({method:a,url:l,headers:f,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};var Wl=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 o=r.versions;if(o&&o.node){let n=o.node,s=parseInt(n.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
49
49
|
import ws from "ws"
|
|
50
50
|
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+=`
|
|
51
51
|
|
|
52
|
-
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},Vl=ql;var uf="2.100.1";var cf=`realtime-js/${uf}`,df="1.0.0",Wl="2.0.0",ff=Wl;var mf=1e4;var hf=100;var Dt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ui={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var zn={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var Gn=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 o=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(o))}_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,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,o){var n,s;let i=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",u=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(c).length===0?"":JSON.stringify(c);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(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.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+i.length+u.length+d.length,m=new ArrayBuffer(this.HEADER_LENGTH+f),h=new DataView(m),g=0;h.setUint8(g++,this.KINDS.userBroadcastPush),h.setUint8(g++,l.length),h.setUint8(g++,a.length),h.setUint8(g++,i.length),h.setUint8(g++,u.length),h.setUint8(g++,d.length),h.setUint8(g++,r),Array.from(l,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(i,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(u,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>h.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(m.byteLength+o.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(o),m.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let o=this._binaryDecode(e);return r(o)}if(typeof e=="string"){let o=JSON.parse(e),[n,s,i,a,l]=o;return r({join_ref:n,ref:s,topic:i,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),o=r.getUint8(0),n=new TextDecoder;if(o===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,o){let n=r.getUint8(1),s=r.getUint8(2),i=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,u=o.decode(e.slice(l,l+n));l=l+n;let c=o.decode(e.slice(l,l+s));l=l+s;let d=o.decode(e.slice(l,l+i));l=l+i;let f=e.slice(l,e.byteLength),m=a===this.JSON_ENCODING?JSON.parse(o.decode(f)):f,h={type:this.BROADCAST_EVENT,event:c,payload:m};return i>0&&(h.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:h}}_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(([o])=>r.includes(o)))}};var re;(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"})(re||(re={}));var zl=(t,e,r={})=>{var o;let n=(o=r.skipTypes)!==null&&o!==void 0?o:[];return e?Object.keys(e).reduce((s,i)=>(s[i]=x_(i,t,e,n),s),{}):{}},x_=(t,e,r,o)=>{let n=e.find(a=>a.name===t),s=n?.type,i=r[t];return s&&!o.includes(s)?pf(s,i):Hl(i)},pf=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return E_(e,r)}switch(t){case re.bool:return k_(e);case re.float4:case re.float8:case re.int2:case re.int4:case re.int8:case re.numeric:case re.oid:return T_(e);case re.json:case re.jsonb:return C_(e);case re.timestamp:return P_(e);case re.abstime:case re.date:case re.daterange:case re.int4range:case re.int8range:case re.money:case re.reltime:case re.text:case re.time:case re.timestamptz:case re.timetz:case re.tsrange:case re.tstzrange:return Hl(e);default:return Hl(e)}},Hl=t=>t,k_=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},T_=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},C_=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},E_=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,o=t[r];if(t[0]==="{"&&o==="}"){let s,i=t.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map(a=>pf(e,a))}return t},P_=t=>typeof t=="string"?t.replace(" ","T"):t,ci=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};var Kn=class t{constructor(e,r){let o=R_(r);this.presence=new $s(e.getChannel(),o),this.presence.onJoin((n,s,i)=>{let a=t.onJoinPayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,s,i)=>{let a=t.onLeavePayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=A_(e),Object.getOwnPropertyNames(e).reduce((r,o)=>{let n=e[o];return r[o]=di(n),r},{})}static onJoinPayload(e,r,o){let n=gf(r),s=di(o);return{event:"join",key:e,currentPresences:n,newPresences:s}}static onLeavePayload(e,r,o){let n=gf(r),s=di(o);return{event:"leave",key:e,currentPresences:n,leftPresences:s}}};function di(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function A_(t){return JSON.parse(JSON.stringify(t))}function R_(t){return t?.events&&{events:t.events}}function gf(t){return t?.metas?di(t):[]}var Gl;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Gl||(Gl={}));var Io=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Kn(this.channel.channelAdapter,r)}};var Jn=class{constructor(e,r,o){let n=I_(o);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,o){let n;try{n=this.channel.push(e,r,o)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>hf){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===Dt.joined}isJoined(){return this.state===Dt.joined}isJoining(){return this.state===Dt.joining}isClosed(){return this.state===Dt.closed}isLeaving(){return this.state===Dt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function I_(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Kl;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Kl||(Kl={}));var Do;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Do||(Do={}));var Lt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Lt||(Lt={}));var Lo=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},o){var n,s;if(this.topic=e,this.params=r,this.socket=o,this.bindings={},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.channelAdapter=new Jn(this.socket.socketAdapter,e,this.params),this.presence=new Io(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=ci(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||s===void 0)&&s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var o,n,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:l}}=this.params,u=(n=(o=this.bindings.postgres_changes)===null||o===void 0?void 0:o.map(m=>m.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[Do.PRESENCE]&&this.bindings[Do.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},f={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(Lt.CHANNEL_ERROR,m)}),this._onClose(()=>e?.(Lt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(Lt.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=Dt.errored,e?.(Lt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{e?.(Lt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var o;let n=this.bindings.postgres_changes,s=(o=n?.length)!==null&&o!==void 0?o:0,i=[];for(let a=0;a<s;a++){let l=n[a],{filter:{event:u,schema:c,table:d,filter:f}}=l,m=e&&e[a];if(m&&m.event===u&&t.isFilterValueEqual(m.schema,c)&&t.isFilterValueEqual(m.table,d)&&t.isFilterValueEqual(m.filter,f))i.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=Dt.errored,r?.(Lt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=Dt.errored&&r&&r(Lt.SUBSCRIBED)}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,o){if(this.channelAdapter.isJoined()&&e===Do.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,o)}async httpSend(e,r,o={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=o.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var o,n;if(!this.channelAdapter.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:s,payload:i}=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:s,payload:i,private:this.private}]})};try{let u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(o=r.timeout)!==null&&o!==void 0?o:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var i,a,l;let u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(i=this.params)===null||i===void 0?void 0:i.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,o){let n=new AbortController,s=setTimeout(()=>n.abort(),o),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(s),i}_on(e,r,o){let n=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,o),i={type:n,filter:r,callback:o,ref:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,o)=>{var n,s,i,a,l,u,c;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,o))return!1;let f=(n=this.bindings[d])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in f){let m=f.id,h=(s=f.filter)===null||s===void 0?void 0:s.event;return m&&((i=r.ids)===null||i===void 0?void 0:i.includes(m))&&(h==="*"||h?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let m=(u=(l=f?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((c=r?.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:o,error:n,leave:s,join:i}=ui;return r&&[o,n,s,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,o)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:s,table:i,commit_timestamp:a,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:s,table:i,commit_timestamp:a,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=zl(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=zl(e.columns,e.old_record)),r}};var Yn=class{constructor(e,r){this.socket=new Bs(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,o,n=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),n),this.socket.disconnect(()=>{e(),s("ok")},r,o)})}push(e){this.socket.push(e)}log(e,r,o){this.socket.log(e,r,o)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==zn.connecting}isDisconnecting(){return this.socket.connectionState()==zn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var D_={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},L_=[1e3,2e3,5e3,1e4],N_=1e4,j_=`
|
|
52
|
+
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},Hl=Wl;var df="2.100.1";var ff=`realtime-js/${df}`,mf="1.0.0",zl="2.0.0",hf=zl;var pf=1e4;var gf=100;var Dt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ui={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var zn={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var Gn=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 o=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(o))}_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,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,o){var n,s;let i=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",u=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(c).length===0?"":JSON.stringify(c);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(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.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+i.length+u.length+d.length,m=new ArrayBuffer(this.HEADER_LENGTH+f),h=new DataView(m),g=0;h.setUint8(g++,this.KINDS.userBroadcastPush),h.setUint8(g++,l.length),h.setUint8(g++,a.length),h.setUint8(g++,i.length),h.setUint8(g++,u.length),h.setUint8(g++,d.length),h.setUint8(g++,r),Array.from(l,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(i,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(u,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>h.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(m.byteLength+o.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(o),m.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let o=this._binaryDecode(e);return r(o)}if(typeof e=="string"){let o=JSON.parse(e),[n,s,i,a,l]=o;return r({join_ref:n,ref:s,topic:i,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),o=r.getUint8(0),n=new TextDecoder;if(o===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,o){let n=r.getUint8(1),s=r.getUint8(2),i=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,u=o.decode(e.slice(l,l+n));l=l+n;let c=o.decode(e.slice(l,l+s));l=l+s;let d=o.decode(e.slice(l,l+i));l=l+i;let f=e.slice(l,e.byteLength),m=a===this.JSON_ENCODING?JSON.parse(o.decode(f)):f,h={type:this.BROADCAST_EVENT,event:c,payload:m};return i>0&&(h.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:h}}_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(([o])=>r.includes(o)))}};var re;(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"})(re||(re={}));var Kl=(t,e,r={})=>{var o;let n=(o=r.skipTypes)!==null&&o!==void 0?o:[];return e?Object.keys(e).reduce((s,i)=>(s[i]=x_(i,t,e,n),s),{}):{}},x_=(t,e,r,o)=>{let n=e.find(a=>a.name===t),s=n?.type,i=r[t];return s&&!o.includes(s)?yf(s,i):Gl(i)},yf=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return E_(e,r)}switch(t){case re.bool:return k_(e);case re.float4:case re.float8:case re.int2:case re.int4:case re.int8:case re.numeric:case re.oid:return T_(e);case re.json:case re.jsonb:return C_(e);case re.timestamp:return P_(e);case re.abstime:case re.date:case re.daterange:case re.int4range:case re.int8range:case re.money:case re.reltime:case re.text:case re.time:case re.timestamptz:case re.timetz:case re.tsrange:case re.tstzrange:return Gl(e);default:return Gl(e)}},Gl=t=>t,k_=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},T_=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},C_=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},E_=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,o=t[r];if(t[0]==="{"&&o==="}"){let s,i=t.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map(a=>yf(e,a))}return t},P_=t=>typeof t=="string"?t.replace(" ","T"):t,ci=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};var Kn=class t{constructor(e,r){let o=R_(r);this.presence=new $s(e.getChannel(),o),this.presence.onJoin((n,s,i)=>{let a=t.onJoinPayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,s,i)=>{let a=t.onLeavePayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=A_(e),Object.getOwnPropertyNames(e).reduce((r,o)=>{let n=e[o];return r[o]=di(n),r},{})}static onJoinPayload(e,r,o){let n=bf(r),s=di(o);return{event:"join",key:e,currentPresences:n,newPresences:s}}static onLeavePayload(e,r,o){let n=bf(r),s=di(o);return{event:"leave",key:e,currentPresences:n,leftPresences:s}}};function di(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function A_(t){return JSON.parse(JSON.stringify(t))}function R_(t){return t?.events&&{events:t.events}}function bf(t){return t?.metas?di(t):[]}var Jl;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Jl||(Jl={}));var Io=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Kn(this.channel.channelAdapter,r)}};var Jn=class{constructor(e,r,o){let n=I_(o);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,o){let n;try{n=this.channel.push(e,r,o)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>gf){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===Dt.joined}isJoined(){return this.state===Dt.joined}isJoining(){return this.state===Dt.joining}isClosed(){return this.state===Dt.closed}isLeaving(){return this.state===Dt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function I_(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Yl;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Yl||(Yl={}));var Do;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Do||(Do={}));var Lt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Lt||(Lt={}));var Lo=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},o){var n,s;if(this.topic=e,this.params=r,this.socket=o,this.bindings={},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.channelAdapter=new Jn(this.socket.socketAdapter,e,this.params),this.presence=new Io(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=ci(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||s===void 0)&&s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var o,n,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:l}}=this.params,u=(n=(o=this.bindings.postgres_changes)===null||o===void 0?void 0:o.map(m=>m.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[Do.PRESENCE]&&this.bindings[Do.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},f={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(Lt.CHANNEL_ERROR,m)}),this._onClose(()=>e?.(Lt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(Lt.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=Dt.errored,e?.(Lt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{e?.(Lt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var o;let n=this.bindings.postgres_changes,s=(o=n?.length)!==null&&o!==void 0?o:0,i=[];for(let a=0;a<s;a++){let l=n[a],{filter:{event:u,schema:c,table:d,filter:f}}=l,m=e&&e[a];if(m&&m.event===u&&t.isFilterValueEqual(m.schema,c)&&t.isFilterValueEqual(m.table,d)&&t.isFilterValueEqual(m.filter,f))i.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=Dt.errored,r?.(Lt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=Dt.errored&&r&&r(Lt.SUBSCRIBED)}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,o){if(this.channelAdapter.isJoined()&&e===Do.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,o)}async httpSend(e,r,o={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=o.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var o,n;if(!this.channelAdapter.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:s,payload:i}=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:s,payload:i,private:this.private}]})};try{let u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(o=r.timeout)!==null&&o!==void 0?o:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var i,a,l;let u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(i=this.params)===null||i===void 0?void 0:i.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,o){let n=new AbortController,s=setTimeout(()=>n.abort(),o),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(s),i}_on(e,r,o){let n=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,o),i={type:n,filter:r,callback:o,ref:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,o)=>{var n,s,i,a,l,u,c;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,o))return!1;let f=(n=this.bindings[d])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in f){let m=f.id,h=(s=f.filter)===null||s===void 0?void 0:s.event;return m&&((i=r.ids)===null||i===void 0?void 0:i.includes(m))&&(h==="*"||h?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let m=(u=(l=f?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((c=r?.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:o,error:n,leave:s,join:i}=ui;return r&&[o,n,s,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,o)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:s,table:i,commit_timestamp:a,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:s,table:i,commit_timestamp:a,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Kl(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Kl(e.columns,e.old_record)),r}};var Yn=class{constructor(e,r){this.socket=new Bs(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,o,n=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),n),this.socket.disconnect(()=>{e(),s("ok")},r,o)})}push(e){this.socket.push(e)}log(e,r,o){this.socket.log(e,r,o)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==zn.connecting}isDisconnecting(){return this.socket.connectionState()==zn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var D_={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},L_=[1e3,2e3,5e3,1e4],N_=1e4,j_=`
|
|
53
53
|
addEventListener("message", (e) => {
|
|
54
54
|
if (e.data.event === "start") {
|
|
55
55
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
@@ -67,9 +67,9 @@ Option 2: Install and provide the "ws" package:
|
|
|
67
67
|
const client = new RealtimeClient(url, {
|
|
68
68
|
...options,
|
|
69
69
|
transport: ws
|
|
70
|
-
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async o=>{let n=await o.unsubscribe();return o.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,o){this.socketAdapter.log(e,r,o)}connectionState(){return this.socketAdapter.connectionState()||zn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let o=`realtime:${e}`,n=this.getChannels().find(s=>s.topic===o);if(n)return n;{let s=new Lo(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,o=!1;if(e)r=e,o=!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;o?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let s={access_token:r,version:cf};r&&n.updateJoinPayload(s),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(ui.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)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,o)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,o)}}_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.disconnect()},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)}_workerObjectUrl(e){let r;if(e)r=e;else{let o=new Blob([j_],{type:"application/javascript"});r=URL.createObjectURL(o)}return r}_initializeOptions(e){var r,o,n,s,i,a,l,u,c;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null;let d={};d.timeout=(n=e?.timeout)!==null&&n!==void 0?n:mf,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:D_.HEARTBEAT_INTERVAL,d.transport=(i=e?.transport)!==null&&i!==void 0?i:Vl.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(g=>L_[g-1]||N_);let f,m,h=(l=e?.vsn)!==null&&l!==void 0?l:ff;switch(h){case df:f=(g,y)=>y(JSON.stringify(g)),m=(g,y)=>y(JSON.parse(g));break;case Wl:f=this.serializer.encode.bind(this.serializer),m=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=h,d.encode=(u=e?.encode)!==null&&u!==void 0?u:f,d.decode=(c=e?.decode)!==null&&c!==void 0?c:m,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var fi=class extends Error{constructor(t,e="storage",r,o){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=o}};function mi(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Jl=class extends fi{constructor(t,e,r,o="storage"){super(t,o,e,r),this.name=o==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},wf=class extends fi{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var M_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),U_=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)},Yl=t=>{if(Array.isArray(t))return t.map(r=>Yl(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,o])=>{let n=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[n]=Yl(o)}),e},F_=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function Qn(t){"@babel/helpers - typeof";return Qn=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},Qn(t)}function $_(t,e){if(Qn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Qn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function B_(t){var e=$_(t,"string");return Qn(e)=="symbol"?e:e+""}function q_(t,e,r){return(e=B_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function yf(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function D(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?yf(Object(r),!0).forEach(function(o){q_(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):yf(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var bf=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)},V_=async(t,e,r,o)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let n=t,s=parseInt(n.status,10);Number.isFinite(s)||(s=500),n.json().then(i=>{let a=i?.statusCode||i?.code||s+"";e(new Jl(bf(i),s,a,o))}).catch(()=>{let i=s+"";e(new Jl(n.statusText||`HTTP ${s} error`,s,i,o))})}else e(new wf(bf(t),t,o))},W_=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!o?D(D({},n),r):(U_(o)?(n.headers=D({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(o)):n.body=o,e?.duplex&&(n.duplex=e.duplex),D(D({},n),r))};async function Xn(t,e,r,o,n,s,i){return new Promise((a,l)=>{t(r,W_(e,o,n,s)).then(u=>{if(!u.ok)throw u;if(o?.noResolveJson)return u;if(i==="vectors"){let c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>V_(u,l,o,i))})}function vf(t="storage"){return{get:async(e,r,o,n)=>Xn(e,"GET",r,o,n,void 0,t),post:async(e,r,o,n,s)=>Xn(e,"POST",r,n,s,o,t),put:async(e,r,o,n,s)=>Xn(e,"PUT",r,n,s,o,t),head:async(e,r,o,n)=>Xn(e,"HEAD",r,D(D({},o),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,o,n,s)=>Xn(e,"DELETE",r,n,s,o,t)}}var H_=vf("storage"),{get:Zn,post:_t,put:Xl,head:z_,remove:Ql}=H_,Ke=vf("vectors"),jo=class{constructor(t,e={},r,o="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=M_(r),this.namespace=o}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=D(D({},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(mi(r))return{data:null,error:r};throw r}}},G_=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(mi(e))return{data:null,error:e};throw e}}},Sf;Sf=Symbol.toStringTag;var K_=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Sf]="BlobDownloadBuilder",this.promise=null}asStream(){return new G_(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(mi(e))return{data:null,error:e};throw e}}},J_={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_f={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Y_=class extends jo{constructor(t,e={},r,o){super(t,e,o,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,o){var n=this;return n.handleOperation(async()=>{let s,i=D(D({},_f),o),a=D(D({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)}),l=i.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",i.cacheControl),l&&s.append("metadata",n.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",i.cacheControl),l&&!s.has("metadata")&&s.append("metadata",n.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${i.cacheControl}`,a["content-type"]=i.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!i.duplex&&(i.duplex="half")),o?.headers&&(a=D(D({},a),o.headers));let u=n._removeEmptyFolders(e),c=n._getFinalPath(u),d=await(t=="PUT"?Xl:_t)(n.fetch,`${n.url}/object/${c}`,s,D({headers:a},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,o){var n=this;let s=n._removeEmptyFolders(t),i=n._getFinalPath(s),a=new URL(n.url+`/object/upload/sign/${i}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,u=D(D({},_f),o),c=D(D({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:s,fullPath:(await Xl(n.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let o=r._getFinalPath(t),n=D({},r.headers);e?.upsert&&(n["x-upsert"]="true");let s=await _t(r.fetch,`${r.url}/object/upload/sign/${o}`,{},{headers:n}),i=new URL(r.url+s.url),a=i.searchParams.get("token");if(!a)throw new fi("No token returned by API");return{signedUrl:i.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var o=this;return o.handleOperation(async()=>await _t(o.fetch,`${o.url}/object/move`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers}))}async copy(t,e,r){var o=this;return o.handleOperation(async()=>({path:(await _t(o.fetch,`${o.url}/object/copy`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers})).Key}))}async createSignedUrl(t,e,r){var o=this;return o.handleOperation(async()=>{let n=o._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,i=await _t(o.fetch,`${o.url}/object/sign/${n}`,D({expiresIn:e},s?{transform:r.transform}:{}),{headers:o.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",l=s&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${o.url}${l}${a}`)}})}async createSignedUrls(t,e,r){var o=this;return o.handleOperation(async()=>{let n=await _t(o.fetch,`${o.url}/object/sign/${o.bucketId}`,{expiresIn:e,paths:t},{headers:o.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(i=>D(D({},i),{},{signedUrl:i.signedURL?encodeURI(`${o.url}${i.signedURL}${s}`):null}))})}download(t,e,r){let o=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),s=n?`?${n}`:"",i=this._getFinalPath(t),a=()=>Zn(this.fetch,`${this.url}/${o}/${i}${s}`,{headers:this.headers,noResolveJson:!0},r);return new K_(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>Yl(await Zn(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await z_(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(mi(n)){var o;let s=n instanceof Jl?n.status:n instanceof wf?(o=n.originalError)===null||o===void 0?void 0:o.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),o=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&o.push(n);let s=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&o.push(i);let a=o.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await Ql(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var o=this;return o.handleOperation(async()=>{let n=D(D(D({},J_),e),{},{prefix:t||""});return await _t(o.fetch,`${o.url}/object/list/${o.bucketId}`,n,{headers:o.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let o=D({},t);return await _t(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,o,{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("&")}},X_="2.100.1",es={"X-Client-Info":`storage-js/${X_}`},Q_=class extends jo{constructor(t,e={},r,o){let n=new URL(t);o?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let s=n.href.replace(/\/$/,""),i=D(D({},es),e);super(s,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Zn(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Zn(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await _t(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 Xl(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 _t(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ql(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():""}},Z_=class extends jo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},es),e);super(o,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await _t(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 o=r.toString(),n=o?`${e.url}/bucket?${o}`:`${e.url}/bucket`;return await Zn(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ql(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!F_(t))throw new fi("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 Ws({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),o=this.shouldThrowOnError;return new Proxy(r,{get(n,s){let i=n[s];return typeof i!="function"?i:async(...a)=>{try{return{data:await i.apply(n,a),error:null}}catch(l){if(o)throw l;return{data:null,error:l}}}}})}},ew=class extends jo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},es),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ke.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ke.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},tw=class extends jo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},es),{},{"Content-Type":"application/json"},e);super(o,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 Ke.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ke.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 Ke.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ke.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 Ke.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},rw=class extends jo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},es),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},ow=class extends rw{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new nw(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)}},nw=class extends ew{constructor(t,e,r,o){super(t,e,o),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,D(D({},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 sw(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},sw=class extends tw{constructor(t,e,r,o,n){super(t,e,n),this.vectorBucketName=r,this.indexName=o}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},xf=class extends Q_{constructor(t,e={},r,o){super(t,e,r,o)}from(t){return new Y_(this.url,this.headers,t,this.fetch)}get vectors(){return new ow(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Z_(this.url+"/iceberg",this.headers,this.fetch)}};var hi="2.100.1";var Br=30*1e3,pi=3,gi=pi*Br,kf="http://localhost:9999",Tf="supabase.auth.token";var Cf={"X-Client-Info":`gotrue-js/${hi}`};var ts="X-Supabase-Api-Version",Zl={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Ef=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Pf=600*1e3;var pr=class extends Error{constructor(e,r,o){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=o}};function T(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var yi=class extends pr{constructor(e,r,o){super(e,r,o),this.name="AuthApiError",this.status=r,this.code=o}};function Of(t){return T(t)&&t.name==="AuthApiError"}var it=class extends pr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},wt=class extends pr{constructor(e,r,o,n){super(e,o,n),this.name=r,this.status=o}},Oe=class extends wt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function _i(t){return T(t)&&t.name==="AuthSessionMissingError"}var Yt=class extends wt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},qr=class extends wt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Vr=class extends wt{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}}};function Af(t){return T(t)&&t.name==="AuthImplicitGrantRedirectError"}var rs=class extends wt{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}}},bi=class extends wt{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")}};var Mo=class extends wt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function wi(t){return T(t)&&t.name==="AuthRetryableFetchError"}var os=class extends wt{constructor(e,r,o){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=o}};var Wr=class extends wt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var vi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Rf=`
|
|
71
|
-
\r=`.split(""),iw=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Rf.length;e+=1)t[Rf[e].charCodeAt(0)]=-2;for(let e=0;e<vi.length;e+=1)t[vi[e].charCodeAt(0)]=e;return t})();function If(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(vi[o]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(vi[o]),e.queuedBits-=6}}function Df(t,e,r){let o=iw[t];if(o>-1)for(e.queue=e.queue<<6|o,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(o===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function eu(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},s=i=>{uw(i,o,r)};for(let i=0;i<t.length;i+=1)Df(t.charCodeAt(i),n,s);return e.join("")}function aw(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 lw(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}aw(o,e)}}function uw(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;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 gr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)Df(t.charCodeAt(n),r,o);return new Uint8Array(e)}function Lf(t){let e=[];return lw(t,r=>e.push(r)),new Uint8Array(e)}function Xt(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};return t.forEach(n=>If(n,r,o)),If(null,r,o),e.join("")}function Nf(t){return Math.round(Date.now()/1e3)+t}function jf(){return Symbol("auth-callback")}var _e=()=>typeof window<"u"&&typeof document<"u",Hr={tested:!1,writable:!1},Si=()=>{if(!_e())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Hr.tested)return Hr.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Hr.tested=!0,Hr.writable=!0}catch{Hr.tested=!0,Hr.writable=!1}return Hr.writable};function Mf(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,s)=>{e[s]=n})}catch{}return r.searchParams.forEach((o,n)=>{e[n]=o}),e}var xi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Uf=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",zr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},yr=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Ce=async(t,e)=>{await t.removeItem(e)},ns=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};ns.promiseConstructor=Promise;function ss(t){let e=t.split(".");if(e.length!==3)throw new Wr("Invalid JWT structure");for(let o=0;o<e.length;o++)if(!Ef.test(e[o]))throw new Wr("JWT not in base64url format");return{header:JSON.parse(eu(e[0])),payload:JSON.parse(eu(e[1])),signature:gr(e[2]),raw:{header:e[0],payload:e[1]}}}async function Ff(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function $f(t,e){return new Promise((o,n)=>{(async()=>{for(let s=0;s<1/0;s++)try{let i=await t(s);if(!e(s,null,i)){o(i);return}}catch(i){if(!e(s,i)){n(i);return}}})()})}function cw(t){return("0"+t.toString(16)).substr(-2)}function dw(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=r.length,n="";for(let s=0;s<56;s++)n+=r.charAt(Math.floor(Math.random()*o));return n}return crypto.getRandomValues(e),Array.from(e,cw).join("")}async function fw(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(o);return Array.from(n).map(s=>String.fromCharCode(s)).join("")}async function mw(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 fw(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Gr(t,e,r=!1){let o=dw(),n=o;r&&(n+="/PASSWORD_RECOVERY"),await zr(t,`${e}-code-verifier`,n);let s=await mw(o);return[s,o===s?"plain":"s256"]}var hw=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Bf(t){let e=t.headers.get(ts);if(!e||!e.match(hw))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function qf(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 Vf(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 pw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Kr(t){if(!pw.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ki(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let o=r.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="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 Wf(t,e){return new Proxy(t,{get:(r,o,n)=>{if(o==="__isInsecureUserWarningProxy")return!0;if(typeof o=="symbol"){let s=o.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,o,n)}return!e.value&&typeof o=="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,o,n)}})}function tu(t){return JSON.parse(JSON.stringify(t))}var Jr=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),gw=[502,503,504];async function Hf(t){var e;if(!Uf(t))throw new Mo(Jr(t),0);if(gw.includes(t.status))throw new Mo(Jr(t),t.status);let r;try{r=await t.json()}catch(s){throw new it(Jr(s),s)}let o,n=Bf(t);if(n&&n.getTime()>=Zl["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?o=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(o=r.error_code),o){if(o==="weak_password")throw new os(Jr(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(o==="session_not_found")throw new Oe}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((s,i)=>s&&typeof i=="string",!0))throw new os(Jr(r),t.status,r.weak_password.reasons);throw new yi(Jr(r),t.status||500,o)}var yw=(t,e,r,o)=>{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(o),Object.assign(Object.assign({},n),r))};async function A(t,e,r,o){var n;let s=Object.assign({},o?.headers);s[ts]||(s[ts]=Zl["2024-01-01"].name),o?.jwt&&(s.Authorization=`Bearer ${o.jwt}`);let i=(n=o?.query)!==null&&n!==void 0?n:{};o?.redirectTo&&(i.redirect_to=o.redirectTo);let a=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await bw(t,e,r+a,{headers:s,noResolveJson:o?.noResolveJson},{},o?.body);return o?.xform?o?.xform(l):{data:Object.assign({},l),error:null}}async function bw(t,e,r,o,n,s){let i=yw(e,o,n,s),a;try{a=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new Mo(Jr(l),0)}if(a.ok||await Hf(a),o?.noResolveJson)return a;try{return await a.json()}catch(l){await Hf(l)}}function at(t){var e;let r=null;_w(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Nf(t.expires_in)));let o=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:o},error:null}}function ru(t){let e=at(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,o)=>r&&typeof o=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Nt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function zf(t){return{data:t,error:null}}function Gf(t){let{action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s}=t,i=Be(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s},l=Object.assign({},i);return{data:{properties:a,user:l},error:null}}function ou(t){return t}function _w(t){return t.access_token&&t.refresh_token&&t.expires_in}var Ti=["global","local","others"];var Yr=class{constructor({url:e="",headers:r={},fetch:o}){this.url=e,this.headers=r,this.fetch=xi(o),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)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,r=Ti[0]){if(Ti.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ti.join(", ")}`);try{return await A(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(o){if(T(o))return{data:null,error:o};throw o}}async inviteUserByEmail(e,r={}){try{return await A(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Nt})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async generateLink(e){try{let{options:r}=e,o=Be(e,["options"]),n=Object.assign(Object.assign({},o),r);return"newEmail"in o&&(n.new_email=o?.newEmail,delete n.newEmail),await A(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Gf,redirectTo:r?.redirectTo})}catch(r){if(T(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await A(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Nt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await A(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:ou});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(T(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Kr(e);try{return await A(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Nt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Kr(e);try{return await A(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Nt})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async deleteUser(e,r=!1){Kr(e);try{return await A(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Nt})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async _listFactors(e){Kr(e.userId);try{let{data:r,error:o}=await A(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:o}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Kr(e.userId),Kr(e.id);try{return{data:await A(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await A(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:ou});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(T(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await A(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await A(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await A(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(T(o))return{data:null,error:o};throw o}}async _deleteOAuthClient(e){try{return await A(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await A(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await A(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:o=>{var n;return{data:{providers:(n=o?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(T(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await A(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await A(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await A(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(T(o))return{data:null,error:o};throw o}}async _deleteCustomProvider(e){try{return await A(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}};function nu(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var vt={debug:!!(globalThis&&Si()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},is=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},as=class extends is{};async function su(t,e,r){vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let o=new globalThis.AbortController,n;e>0&&(n=setTimeout(()=>{o.abort(),vt.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:o.signal},async s=>{if(s){clearTimeout(n),vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new as(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(vt.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"),clearTimeout(n),await r()}})}catch(s){if(e>0&&clearTimeout(n),s?.name==="AbortError"&&e>0){if(o.signal.aborted)return vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async i=>{if(i){vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new as(`Lock "${t}" was released because another request stole it`)}throw s}}function Kf(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function iu(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Jf(t){return parseInt(t,16)}function Yf(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}function Xf(t){var e;let{chainId:r,domain:o,expirationTime:n,issuedAt:s=new Date,nonce:i,notBefore:a,requestId:l,resources:u,scheme:c,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(!o)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);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(`
|
|
72
|
-
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let m=
|
|
70
|
+
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async o=>{let n=await o.unsubscribe();return o.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,o){this.socketAdapter.log(e,r,o)}connectionState(){return this.socketAdapter.connectionState()||zn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let o=`realtime:${e}`,n=this.getChannels().find(s=>s.topic===o);if(n)return n;{let s=new Lo(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,o=!1;if(e)r=e,o=!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;o?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let s={access_token:r,version:ff};r&&n.updateJoinPayload(s),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(ui.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)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,o)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,o)}}_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.disconnect()},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)}_workerObjectUrl(e){let r;if(e)r=e;else{let o=new Blob([j_],{type:"application/javascript"});r=URL.createObjectURL(o)}return r}_initializeOptions(e){var r,o,n,s,i,a,l,u,c;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null;let d={};d.timeout=(n=e?.timeout)!==null&&n!==void 0?n:pf,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:D_.HEARTBEAT_INTERVAL,d.transport=(i=e?.transport)!==null&&i!==void 0?i:Hl.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(g=>L_[g-1]||N_);let f,m,h=(l=e?.vsn)!==null&&l!==void 0?l:hf;switch(h){case mf:f=(g,y)=>y(JSON.stringify(g)),m=(g,y)=>y(JSON.parse(g));break;case zl:f=this.serializer.encode.bind(this.serializer),m=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=h,d.encode=(u=e?.encode)!==null&&u!==void 0?u:f,d.decode=(c=e?.decode)!==null&&c!==void 0?c:m,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var fi=class extends Error{constructor(t,e="storage",r,o){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=o}};function mi(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Xl=class extends fi{constructor(t,e,r,o="storage"){super(t,o,e,r),this.name=o==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Sf=class extends fi{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var M_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),U_=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)},Ql=t=>{if(Array.isArray(t))return t.map(r=>Ql(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,o])=>{let n=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[n]=Ql(o)}),e},F_=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function Qn(t){"@babel/helpers - typeof";return Qn=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},Qn(t)}function $_(t,e){if(Qn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Qn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function B_(t){var e=$_(t,"string");return Qn(e)=="symbol"?e:e+""}function q_(t,e,r){return(e=B_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function _f(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function D(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?_f(Object(r),!0).forEach(function(o){q_(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):_f(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var wf=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)},V_=async(t,e,r,o)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let n=t,s=parseInt(n.status,10);Number.isFinite(s)||(s=500),n.json().then(i=>{let a=i?.statusCode||i?.code||s+"";e(new Xl(wf(i),s,a,o))}).catch(()=>{let i=s+"";e(new Xl(n.statusText||`HTTP ${s} error`,s,i,o))})}else e(new Sf(wf(t),t,o))},W_=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!o?D(D({},n),r):(U_(o)?(n.headers=D({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(o)):n.body=o,e?.duplex&&(n.duplex=e.duplex),D(D({},n),r))};async function Xn(t,e,r,o,n,s,i){return new Promise((a,l)=>{t(r,W_(e,o,n,s)).then(u=>{if(!u.ok)throw u;if(o?.noResolveJson)return u;if(i==="vectors"){let c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>V_(u,l,o,i))})}function xf(t="storage"){return{get:async(e,r,o,n)=>Xn(e,"GET",r,o,n,void 0,t),post:async(e,r,o,n,s)=>Xn(e,"POST",r,n,s,o,t),put:async(e,r,o,n,s)=>Xn(e,"PUT",r,n,s,o,t),head:async(e,r,o,n)=>Xn(e,"HEAD",r,D(D({},o),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,o,n,s)=>Xn(e,"DELETE",r,n,s,o,t)}}var H_=xf("storage"),{get:Zn,post:_t,put:Zl,head:z_,remove:eu}=H_,Ke=xf("vectors"),jo=class{constructor(t,e={},r,o="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=M_(r),this.namespace=o}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=D(D({},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(mi(r))return{data:null,error:r};throw r}}},G_=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(mi(e))return{data:null,error:e};throw e}}},kf;kf=Symbol.toStringTag;var K_=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[kf]="BlobDownloadBuilder",this.promise=null}asStream(){return new G_(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(mi(e))return{data:null,error:e};throw e}}},J_={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},vf={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Y_=class extends jo{constructor(t,e={},r,o){super(t,e,o,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,o){var n=this;return n.handleOperation(async()=>{let s,i=D(D({},vf),o),a=D(D({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)}),l=i.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",i.cacheControl),l&&s.append("metadata",n.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",i.cacheControl),l&&!s.has("metadata")&&s.append("metadata",n.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${i.cacheControl}`,a["content-type"]=i.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!i.duplex&&(i.duplex="half")),o?.headers&&(a=D(D({},a),o.headers));let u=n._removeEmptyFolders(e),c=n._getFinalPath(u),d=await(t=="PUT"?Zl:_t)(n.fetch,`${n.url}/object/${c}`,s,D({headers:a},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,o){var n=this;let s=n._removeEmptyFolders(t),i=n._getFinalPath(s),a=new URL(n.url+`/object/upload/sign/${i}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,u=D(D({},vf),o),c=D(D({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:s,fullPath:(await Zl(n.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let o=r._getFinalPath(t),n=D({},r.headers);e?.upsert&&(n["x-upsert"]="true");let s=await _t(r.fetch,`${r.url}/object/upload/sign/${o}`,{},{headers:n}),i=new URL(r.url+s.url),a=i.searchParams.get("token");if(!a)throw new fi("No token returned by API");return{signedUrl:i.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var o=this;return o.handleOperation(async()=>await _t(o.fetch,`${o.url}/object/move`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers}))}async copy(t,e,r){var o=this;return o.handleOperation(async()=>({path:(await _t(o.fetch,`${o.url}/object/copy`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers})).Key}))}async createSignedUrl(t,e,r){var o=this;return o.handleOperation(async()=>{let n=o._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,i=await _t(o.fetch,`${o.url}/object/sign/${n}`,D({expiresIn:e},s?{transform:r.transform}:{}),{headers:o.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",l=s&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${o.url}${l}${a}`)}})}async createSignedUrls(t,e,r){var o=this;return o.handleOperation(async()=>{let n=await _t(o.fetch,`${o.url}/object/sign/${o.bucketId}`,{expiresIn:e,paths:t},{headers:o.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(i=>D(D({},i),{},{signedUrl:i.signedURL?encodeURI(`${o.url}${i.signedURL}${s}`):null}))})}download(t,e,r){let o=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),s=n?`?${n}`:"",i=this._getFinalPath(t),a=()=>Zn(this.fetch,`${this.url}/${o}/${i}${s}`,{headers:this.headers,noResolveJson:!0},r);return new K_(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>Ql(await Zn(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await z_(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(mi(n)){var o;let s=n instanceof Xl?n.status:n instanceof Sf?(o=n.originalError)===null||o===void 0?void 0:o.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),o=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&o.push(n);let s=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&o.push(i);let a=o.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await eu(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var o=this;return o.handleOperation(async()=>{let n=D(D(D({},J_),e),{},{prefix:t||""});return await _t(o.fetch,`${o.url}/object/list/${o.bucketId}`,n,{headers:o.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let o=D({},t);return await _t(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,o,{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("&")}},X_="2.100.1",es={"X-Client-Info":`storage-js/${X_}`},Q_=class extends jo{constructor(t,e={},r,o){let n=new URL(t);o?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let s=n.href.replace(/\/$/,""),i=D(D({},es),e);super(s,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Zn(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Zn(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await _t(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 Zl(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 _t(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await eu(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():""}},Z_=class extends jo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},es),e);super(o,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await _t(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 o=r.toString(),n=o?`${e.url}/bucket?${o}`:`${e.url}/bucket`;return await Zn(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await eu(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!F_(t))throw new fi("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 Ws({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),o=this.shouldThrowOnError;return new Proxy(r,{get(n,s){let i=n[s];return typeof i!="function"?i:async(...a)=>{try{return{data:await i.apply(n,a),error:null}}catch(l){if(o)throw l;return{data:null,error:l}}}}})}},ew=class extends jo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},es),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ke.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ke.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},tw=class extends jo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},es),{},{"Content-Type":"application/json"},e);super(o,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 Ke.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ke.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 Ke.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ke.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 Ke.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},rw=class extends jo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},es),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ke.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},ow=class extends rw{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new nw(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)}},nw=class extends ew{constructor(t,e,r,o){super(t,e,o),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,D(D({},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 sw(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},sw=class extends tw{constructor(t,e,r,o,n){super(t,e,n),this.vectorBucketName=r,this.indexName=o}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Tf=class extends Q_{constructor(t,e={},r,o){super(t,e,r,o)}from(t){return new Y_(this.url,this.headers,t,this.fetch)}get vectors(){return new ow(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Z_(this.url+"/iceberg",this.headers,this.fetch)}};var hi="2.100.1";var Br=30*1e3,pi=3,gi=pi*Br,Cf="http://localhost:9999",Ef="supabase.auth.token";var Pf={"X-Client-Info":`gotrue-js/${hi}`};var ts="X-Supabase-Api-Version",tu={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Of=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Af=600*1e3;var pr=class extends Error{constructor(e,r,o){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=o}};function T(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var yi=class extends pr{constructor(e,r,o){super(e,r,o),this.name="AuthApiError",this.status=r,this.code=o}};function Rf(t){return T(t)&&t.name==="AuthApiError"}var it=class extends pr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},wt=class extends pr{constructor(e,r,o,n){super(e,o,n),this.name=r,this.status=o}},Oe=class extends wt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function _i(t){return T(t)&&t.name==="AuthSessionMissingError"}var Yt=class extends wt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},qr=class extends wt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Vr=class extends wt{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}}};function If(t){return T(t)&&t.name==="AuthImplicitGrantRedirectError"}var rs=class extends wt{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}}},bi=class extends wt{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")}};var Mo=class extends wt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function wi(t){return T(t)&&t.name==="AuthRetryableFetchError"}var os=class extends wt{constructor(e,r,o){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=o}};var Wr=class extends wt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var vi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Df=`
|
|
71
|
+
\r=`.split(""),iw=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Df.length;e+=1)t[Df[e].charCodeAt(0)]=-2;for(let e=0;e<vi.length;e+=1)t[vi[e].charCodeAt(0)]=e;return t})();function Lf(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(vi[o]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(vi[o]),e.queuedBits-=6}}function Nf(t,e,r){let o=iw[t];if(o>-1)for(e.queue=e.queue<<6|o,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(o===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function ru(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},s=i=>{uw(i,o,r)};for(let i=0;i<t.length;i+=1)Nf(t.charCodeAt(i),n,s);return e.join("")}function aw(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 lw(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}aw(o,e)}}function uw(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;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 gr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)Nf(t.charCodeAt(n),r,o);return new Uint8Array(e)}function jf(t){let e=[];return lw(t,r=>e.push(r)),new Uint8Array(e)}function Xt(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};return t.forEach(n=>Lf(n,r,o)),Lf(null,r,o),e.join("")}function Mf(t){return Math.round(Date.now()/1e3)+t}function Uf(){return Symbol("auth-callback")}var _e=()=>typeof window<"u"&&typeof document<"u",Hr={tested:!1,writable:!1},Si=()=>{if(!_e())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Hr.tested)return Hr.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Hr.tested=!0,Hr.writable=!0}catch{Hr.tested=!0,Hr.writable=!1}return Hr.writable};function Ff(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,s)=>{e[s]=n})}catch{}return r.searchParams.forEach((o,n)=>{e[n]=o}),e}var xi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),$f=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",zr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},yr=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Ce=async(t,e)=>{await t.removeItem(e)},ns=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};ns.promiseConstructor=Promise;function ss(t){let e=t.split(".");if(e.length!==3)throw new Wr("Invalid JWT structure");for(let o=0;o<e.length;o++)if(!Of.test(e[o]))throw new Wr("JWT not in base64url format");return{header:JSON.parse(ru(e[0])),payload:JSON.parse(ru(e[1])),signature:gr(e[2]),raw:{header:e[0],payload:e[1]}}}async function Bf(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function qf(t,e){return new Promise((o,n)=>{(async()=>{for(let s=0;s<1/0;s++)try{let i=await t(s);if(!e(s,null,i)){o(i);return}}catch(i){if(!e(s,i)){n(i);return}}})()})}function cw(t){return("0"+t.toString(16)).substr(-2)}function dw(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=r.length,n="";for(let s=0;s<56;s++)n+=r.charAt(Math.floor(Math.random()*o));return n}return crypto.getRandomValues(e),Array.from(e,cw).join("")}async function fw(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(o);return Array.from(n).map(s=>String.fromCharCode(s)).join("")}async function mw(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 fw(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Gr(t,e,r=!1){let o=dw(),n=o;r&&(n+="/PASSWORD_RECOVERY"),await zr(t,`${e}-code-verifier`,n);let s=await mw(o);return[s,o===s?"plain":"s256"]}var hw=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Vf(t){let e=t.headers.get(ts);if(!e||!e.match(hw))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Wf(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 Hf(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 pw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Kr(t){if(!pw.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ki(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let o=r.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="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 zf(t,e){return new Proxy(t,{get:(r,o,n)=>{if(o==="__isInsecureUserWarningProxy")return!0;if(typeof o=="symbol"){let s=o.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,o,n)}return!e.value&&typeof o=="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,o,n)}})}function ou(t){return JSON.parse(JSON.stringify(t))}var Jr=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),gw=[502,503,504];async function Gf(t){var e;if(!$f(t))throw new Mo(Jr(t),0);if(gw.includes(t.status))throw new Mo(Jr(t),t.status);let r;try{r=await t.json()}catch(s){throw new it(Jr(s),s)}let o,n=Vf(t);if(n&&n.getTime()>=tu["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?o=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(o=r.error_code),o){if(o==="weak_password")throw new os(Jr(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(o==="session_not_found")throw new Oe}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((s,i)=>s&&typeof i=="string",!0))throw new os(Jr(r),t.status,r.weak_password.reasons);throw new yi(Jr(r),t.status||500,o)}var yw=(t,e,r,o)=>{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(o),Object.assign(Object.assign({},n),r))};async function A(t,e,r,o){var n;let s=Object.assign({},o?.headers);s[ts]||(s[ts]=tu["2024-01-01"].name),o?.jwt&&(s.Authorization=`Bearer ${o.jwt}`);let i=(n=o?.query)!==null&&n!==void 0?n:{};o?.redirectTo&&(i.redirect_to=o.redirectTo);let a=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await bw(t,e,r+a,{headers:s,noResolveJson:o?.noResolveJson},{},o?.body);return o?.xform?o?.xform(l):{data:Object.assign({},l),error:null}}async function bw(t,e,r,o,n,s){let i=yw(e,o,n,s),a;try{a=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new Mo(Jr(l),0)}if(a.ok||await Gf(a),o?.noResolveJson)return a;try{return await a.json()}catch(l){await Gf(l)}}function at(t){var e;let r=null;_w(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Mf(t.expires_in)));let o=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:o},error:null}}function nu(t){let e=at(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,o)=>r&&typeof o=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Nt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Kf(t){return{data:t,error:null}}function Jf(t){let{action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s}=t,i=Be(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s},l=Object.assign({},i);return{data:{properties:a,user:l},error:null}}function su(t){return t}function _w(t){return t.access_token&&t.refresh_token&&t.expires_in}var Ti=["global","local","others"];var Yr=class{constructor({url:e="",headers:r={},fetch:o}){this.url=e,this.headers=r,this.fetch=xi(o),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)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,r=Ti[0]){if(Ti.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ti.join(", ")}`);try{return await A(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(o){if(T(o))return{data:null,error:o};throw o}}async inviteUserByEmail(e,r={}){try{return await A(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Nt})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async generateLink(e){try{let{options:r}=e,o=Be(e,["options"]),n=Object.assign(Object.assign({},o),r);return"newEmail"in o&&(n.new_email=o?.newEmail,delete n.newEmail),await A(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Jf,redirectTo:r?.redirectTo})}catch(r){if(T(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await A(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Nt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await A(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:su});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(T(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Kr(e);try{return await A(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Nt})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Kr(e);try{return await A(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Nt})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async deleteUser(e,r=!1){Kr(e);try{return await A(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Nt})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async _listFactors(e){Kr(e.userId);try{let{data:r,error:o}=await A(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:o}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Kr(e.userId),Kr(e.id);try{return{data:await A(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await A(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:su});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(T(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await A(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await A(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await A(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(T(o))return{data:null,error:o};throw o}}async _deleteOAuthClient(e){try{return await A(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await A(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await A(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:o=>{var n;return{data:{providers:(n=o?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(T(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await A(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await A(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await A(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(T(o))return{data:null,error:o};throw o}}async _deleteCustomProvider(e){try{return await A(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}};function iu(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var vt={debug:!!(globalThis&&Si()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},is=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},as=class extends is{};async function au(t,e,r){vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let o=new globalThis.AbortController,n;e>0&&(n=setTimeout(()=>{o.abort(),vt.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:o.signal},async s=>{if(s){clearTimeout(n),vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new as(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(vt.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"),clearTimeout(n),await r()}})}catch(s){if(e>0&&clearTimeout(n),s?.name==="AbortError"&&e>0){if(o.signal.aborted)return vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async i=>{if(i){vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw vt.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new as(`Lock "${t}" was released because another request stole it`)}throw s}}function Yf(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function lu(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Xf(t){return parseInt(t,16)}function Qf(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}function Zf(t){var e;let{chainId:r,domain:o,expirationTime:n,issuedAt:s=new Date,nonce:i,notBefore:a,requestId:l,resources:u,scheme:c,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(!o)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);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(`
|
|
72
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let m=lu(t.address),h=c?`${c}://${o}`:o,g=t.statement?`${t.statement}
|
|
73
73
|
`:"",y=`${h} wants you to sign in with your Ethereum account:
|
|
74
74
|
${m}
|
|
75
75
|
|
|
@@ -83,13 +83,13 @@ Not Before: ${a.toISOString()}`),l&&(p+=`
|
|
|
83
83
|
Request ID: ${l}`),u){let b=`
|
|
84
84
|
Resources:`;for(let _ of u){if(!_||typeof _!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${_}`);b+=`
|
|
85
85
|
- ${_}`}p+=b}return`${y}
|
|
86
|
-
${p}`}var ie=class extends Error{constructor({message:e,code:r,cause:o,name:n}){var s;super(e,{cause:o}),this.__isWebAuthnError=!0,this.name=(s=n??(o instanceof Error?o.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},Xr=class extends ie{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function Qf({error:t,options:e}){var r,o,n;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ie({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new ie({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((o=s.authenticatorSelection)===null||o===void 0?void 0:o.userVerification)==="required")return new ie({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=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ie({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 ie({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new ie({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new ie({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new ie({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 i=window.location.hostname;if(au(i)){if(s.rp.id!==i)return new ie({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ie({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new ie({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 ie({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 ie({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Zf({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 ie({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new ie({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(au(o)){if(r.rpId!==o)return new ie({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ie({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new ie({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 ie({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var lu=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}}},ww=new lu;function tm(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:o}=t,n=Be(t,["challenge","user","excludeCredentials"]),s=gr(e).buffer,i=Object.assign(Object.assign({},r),{id:gr(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:s,user:i});if(o&&o.length>0){a.excludeCredentials=new Array(o.length);for(let l=0;l<o.length;l++){let u=o[l];a.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:gr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function rm(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,o=Be(t,["challenge","allowCredentials"]),n=gr(e).buffer,s=Object.assign(Object.assign({},o),{challenge:n});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){let a=r[i];s.allowCredentials[i]=Object.assign(Object.assign({},a),{id:gr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function om(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:Xt(new Uint8Array(t.response.attestationObject)),clientDataJSON:Xt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function nm(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,o=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Xt(new Uint8Array(n.authenticatorData)),clientDataJSON:Xt(new Uint8Array(n.clientDataJSON)),signature:Xt(new Uint8Array(n.signature)),userHandle:n.userHandle?Xt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:o,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function au(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function em(){var t,e;return!!(_e()&&"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 vw(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Xr("Browser returned unexpected credential type",e)}:{data:null,error:new Xr("Empty credential response",e)}}catch(e){return{data:null,error:Qf({error:e,options:t})}}}async function Sw(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Xr("Browser returned unexpected credential type",e)}:{data:null,error:new Xr("Empty credential response",e)}}catch(e){return{data:null,error:Zf({error:e,options:t})}}}var xw={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},kw={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ci(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),o={};for(let n of t)if(n)for(let s in n){let i=n[s];if(i!==void 0)if(Array.isArray(i))o[s]=i;else if(r(i))o[s]=i;else if(e(i)){let a=o[s];e(a)?o[s]=Ci(a,i):o[s]=Ci(i)}else o[s]=i}return o}function Tw(t,e){return Ci(xw,t,e||{})}function Cw(t,e){return Ci(kw,t,e||{})}var Ei=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:o,signal:n},s){var i;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let u=n??ww.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){let d=o;if(d)c.name=`${c.id}:${d}`;else{let m=(await this.client.getUser()).data.user,h=((i=m?.user_metadata)===null||i===void 0?void 0:i.name)||m?.email||m?.id||"User";c.name=`${c.id}:${h}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{let c=Tw(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:f}=await vw({publicKey:c,signal:u});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 c=Cw(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:f}=await Sw(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));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 T(a)?{data:null,error:a}:{data:null,error:new it("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:o}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:o})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new pr("rpId is required for WebAuthn authentication")};try{if(!em())return{data:null,error:new it("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:o},signal:n},{request:s});if(!i)return{data:null,error:a};let{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:o,credential_response:l.credential_response}})}catch(i){return T(i)?{data:null,error:i}:{data:null,error:new it("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new pr("rpId is required for WebAuthn registration")};try{if(!em())return{data:null,error:new it("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(c=>{var d;return(d=c.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};let{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:o},signal:n},{create:s});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:o,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return T(i)?{data:null,error:i}:{data:null,error:new it("Unexpected error in register",i)}}}};Kf();var Ew={url:kf,storageKey:Tf,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Cf,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function sm(t,e,r){return await r()}var Uo={},Pi=class t{get jwks(){var e,r;return(r=(e=Uo[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Uo[this.storageKey]=Object.assign(Object.assign({},Uo[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Uo[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Uo[this.storageKey]=Object.assign(Object.assign({},Uo[this.storageKey]),{cachedAt:e})}constructor(e){var r,o,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 s=Object.assign(Object.assign({},Ew),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&_e()){let i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Yr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=xi(s.fetch),this.lock=s.lock||sm,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&_e()&&(!((o=globalThis?.navigator)===null||o===void 0)&&o.locks)?this.lock=su:this.lock=sm,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 Ei(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?(s.storage?this.storage=s.storage:Si()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=nu(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=nu(this.memoryStorage)),_e()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${hi}) ${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={},o="none";if(_e()&&(r=Mf(window.location.href),this._isImplicitGrantCallback(r)?o="implicit":await this._isPKCECallback(r)&&(o="pkce")),_e()&&this.detectSessionInUrl&&o!=="none"){let{data:n,error:s}=await this._getSessionFromURL(r,o);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),Af(s)){let l=(e=s.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:s}}return{error:s}}let{session:i,redirectType:a}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return T(r)?this._returnResult({error:r}):this._returnResult({error:new it("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,o,n;try{let s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(o=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&o!==void 0?o:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:at}),{data:i,error:a}=s;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,o,n;try{let s;if("email"in e){let{email:c,password:d,options:f}=e,m=null,h=null;this.flowType==="pkce"&&([m,h]=await Gr(this.storage,this.storageKey)),s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:h},xform:at})}else if("phone"in e){let{phone:c,password:d,options:f}=e;s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(o=f?.data)!==null&&o!==void 0?o:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:at})}else throw new qr("You must provide either an email or phone number and a password");let{data:i,error:a}=s;if(a||!i)return await Ce(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:i,options:a}=e;r=await A(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ru})}else if("phone"in e){let{phone:s,password:i,options:a}=e;r=await A(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:ru})}else throw new qr("You must provide either an email or phone number and a password");let{data:o,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!o||!o.session||!o.user){let s=new Yt;return this._returnResult({data:{user:null,session:null},error:s})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign({user:o.user,session:o.session},o.weak_password?{weakPassword:o.weak_password}:null),error:n})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,o,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.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,o,n,s,i,a,l,u,c,d,f;let m,h;if("message"in e)m=e.message,h=e.signature;else{let{chain:g,wallet:y,statement:p,options:b}=e,_;if(_e())if(typeof y=="object")_=y;else{let F=window;if("ethereum"in F&&typeof F.ethereum=="object"&&"request"in F.ethereum&&typeof F.ethereum.request=="function")_=F.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=y}let v=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),L=await _.request({method:"eth_requestAccounts"}).then(F=>F).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!L||L.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let x=iu(L[0]),P=(o=b?.signInWithEthereum)===null||o===void 0?void 0:o.chainId;if(!P){let F=await _.request({method:"eth_chainId"});P=Jf(F)}let X={domain:v.host,address:x,statement:p,uri:v.href,version:"1",chainId:P,nonce:(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=Xf(X),h=await _.request({method:"personal_sign",params:[Yf(m),x]})}try{let{data:g,error:y}=await A(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:h},!((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:at});if(y)throw y;if(!g||!g.session||!g.user){let p=new Yt;return this._returnResult({data:{user:null,session:null},error:p})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(T(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,o,n,s,i,a,l,u,c,d,f,m;let h,g;if("message"in e)h=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:b,options:_}=e,v;if(_e())if(typeof p=="object")v=p;else{let x=window;if("solana"in x&&typeof x.solana=="object"&&("signIn"in x.solana&&typeof x.solana.signIn=="function"||"signMessage"in x.solana&&typeof x.solana.signMessage=="function"))v=x.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 p!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=p}let L=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in v&&v.signIn){let x=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:L.host,uri:L.href}),b?{statement:b}:null)),P;if(Array.isArray(x)&&x[0]&&typeof x[0]=="object")P=x[0];else if(x&&typeof x=="object"&&"signedMessage"in x&&"signature"in x)P=x;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)h=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),g=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in v)||typeof v.signMessage!="function"||!("publicKey"in v)||typeof v!="object"||!v.publicKey||!("toBase58"in v.publicKey)||typeof v.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");h=[`${L.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${L.href}`,`Issued At: ${(n=(o=_?.signInWithSolana)===null||o===void 0?void 0:o.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((s=_?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((d=(c=_?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
87
|
-
`);let x=await v.signMessage(new TextEncoder().encode(h),"utf8");if(!x||!(x instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=x}}try{let{data:y,error:p}=await A(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:Xt(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:at});if(p)throw p;if(!y||!y.session||!y.user){let b=new Yt;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:p})}catch(y){if(T(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){let r=await yr(this.storage,`${this.storageKey}-code-verifier`),[o,n]=(r??"").split("/");try{if(!o&&this.flowType==="pkce")throw new bi;let{data:s,error:i}=await A(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:at});if(await Ce(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let a=new Yt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:n??null}),error:i})}catch(s){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:o,token:n,access_token:s,nonce:i}=e,a=await A(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:o,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:at}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new Yt;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,o,n,s,i;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await Gr(this.storage,this.storageKey));let{error:d}=await A(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(o=l?.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await A(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new qr("You must provide either an email or phone number.")}catch(a){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,o;try{let n,s;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(o=e.options)===null||o===void 0?void 0:o.captchaToken);let{data:i,error:a}=await A(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:at});if(a)throw a;if(!i)throw new Error("An error occurred on token verification.");let l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,o,n,s,i;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await Gr(this.storage,this.storageKey));let u=await A(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:(o=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&o!==void 0?o: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:zf});return!((s=u.data)===null||s===void 0)&&s.url&&_e()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(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:o}=e;if(o)throw o;if(!r)throw new Oe;let{error:n}=await A(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(T(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:o,type:n,options:s}=e,{error:i}=await A(this.fetch,"POST",r,{headers:this.headers,body:{email:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){let{phone:o,type:n,options:s}=e,{data:i,error:a}=await A(this.fetch,"POST",r,{headers:this.headers,body:{phone:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:a})}throw new qr("You must provide either an email or phone number and a type")}catch(r){if(T(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 o=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await o,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 o=r();for(this.pendingInLock.push((async()=>{try{await o}catch{}})()),await o;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await o}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 yr(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 o=e.expires_at?e.expires_at*1e3-Date.now()<gi:!1;if(this._debug("#__loadSession()",`session has${o?"":" not"} expired`,"expires_at",e.expires_at),!o){if(this.userStorage){let i=await yr(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=ki()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let i={value:this.suppressGetSessionWarning};e.user=Wf(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):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 A(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Nt}):await this._useSession(async r=>{var o,n,s;let{data:i,error:a}=r;if(a)throw a;return!(!((o=i.session)===null||o===void 0)&&o.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Oe}:await A(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0,xform:Nt})})}catch(r){if(T(r))return _i(r)&&(await this._removeSession(),await Ce(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 o=>{let{data:n,error:s}=o;if(s)throw s;if(!n.session)throw new Oe;let i=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Gr(this.storage,this.storageKey));let{data:u,error:c}=await A(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:i.access_token,xform:Nt});if(c)throw c;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(o){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(o))return this._returnResult({data:{user:null},error:o});throw o}}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 Oe;let r=Date.now()/1e3,o=r,n=!0,s=null,{payload:i}=ss(e.access_token);if(i.exp&&(o=i.exp,n=o<=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};s=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});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:o-r,expires_at:o},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(T(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 o;if(!e){let{data:i,error:a}=r;if(a)throw a;e=(o=i.session)!==null&&o!==void 0?o:void 0}if(!e?.refresh_token)throw new Oe;let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!_e())throw new Vr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Vr(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 rs("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Vr("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 rs("No code detected.");let{data:b,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;let v=new URL(window.location.href);return v.searchParams.delete("code"),window.history.replaceState(window.history.state,"",v.toString()),{data:{session:b.session,redirectType:null},error:null}}let{provider_token:o,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:a,expires_at:l,token_type:u}=e;if(!s||!a||!i||!u)throw new Vr("No session defined in URL");let c=Math.round(Date.now()/1e3),d=parseInt(a),f=c+d;l&&(f=parseInt(l));let m=f-c;m*1e3<=Br&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);let h=f-d;c-h>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,f,c):c-h<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,f,c);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:o,provider_refresh_token:n,access_token:s,expires_in:d,expires_at:f,refresh_token:i,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(o){if(T(o))return this._returnResult({data:{session:null,redirectType:null},error:o});throw o}}_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 yr(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 o;let{data:n,error:s}=r;if(s&&!_i(s))return this._returnResult({error:s});let i=(o=n.session)===null||o===void 0?void 0:o.access_token;if(i){let{error:a}=await this.admin.signOut(i,e);if(a&&!(Of(a)&&(a.status===404||a.status===401||a.status===403)||_i(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await Ce(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=jf(),o={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,o),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:o}}}async _emitInitialSession(e){return await this._useSession(async r=>{var o,n;try{let{data:{session:s},error:i}=r;if(i)throw i;await((o=this.stateChangeEmitters.get(e))===null||o===void 0?void 0:o.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){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",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let o=null,n=null;this.flowType==="pkce"&&([o,n]=await Gr(this.storage,this.storageKey,!0));try{return await A(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:o,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:o}=await this.getUser();if(o)throw o;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(T(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:o,error:n}=await this._useSession(async s=>{var i,a,l,u,c;let{data:d,error:f}=s;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.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 A(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;return _e()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(o?.url),this._returnResult({data:{provider:e.provider,url:o?.url},error:null})}catch(o){if(T(o))return this._returnResult({data:{provider:e.provider,url:null},error:o});throw o}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var o;try{let{error:n,data:{session:s}}=r;if(n)throw n;let{options:i,provider:a,token:l,access_token:u,nonce:c}=e,d=await A(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(o=s?.access_token)!==null&&o!==void 0?o:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:at}),{data:f,error:m}=d;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new Yt}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(n){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)throw i;return await A(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(o=s.session)===null||o===void 0?void 0:o.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(T(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 o=Date.now();return await $f(async n=>(n>0&&await Ff(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await A(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:at})),(n,s)=>{let i=200*Math.pow(2,n);return s&&wi(s)&&Date.now()+i-o<Br})}catch(o){if(this._debug(r,"error",o),T(o))return this._returnResult({data:{session:null,user:null},error:o});throw o}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 o=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",o),_e()&&!r.skipBrowserRedirect&&window.location.assign(o),{data:{provider:e,url:o},error:null}}async _recoverAndRefresh(){var e,r;let o="#_recoverAndRefresh()";this._debug(o,"begin");try{let n=await yr(this.storage,this.storageKey);if(n&&this.userStorage){let i=await yr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await zr(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:ki()}else if(n&&!n.user&&!n.user){let i=await yr(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await Ce(this.storage,this.storageKey+"-user"),await zr(this.storage,this.storageKey,n)):n.user=ki()}if(this._debug(o,"session from storage",n),!this._isValidSession(n)){this._debug(o,"session is not valid"),n!==null&&await this._removeSession();return}let s=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<gi;if(this._debug(o,`session has${s?"":" not"} expired with margin of ${gi}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),wi(i)||(this._debug(o,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:a}=await this._getUser(n.access_token);!a&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(o,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(o,"error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(o,"error",n),console.error(n);return}finally{this._debug(o,"end")}}async _callRefreshToken(e){var r,o;if(!e)throw new Oe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new ns;let{data:s,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!s.session)throw new Oe;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(n,"error",s),T(s)){let i={data:null,error:s};return wi(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(o=this.refreshingDeferred)===null||o===void 0||o.reject(s),s}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,o=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${o}`);try{this.broadcastChannel&&o&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){s.push(l)}});if(await Promise.all(i),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ce(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),o=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!o&&r.user&&await zr(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let s=tu(n);await zr(this.storage,this.storageKey,s)}else{let n=tu(r);await zr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Ce(this.storage,this.storageKey),await Ce(this.storage,this.storageKey+"-code-verifier"),await Ce(this.storage,this.storageKey+"-user"),this.userStorage&&await Ce(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&_e()&&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(),Br);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:o}}=r;if(!o||!o.refresh_token||!o.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((o.expires_at*1e3-e)/Br);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Br}ms, refresh threshold is ${pi} ticks`),n<=pi&&await this._callRefreshToken(o.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 is)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!_e()||!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,o){let n=[`provider=${encodeURIComponent(r)}`];if(o?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(o.redirectTo)}`),o?.scopes&&n.push(`scopes=${encodeURIComponent(o.scopes)}`),this.flowType==="pkce"){let[s,i]=await Gr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(a.toString())}if(o?.queryParams){let s=new URLSearchParams(o.queryParams);n.push(s.toString())}return o?.skipBrowserRedirect&&n.push(`skip_http_redirect=${o.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;return s?this._returnResult({data:null,error:s}):await A(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});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:u}=await A(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(o=s?.session)===null||o===void 0?void 0:o.access_token});return u?this._returnResult({data:null,error:u}):(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(T(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 o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?om(e.webauthn.credential_response):nm(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await A(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.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(T(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 o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=await A(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token});if(i.error)return i;let{data:a}=i;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:tm(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:rm(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:o}=await this._challenge({factorId:e.factorId});return o?this._returnResult({data:null,error:o}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:o}=await this.getUser();if(o)return{data:null,error:o};let n={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(s),s.status==="verified"&&n[s.factor_type].push(s);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,o,n,s;if(e)try{let{payload:m}=ss(e),h=null;m.aal&&(h=m.aal);let g=h,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((o=(r=y?.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(g="aal2");let _=m.amr||[];return{data:{currentLevel:h,nextLevel:g,currentAuthenticationMethods:_},error:null}}catch(m){if(T(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:i},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=ss(i.access_token),u=null;l.aal&&(u=l.aal);let c=u;((s=(n=i.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let f=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?await A(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:o.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Oe})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Oe});let i=await A(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 i.data&&i.data.redirect_url&&_e()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}async _denyAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Oe});let i=await A(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 i.data&&i.data.redirect_url&&_e()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:o}=e;return o?this._returnResult({data:null,error:o}):r?await A(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 Oe})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?(await A(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:o.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Oe})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let o=r.keys.find(a=>a.kid===e);if(o)return o;let n=Date.now();if(o=this.jwks.keys.find(a=>a.kid===e),o&&this.jwks_cached_at+Pf>n)return o;let{data:s,error:i}=await A(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=n,o=s.keys.find(a=>a.kid===e),!o)?null:o}async getClaims(e,r={}){try{let o=e;if(!o){let{data:m,error:h}=await this.getSession();if(h||!m.session)return this._returnResult({data:null,error:h});o=m.session.access_token}let{header:n,payload:s,signature:i,raw:{header:a,payload:l}}=ss(o);r?.allowExpired||qf(s.exp);let u=!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(!u){let{error:m}=await this.getUser(o);if(m)throw m;return{data:{claims:s,header:n,signature:i},error:null}}let c=Vf(n.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,i,Lf(`${a}.${l}`)))throw new Wr("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}};Pi.nextInstanceID={};var uu=Pi;var Pw=uu,cu=Pw;var Ow="2.100.1",ls="";typeof Deno<"u"?ls="deno":typeof document<"u"?ls="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ls="react-native":ls="node";var Aw={"X-Client-Info":`supabase-js-${ls}/${Ow}`},Rw={headers:Aw},Iw={schema:"public"},Dw={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Lw={};function us(t){"@babel/helpers - typeof";return us=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},us(t)}function Nw(t,e){if(us(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(us(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function jw(t){var e=Nw(t,"string");return us(e)=="symbol"?e:e+""}function Mw(t,e,r){return(e=jw(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function im(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function ue(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?im(Object(r),!0).forEach(function(o){Mw(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):im(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var Uw=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Fw=()=>Headers,$w=(t,e,r)=>{let o=Uw(r),n=Fw();return async(s,i)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),o(s,ue(ue({},i),{},{headers:u}))}};function Bw(t){return t.endsWith("/")?t:t+"/"}function qw(t,e){var r,o;let{db:n,auth:s,realtime:i,global:a}=t,{db:l,auth:u,realtime:c,global:d}=e,f={db:ue(ue({},l),n),auth:ue(ue({},u),s),realtime:ue(ue({},c),i),storage:{},global:ue(ue(ue({},d),a),{},{headers:ue(ue({},(r=d?.headers)!==null&&r!==void 0?r:{}),(o=a?.headers)!==null&&o!==void 0?o:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function Vw(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(Bw(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Ww=class extends cu{constructor(t){super(t)}},Hw=class{constructor(t,e,r){var o,n;this.supabaseUrl=t,this.supabaseKey=e;let s=Vw(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:Iw,realtime:Lw,auth:ue(ue({},Dw),{},{storageKey:i}),global:Rw},l=qw(r??{},a);if(this.storageKey=(o=l.auth.storageKey)!==null&&o!==void 0?o:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,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 u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=$w(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(ue({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new af(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new xf(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Wn(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:o}=await t.auth.getSession();return(e=(r=o.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:o,userStorage:n,storageKey:s,flowType:i,lock:a,debug:l,throwOnError:u},c,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ww({url:this.authUrl.href,headers:ue(ue({},f),c),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,flowType:i,lock:a,debug:l,throwOnError:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new No(this.realtimeUrl.href,ue(ue({},t),{},{params:ue(ue({},{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)}},am=(t,e,r)=>new Hw(t,e,r);function zw(){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}zw()&&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 du="0.5.2";var cm=yn(mu());function Qr(){return typeof window<"u"&&typeof window.document<"u"}var br={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4};var nv=/^(.*)[.](0|[1-9][0-9]*)$/;function cs(t,e){if(t===e)return!0;let r=t.match(nv);return!!(r&&r[1]===e)}function hu(t,e,r){let o=r??3180,n=encodeURIComponent(e);if(n.length<=o)return[{name:t,value:e}];let s=[];for(;n.length>0;){let i=n.slice(0,o),a=i.lastIndexOf("%");a>o-3&&(i=i.slice(0,a));let l="";for(;i.length>0;)try{l=decodeURIComponent(i);break}catch(u){if(u instanceof URIError&&i.at(-3)==="%"&&i.length>3)i=i.slice(0,i.length-3);else throw u}s.push(l),n=n.slice(i.length)}return s.map((i,a)=>({name:`${t}.${a}`,value:i}))}async function pu(t,e){let r=await e(t);if(r)return r;let o=[];for(let n=0;;n++){let s=`${t}.${n}`,i=await e(s);if(!i)break;o.push(i)}return o.length>0?o.join(""):null}var Oi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),dm=`
|
|
88
|
-
\r=`.split(""),sv=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<
|
|
86
|
+
${p}`}var ie=class extends Error{constructor({message:e,code:r,cause:o,name:n}){var s;super(e,{cause:o}),this.__isWebAuthnError=!0,this.name=(s=n??(o instanceof Error?o.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},Xr=class extends ie{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function em({error:t,options:e}){var r,o,n;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ie({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new ie({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((o=s.authenticatorSelection)===null||o===void 0?void 0:o.userVerification)==="required")return new ie({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=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ie({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 ie({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new ie({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new ie({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new ie({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 i=window.location.hostname;if(uu(i)){if(s.rp.id!==i)return new ie({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ie({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new ie({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 ie({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 ie({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function tm({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 ie({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new ie({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(uu(o)){if(r.rpId!==o)return new ie({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ie({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new ie({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 ie({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var cu=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}}},ww=new cu;function om(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:o}=t,n=Be(t,["challenge","user","excludeCredentials"]),s=gr(e).buffer,i=Object.assign(Object.assign({},r),{id:gr(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:s,user:i});if(o&&o.length>0){a.excludeCredentials=new Array(o.length);for(let l=0;l<o.length;l++){let u=o[l];a.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:gr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function nm(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,o=Be(t,["challenge","allowCredentials"]),n=gr(e).buffer,s=Object.assign(Object.assign({},o),{challenge:n});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){let a=r[i];s.allowCredentials[i]=Object.assign(Object.assign({},a),{id:gr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function sm(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:Xt(new Uint8Array(t.response.attestationObject)),clientDataJSON:Xt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function im(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,o=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Xt(new Uint8Array(n.authenticatorData)),clientDataJSON:Xt(new Uint8Array(n.clientDataJSON)),signature:Xt(new Uint8Array(n.signature)),userHandle:n.userHandle?Xt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:o,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function uu(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function rm(){var t,e;return!!(_e()&&"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 vw(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Xr("Browser returned unexpected credential type",e)}:{data:null,error:new Xr("Empty credential response",e)}}catch(e){return{data:null,error:em({error:e,options:t})}}}async function Sw(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Xr("Browser returned unexpected credential type",e)}:{data:null,error:new Xr("Empty credential response",e)}}catch(e){return{data:null,error:tm({error:e,options:t})}}}var xw={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},kw={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ci(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),o={};for(let n of t)if(n)for(let s in n){let i=n[s];if(i!==void 0)if(Array.isArray(i))o[s]=i;else if(r(i))o[s]=i;else if(e(i)){let a=o[s];e(a)?o[s]=Ci(a,i):o[s]=Ci(i)}else o[s]=i}return o}function Tw(t,e){return Ci(xw,t,e||{})}function Cw(t,e){return Ci(kw,t,e||{})}var Ei=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:o,signal:n},s){var i;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let u=n??ww.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){let d=o;if(d)c.name=`${c.id}:${d}`;else{let m=(await this.client.getUser()).data.user,h=((i=m?.user_metadata)===null||i===void 0?void 0:i.name)||m?.email||m?.id||"User";c.name=`${c.id}:${h}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{let c=Tw(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:f}=await vw({publicKey:c,signal:u});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 c=Cw(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:f}=await Sw(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));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 T(a)?{data:null,error:a}:{data:null,error:new it("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:o}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:o})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new pr("rpId is required for WebAuthn authentication")};try{if(!rm())return{data:null,error:new it("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:o},signal:n},{request:s});if(!i)return{data:null,error:a};let{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:o,credential_response:l.credential_response}})}catch(i){return T(i)?{data:null,error:i}:{data:null,error:new it("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new pr("rpId is required for WebAuthn registration")};try{if(!rm())return{data:null,error:new it("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(c=>{var d;return(d=c.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};let{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:o},signal:n},{create:s});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:o,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return T(i)?{data:null,error:i}:{data:null,error:new it("Unexpected error in register",i)}}}};Yf();var Ew={url:Cf,storageKey:Ef,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Pf,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function am(t,e,r){return await r()}var Uo={},Pi=class t{get jwks(){var e,r;return(r=(e=Uo[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Uo[this.storageKey]=Object.assign(Object.assign({},Uo[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Uo[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Uo[this.storageKey]=Object.assign(Object.assign({},Uo[this.storageKey]),{cachedAt:e})}constructor(e){var r,o,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 s=Object.assign(Object.assign({},Ew),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&_e()){let i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Yr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=xi(s.fetch),this.lock=s.lock||am,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&_e()&&(!((o=globalThis?.navigator)===null||o===void 0)&&o.locks)?this.lock=au:this.lock=am,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 Ei(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?(s.storage?this.storage=s.storage:Si()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=iu(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=iu(this.memoryStorage)),_e()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${hi}) ${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={},o="none";if(_e()&&(r=Ff(window.location.href),this._isImplicitGrantCallback(r)?o="implicit":await this._isPKCECallback(r)&&(o="pkce")),_e()&&this.detectSessionInUrl&&o!=="none"){let{data:n,error:s}=await this._getSessionFromURL(r,o);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),If(s)){let l=(e=s.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:s}}return{error:s}}let{session:i,redirectType:a}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return T(r)?this._returnResult({error:r}):this._returnResult({error:new it("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,o,n;try{let s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(o=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&o!==void 0?o:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:at}),{data:i,error:a}=s;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,o,n;try{let s;if("email"in e){let{email:c,password:d,options:f}=e,m=null,h=null;this.flowType==="pkce"&&([m,h]=await Gr(this.storage,this.storageKey)),s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:h},xform:at})}else if("phone"in e){let{phone:c,password:d,options:f}=e;s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(o=f?.data)!==null&&o!==void 0?o:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:at})}else throw new qr("You must provide either an email or phone number and a password");let{data:i,error:a}=s;if(a||!i)return await Ce(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:i,options:a}=e;r=await A(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:nu})}else if("phone"in e){let{phone:s,password:i,options:a}=e;r=await A(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:nu})}else throw new qr("You must provide either an email or phone number and a password");let{data:o,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!o||!o.session||!o.user){let s=new Yt;return this._returnResult({data:{user:null,session:null},error:s})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign({user:o.user,session:o.session},o.weak_password?{weakPassword:o.weak_password}:null),error:n})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,o,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.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,o,n,s,i,a,l,u,c,d,f;let m,h;if("message"in e)m=e.message,h=e.signature;else{let{chain:g,wallet:y,statement:p,options:b}=e,_;if(_e())if(typeof y=="object")_=y;else{let F=window;if("ethereum"in F&&typeof F.ethereum=="object"&&"request"in F.ethereum&&typeof F.ethereum.request=="function")_=F.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=y}let v=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),L=await _.request({method:"eth_requestAccounts"}).then(F=>F).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!L||L.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let x=lu(L[0]),P=(o=b?.signInWithEthereum)===null||o===void 0?void 0:o.chainId;if(!P){let F=await _.request({method:"eth_chainId"});P=Xf(F)}let X={domain:v.host,address:x,statement:p,uri:v.href,version:"1",chainId:P,nonce:(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=Zf(X),h=await _.request({method:"personal_sign",params:[Qf(m),x]})}try{let{data:g,error:y}=await A(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:h},!((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:at});if(y)throw y;if(!g||!g.session||!g.user){let p=new Yt;return this._returnResult({data:{user:null,session:null},error:p})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(T(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,o,n,s,i,a,l,u,c,d,f,m;let h,g;if("message"in e)h=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:b,options:_}=e,v;if(_e())if(typeof p=="object")v=p;else{let x=window;if("solana"in x&&typeof x.solana=="object"&&("signIn"in x.solana&&typeof x.solana.signIn=="function"||"signMessage"in x.solana&&typeof x.solana.signMessage=="function"))v=x.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 p!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=p}let L=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in v&&v.signIn){let x=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:L.host,uri:L.href}),b?{statement:b}:null)),P;if(Array.isArray(x)&&x[0]&&typeof x[0]=="object")P=x[0];else if(x&&typeof x=="object"&&"signedMessage"in x&&"signature"in x)P=x;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)h=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),g=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in v)||typeof v.signMessage!="function"||!("publicKey"in v)||typeof v!="object"||!v.publicKey||!("toBase58"in v.publicKey)||typeof v.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");h=[`${L.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${L.href}`,`Issued At: ${(n=(o=_?.signInWithSolana)===null||o===void 0?void 0:o.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((s=_?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((d=(c=_?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
87
|
+
`);let x=await v.signMessage(new TextEncoder().encode(h),"utf8");if(!x||!(x instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=x}}try{let{data:y,error:p}=await A(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:Xt(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:at});if(p)throw p;if(!y||!y.session||!y.user){let b=new Yt;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:p})}catch(y){if(T(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){let r=await yr(this.storage,`${this.storageKey}-code-verifier`),[o,n]=(r??"").split("/");try{if(!o&&this.flowType==="pkce")throw new bi;let{data:s,error:i}=await A(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:at});if(await Ce(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let a=new Yt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:n??null}),error:i})}catch(s){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:o,token:n,access_token:s,nonce:i}=e,a=await A(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:o,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:at}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new Yt;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,o,n,s,i;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await Gr(this.storage,this.storageKey));let{error:d}=await A(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(o=l?.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await A(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new qr("You must provide either an email or phone number.")}catch(a){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,o;try{let n,s;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(o=e.options)===null||o===void 0?void 0:o.captchaToken);let{data:i,error:a}=await A(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:at});if(a)throw a;if(!i)throw new Error("An error occurred on token verification.");let l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,o,n,s,i;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await Gr(this.storage,this.storageKey));let u=await A(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:(o=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&o!==void 0?o: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:Kf});return!((s=u.data)===null||s===void 0)&&s.url&&_e()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(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:o}=e;if(o)throw o;if(!r)throw new Oe;let{error:n}=await A(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(T(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:o,type:n,options:s}=e,{error:i}=await A(this.fetch,"POST",r,{headers:this.headers,body:{email:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){let{phone:o,type:n,options:s}=e,{data:i,error:a}=await A(this.fetch,"POST",r,{headers:this.headers,body:{phone:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:a})}throw new qr("You must provide either an email or phone number and a type")}catch(r){if(T(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 o=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await o,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 o=r();for(this.pendingInLock.push((async()=>{try{await o}catch{}})()),await o;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await o}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 yr(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 o=e.expires_at?e.expires_at*1e3-Date.now()<gi:!1;if(this._debug("#__loadSession()",`session has${o?"":" not"} expired`,"expires_at",e.expires_at),!o){if(this.userStorage){let i=await yr(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=ki()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let i={value:this.suppressGetSessionWarning};e.user=zf(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):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 A(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Nt}):await this._useSession(async r=>{var o,n,s;let{data:i,error:a}=r;if(a)throw a;return!(!((o=i.session)===null||o===void 0)&&o.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Oe}:await A(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0,xform:Nt})})}catch(r){if(T(r))return _i(r)&&(await this._removeSession(),await Ce(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 o=>{let{data:n,error:s}=o;if(s)throw s;if(!n.session)throw new Oe;let i=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Gr(this.storage,this.storageKey));let{data:u,error:c}=await A(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:i.access_token,xform:Nt});if(c)throw c;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(o){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(o))return this._returnResult({data:{user:null},error:o});throw o}}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 Oe;let r=Date.now()/1e3,o=r,n=!0,s=null,{payload:i}=ss(e.access_token);if(i.exp&&(o=i.exp,n=o<=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};s=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});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:o-r,expires_at:o},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(T(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 o;if(!e){let{data:i,error:a}=r;if(a)throw a;e=(o=i.session)!==null&&o!==void 0?o:void 0}if(!e?.refresh_token)throw new Oe;let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!_e())throw new Vr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Vr(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 rs("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Vr("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 rs("No code detected.");let{data:b,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;let v=new URL(window.location.href);return v.searchParams.delete("code"),window.history.replaceState(window.history.state,"",v.toString()),{data:{session:b.session,redirectType:null},error:null}}let{provider_token:o,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:a,expires_at:l,token_type:u}=e;if(!s||!a||!i||!u)throw new Vr("No session defined in URL");let c=Math.round(Date.now()/1e3),d=parseInt(a),f=c+d;l&&(f=parseInt(l));let m=f-c;m*1e3<=Br&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);let h=f-d;c-h>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,f,c):c-h<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,f,c);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:o,provider_refresh_token:n,access_token:s,expires_in:d,expires_at:f,refresh_token:i,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(o){if(T(o))return this._returnResult({data:{session:null,redirectType:null},error:o});throw o}}_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 yr(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 o;let{data:n,error:s}=r;if(s&&!_i(s))return this._returnResult({error:s});let i=(o=n.session)===null||o===void 0?void 0:o.access_token;if(i){let{error:a}=await this.admin.signOut(i,e);if(a&&!(Rf(a)&&(a.status===404||a.status===401||a.status===403)||_i(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await Ce(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Uf(),o={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,o),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:o}}}async _emitInitialSession(e){return await this._useSession(async r=>{var o,n;try{let{data:{session:s},error:i}=r;if(i)throw i;await((o=this.stateChangeEmitters.get(e))===null||o===void 0?void 0:o.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){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",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let o=null,n=null;this.flowType==="pkce"&&([o,n]=await Gr(this.storage,this.storageKey,!0));try{return await A(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:o,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:o}=await this.getUser();if(o)throw o;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(T(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:o,error:n}=await this._useSession(async s=>{var i,a,l,u,c;let{data:d,error:f}=s;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.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 A(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;return _e()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(o?.url),this._returnResult({data:{provider:e.provider,url:o?.url},error:null})}catch(o){if(T(o))return this._returnResult({data:{provider:e.provider,url:null},error:o});throw o}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var o;try{let{error:n,data:{session:s}}=r;if(n)throw n;let{options:i,provider:a,token:l,access_token:u,nonce:c}=e,d=await A(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(o=s?.access_token)!==null&&o!==void 0?o:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:at}),{data:f,error:m}=d;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new Yt}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(n){if(await Ce(this.storage,`${this.storageKey}-code-verifier`),T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)throw i;return await A(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(o=s.session)===null||o===void 0?void 0:o.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(T(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 o=Date.now();return await qf(async n=>(n>0&&await Bf(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await A(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:at})),(n,s)=>{let i=200*Math.pow(2,n);return s&&wi(s)&&Date.now()+i-o<Br})}catch(o){if(this._debug(r,"error",o),T(o))return this._returnResult({data:{session:null,user:null},error:o});throw o}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 o=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",o),_e()&&!r.skipBrowserRedirect&&window.location.assign(o),{data:{provider:e,url:o},error:null}}async _recoverAndRefresh(){var e,r;let o="#_recoverAndRefresh()";this._debug(o,"begin");try{let n=await yr(this.storage,this.storageKey);if(n&&this.userStorage){let i=await yr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await zr(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:ki()}else if(n&&!n.user&&!n.user){let i=await yr(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await Ce(this.storage,this.storageKey+"-user"),await zr(this.storage,this.storageKey,n)):n.user=ki()}if(this._debug(o,"session from storage",n),!this._isValidSession(n)){this._debug(o,"session is not valid"),n!==null&&await this._removeSession();return}let s=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<gi;if(this._debug(o,`session has${s?"":" not"} expired with margin of ${gi}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),wi(i)||(this._debug(o,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:a}=await this._getUser(n.access_token);!a&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(o,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(o,"error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(o,"error",n),console.error(n);return}finally{this._debug(o,"end")}}async _callRefreshToken(e){var r,o;if(!e)throw new Oe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new ns;let{data:s,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!s.session)throw new Oe;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(n,"error",s),T(s)){let i={data:null,error:s};return wi(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(o=this.refreshingDeferred)===null||o===void 0||o.reject(s),s}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,o=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${o}`);try{this.broadcastChannel&&o&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){s.push(l)}});if(await Promise.all(i),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ce(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),o=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!o&&r.user&&await zr(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let s=ou(n);await zr(this.storage,this.storageKey,s)}else{let n=ou(r);await zr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Ce(this.storage,this.storageKey),await Ce(this.storage,this.storageKey+"-code-verifier"),await Ce(this.storage,this.storageKey+"-user"),this.userStorage&&await Ce(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&_e()&&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(),Br);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:o}}=r;if(!o||!o.refresh_token||!o.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((o.expires_at*1e3-e)/Br);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Br}ms, refresh threshold is ${pi} ticks`),n<=pi&&await this._callRefreshToken(o.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 is)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!_e()||!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,o){let n=[`provider=${encodeURIComponent(r)}`];if(o?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(o.redirectTo)}`),o?.scopes&&n.push(`scopes=${encodeURIComponent(o.scopes)}`),this.flowType==="pkce"){let[s,i]=await Gr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(a.toString())}if(o?.queryParams){let s=new URLSearchParams(o.queryParams);n.push(s.toString())}return o?.skipBrowserRedirect&&n.push(`skip_http_redirect=${o.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;return s?this._returnResult({data:null,error:s}):await A(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});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:u}=await A(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(o=s?.session)===null||o===void 0?void 0:o.access_token});return u?this._returnResult({data:null,error:u}):(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(T(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 o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?sm(e.webauthn.credential_response):im(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await A(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.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(T(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 o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=await A(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token});if(i.error)return i;let{data:a}=i;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:om(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:nm(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:o}=await this._challenge({factorId:e.factorId});return o?this._returnResult({data:null,error:o}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:o}=await this.getUser();if(o)return{data:null,error:o};let n={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(s),s.status==="verified"&&n[s.factor_type].push(s);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,o,n,s;if(e)try{let{payload:m}=ss(e),h=null;m.aal&&(h=m.aal);let g=h,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((o=(r=y?.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(g="aal2");let _=m.amr||[];return{data:{currentLevel:h,nextLevel:g,currentAuthenticationMethods:_},error:null}}catch(m){if(T(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:i},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=ss(i.access_token),u=null;l.aal&&(u=l.aal);let c=u;((s=(n=i.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let f=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?await A(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:o.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Oe})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Oe});let i=await A(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 i.data&&i.data.redirect_url&&_e()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}async _denyAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Oe});let i=await A(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 i.data&&i.data.redirect_url&&_e()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:o}=e;return o?this._returnResult({data:null,error:o}):r?await A(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 Oe})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?(await A(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:o.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Oe})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let o=r.keys.find(a=>a.kid===e);if(o)return o;let n=Date.now();if(o=this.jwks.keys.find(a=>a.kid===e),o&&this.jwks_cached_at+Af>n)return o;let{data:s,error:i}=await A(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=n,o=s.keys.find(a=>a.kid===e),!o)?null:o}async getClaims(e,r={}){try{let o=e;if(!o){let{data:m,error:h}=await this.getSession();if(h||!m.session)return this._returnResult({data:null,error:h});o=m.session.access_token}let{header:n,payload:s,signature:i,raw:{header:a,payload:l}}=ss(o);r?.allowExpired||Wf(s.exp);let u=!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(!u){let{error:m}=await this.getUser(o);if(m)throw m;return{data:{claims:s,header:n,signature:i},error:null}}let c=Hf(n.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,i,jf(`${a}.${l}`)))throw new Wr("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}};Pi.nextInstanceID={};var du=Pi;var Pw=du,fu=Pw;var Ow="2.100.1",ls="";typeof Deno<"u"?ls="deno":typeof document<"u"?ls="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ls="react-native":ls="node";var Aw={"X-Client-Info":`supabase-js-${ls}/${Ow}`},Rw={headers:Aw},Iw={schema:"public"},Dw={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Lw={};function us(t){"@babel/helpers - typeof";return us=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},us(t)}function Nw(t,e){if(us(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(us(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function jw(t){var e=Nw(t,"string");return us(e)=="symbol"?e:e+""}function Mw(t,e,r){return(e=jw(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function lm(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function ue(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?lm(Object(r),!0).forEach(function(o){Mw(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):lm(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var Uw=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Fw=()=>Headers,$w=(t,e,r)=>{let o=Uw(r),n=Fw();return async(s,i)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),o(s,ue(ue({},i),{},{headers:u}))}};function Bw(t){return t.endsWith("/")?t:t+"/"}function qw(t,e){var r,o;let{db:n,auth:s,realtime:i,global:a}=t,{db:l,auth:u,realtime:c,global:d}=e,f={db:ue(ue({},l),n),auth:ue(ue({},u),s),realtime:ue(ue({},c),i),storage:{},global:ue(ue(ue({},d),a),{},{headers:ue(ue({},(r=d?.headers)!==null&&r!==void 0?r:{}),(o=a?.headers)!==null&&o!==void 0?o:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function Vw(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(Bw(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Ww=class extends fu{constructor(t){super(t)}},Hw=class{constructor(t,e,r){var o,n;this.supabaseUrl=t,this.supabaseKey=e;let s=Vw(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:Iw,realtime:Lw,auth:ue(ue({},Dw),{},{storageKey:i}),global:Rw},l=qw(r??{},a);if(this.storageKey=(o=l.auth.storageKey)!==null&&o!==void 0?o:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,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 u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=$w(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(ue({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new uf(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new Tf(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Wn(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:o}=await t.auth.getSession();return(e=(r=o.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:o,userStorage:n,storageKey:s,flowType:i,lock:a,debug:l,throwOnError:u},c,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ww({url:this.authUrl.href,headers:ue(ue({},f),c),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,flowType:i,lock:a,debug:l,throwOnError:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new No(this.realtimeUrl.href,ue(ue({},t),{},{params:ue(ue({},{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)}},um=(t,e,r)=>new Hw(t,e,r);function zw(){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}zw()&&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 mu="0.5.2";var fm=yn(pu());function Qr(){return typeof window<"u"&&typeof window.document<"u"}var br={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4};var nv=/^(.*)[.](0|[1-9][0-9]*)$/;function cs(t,e){if(t===e)return!0;let r=t.match(nv);return!!(r&&r[1]===e)}function gu(t,e,r){let o=r??3180,n=encodeURIComponent(e);if(n.length<=o)return[{name:t,value:e}];let s=[];for(;n.length>0;){let i=n.slice(0,o),a=i.lastIndexOf("%");a>o-3&&(i=i.slice(0,a));let l="";for(;i.length>0;)try{l=decodeURIComponent(i);break}catch(u){if(u instanceof URIError&&i.at(-3)==="%"&&i.length>3)i=i.slice(0,i.length-3);else throw u}s.push(l),n=n.slice(i.length)}return s.map((i,a)=>({name:`${t}.${a}`,value:i}))}async function yu(t,e){let r=await e(t);if(r)return r;let o=[];for(let n=0;;n++){let s=`${t}.${n}`,i=await e(s);if(!i)break;o.push(i)}return o.length>0?o.join(""):null}var Oi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),mm=`
|
|
88
|
+
\r=`.split(""),sv=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<mm.length;e+=1)t[mm[e].charCodeAt(0)]=-2;for(let e=0;e<Oi.length;e+=1)t[Oi[e].charCodeAt(0)]=e;return t})();function bu(t){let e=[],r=0,o=0;if(av(t,s=>{for(r=r<<8|s,o+=8;o>=6;){let i=r>>o-6&63;e.push(Oi[i]),o-=6}}),o>0)for(r=r<<6-o,o=6;o>=6;){let s=r>>o-6&63;e.push(Oi[s]),o-=6}return e.join("")}function _u(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n=0,s=0;for(let i=0;i<t.length;i+=1){let a=t.charCodeAt(i),l=sv[a];if(l>-1)for(n=n<<6|l,s+=6;s>=8;)lv(n>>s-8&255,o,r),s-=8;else{if(l===-2)continue;throw new Error(`Invalid Base64-URL character "${t.at(i)}" at position ${i}`)}}return e.join("")}function iv(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 av(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}iv(o,e)}}function lv(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;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)}}var Ai=yn(pu());var Fo="base64-";function wu(t,e){let r=t.cookies??null,o=t.cookieEncoding,n={},s={},i,a;if(r)if("get"in r){let l=async u=>{let c=u.flatMap(f=>[f,...Array.from({length:5}).map((m,h)=>`${f}.${h}`)]),d=[];for(let f=0;f<c.length;f+=1){let m=await r.get(c[f]);!m&&typeof m!="string"||d.push({name:c[f],value:m})}return d};if(i=async u=>await l(u),"set"in r&&"remove"in r)a=async u=>{for(let c=0;c<u.length;c+=1){let{name:d,value:f,options:m}=u[c];f?await r.set(d,f,m):await r.remove(d,m)}};else if(e)a=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw new Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in r)if(i=async()=>await r.getAll(),"setAll"in r)a=r.setAll;else if(e)a=async()=>{console.warn("@supabase/ssr: createServerClient was configured without the setAll cookie method, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness.")};else throw new Error("@supabase/ssr: createBrowserClient requires configuring both getAll and setAll cookie methods (deprecated: alternatively both get, set and remove can be used)");else throw new Error(`@supabase/ssr: ${e?"createServerClient":"createBrowserClient"} requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).${Qr()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""}`);else if(!e&&Qr()){let l=()=>{let u=(0,Ai.parse)(document.cookie);return Object.keys(u).map(c=>({name:c,value:u[c]}))};i=()=>l(),a=u=>{u.forEach(({name:c,value:d,options:f})=>{document.cookie=(0,Ai.serialize)(c,d,f)})}}else{if(e)throw new Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");i=()=>[],a=()=>{throw new Error("@supabase/ssr: createBrowserClient in non-browser runtimes (including Next.js pre-rendering mode) was not initialized cookie options that specify getAll and setAll functions (deprecated: alternatively use get, set and remove), but they were needed")}}return e?{getAll:i,setAll:a,setItems:n,removedItems:s,storage:{isServer:!0,getItem:async l=>{if(typeof n[l]=="string")return n[l];if(s[l])return null;let u=await i([l]),c=await yu(l,async f=>{let m=u?.find(({name:h})=>h===f)||null;return m?m.value:null});if(!c)return null;let d=c;return typeof c=="string"&&c.startsWith(Fo)&&(d=_u(c.substring(Fo.length))),d},setItem:async(l,u)=>{l.endsWith("-code-verifier")&&await hm({getAll:i,setAll:a,setItems:{[l]:u},removedItems:{}},{cookieOptions:t?.cookieOptions??null,cookieEncoding:o}),n[l]=u,delete s[l]},removeItem:async l=>{delete n[l],s[l]=!0}}}:{getAll:i,setAll:a,setItems:n,removedItems:s,storage:{isServer:!1,getItem:async l=>{let u=await i([l]),c=await yu(l,async f=>{let m=u?.find(({name:h})=>h===f)||null;return m?m.value:null});if(!c)return null;let d=c;return c.startsWith(Fo)&&(d=_u(c.substring(Fo.length))),d},setItem:async(l,u)=>{let d=(await i([l]))?.map(({name:b})=>b)||[],f=new Set(d.filter(b=>cs(b,l))),m=u;o==="base64url"&&(m=Fo+bu(u));let h=gu(l,m);h.forEach(({name:b})=>{f.delete(b)});let g={...br,...t?.cookieOptions,maxAge:0},y={...br,...t?.cookieOptions,maxAge:br.maxAge};delete g.name,delete y.name;let p=[...[...f].map(b=>({name:b,value:"",options:g})),...h.map(({name:b,value:_})=>({name:b,value:_,options:y}))];p.length>0&&await a(p)},removeItem:async l=>{let d=((await i([l]))?.map(({name:m})=>m)||[]).filter(m=>cs(m,l)),f={...br,...t?.cookieOptions,maxAge:0};delete f.name,d.length>0&&await a(d.map(m=>({name:m,value:"",options:f})))}}}}async function hm({getAll:t,setAll:e,setItems:r,removedItems:o},n){let s=n.cookieEncoding,i=n.cookieOptions??null,l=(await t([...r?Object.keys(r):[],...o?Object.keys(o):[]]))?.map(({name:m})=>m)||[],u=Object.keys(o).flatMap(m=>l.filter(h=>cs(h,m))),c=Object.keys(r).flatMap(m=>{let h=new Set(l.filter(p=>cs(p,m))),g=r[m];s==="base64url"&&(g=Fo+bu(g));let y=gu(m,g);return y.forEach(p=>{h.delete(p.name)}),u.push(...h),y}),d={...br,...i,maxAge:0},f={...br,...i,maxAge:br.maxAge};delete d.name,delete f.name,await e([...u.map(m=>({name:m,value:"",options:d})),...c.map(({name:m,value:h})=>({name:m,value:h,options:f}))])}var vu;function pm(t,e,r){let o=r?.isSingleton===!0||(!r||!("isSingleton"in r))&&Qr();if(o&&vu)return vu;if(!t||!e)throw new Error(`@supabase/ssr: Your project's URL and API key are required to create a Supabase client!
|
|
89
89
|
|
|
90
90
|
Check your Supabase project's API settings to find these values
|
|
91
91
|
|
|
92
|
-
https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=
|
|
92
|
+
https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=wu({...r,cookieEncoding:r?.cookieEncoding??"base64url"},!1),s=um(t,e,{...r,global:{...r?.global,headers:{...r?.global?.headers,"X-Client-Info":`supabase-ssr/${mu}`}},auth:{...r?.auth,...r?.cookieOptions?.name?{storageKey:r.cookieOptions.name}:null,flowType:"pkce",autoRefreshToken:Qr(),detectSessionInUrl:Qr(),persistSession:!0,storage:n}});return o&&(vu=s),s}var Su=process.env.NEXT_PUBLIC_SUPABASE_URL||process.env.EXPO_PUBLIC_SUPABASE_URL||"https://dhnpoxorllfdobwftkyb.supabase.co",xu=process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY||process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY||"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRobnBveG9ybGxmZG9id2Z0a3liIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzkwNTQxMDgsImV4cCI6MjA1NDYzMDEwOH0.zI8PwbgKwijHZ1QmxJqmaPrFvg02w1vOY2Qcs7SddzI";var Ri=process.env.NODE_ENV==="production"?"https://api.zorgotech.com":"http://localhost:3000";var ds={DEFAULTS:{PREP_MINUTES:20,PAST_HOURS:24,FUTURE_HOURS:72},ORDER_STATUS:{STAGING:10,PENDING:1,COMPLETED:2,CANCELLED:4,PAID:6,PARTIALLY_PAID:7,KITCHEN_DONE:9,CONFIRMED:11,PREPARING:12,REQUESTED:13},POS_METHOD_ID:3,TEST_CUSTOMER_IDS:[85,90,91,93,95,96,97,203,238,240,241,244,245,246,317,318,319,322,579,580,658,1526,2567,2573,2703,2725,2737,2739,2740,2741,2742,2744,2746,2747,2749,2751,2752,2753,2754,2755,2767,2768,2778,2779,2780,2781,2783,2814,2816,2818,2819,2820,2821,2822,2823,2824,2835,2836,2851,2853,2859,2871,2882,2883,2887,2888,2889,2891,2892,2893,2894,2895,2896,2897,2898,2899,2900,2901,2902,2903,2904,2905,2907,2908,2919,2921,2922,2923,2924,2925,2926,2927,2946,3017,3018,3022,3024,3025,3026,3027,3028,3029,3030,3031,3082,3091,3092,3093],ORDER_TYPE:{DINE_IN:1,TAKEOUT:2,DELIVERY:3},MODIFICATION_HIGHLIGHT_MS:8e3,LISTENER_SYNC_INTERVAL_MS:6e4,ORDER_SELECT:`
|
|
93
93
|
*,
|
|
94
94
|
|
|
95
95
|
charges (
|
|
@@ -108,7 +108,7 @@ https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=bu({...r,
|
|
|
108
108
|
item_id, name, price,
|
|
109
109
|
portion_schemes (id, franchise_id, geometry, name, min_divisions, max_divisions),
|
|
110
110
|
base_items (
|
|
111
|
-
base_item_id, category_id, name,
|
|
111
|
+
base_item_id, category_id, name, per_person,
|
|
112
112
|
categories (category_id, name, is_catering)
|
|
113
113
|
)
|
|
114
114
|
),
|
|
@@ -137,7 +137,7 @@ https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=bu({...r,
|
|
|
137
137
|
components (id, name, component_type_id, serving_weight, measurement_type, display_unit)
|
|
138
138
|
)
|
|
139
139
|
)
|
|
140
|
-
`};var hm=null;var Su=(t,e)=>{if(!hm)return fetch(t,e);let r=new Headers(e?.headers);return r.set("Authorization",`Bearer ${hm}`),fetch(t,{...e,headers:r})};var Eu=globalThis?.navigator?.product==="ReactNative",Om=typeof process<"u"&&process.versions?.node,yv=!Eu&&!Om&&typeof globalThis?.document<"u";function Pm(){if(!Om&&Eu)try{return(Cu(),Kc(Tu)).default}catch{return}}function bv(){return yv?mm(wu,vu,{global:{fetch:Su}}):tf(wu,vu,{auth:{autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!Eu,...Pm()?{storage:Pm()}:{},lock:jl},global:{fetch:Su}})}var M=bv();import{immer as jS}from"zustand/middleware/immer";import{createJSONStorage as MS,devtools as US,persist as FS}from"zustand/middleware";var _v=Math.pow(10,8)*24*60*60*1e3,PI=-_v,Ni=6048e5,Am=864e5,ji=6e4,Mi=36e5,Rm=1e3;var wv=3600;var Im=wv*24,OI=Im*7,vv=Im*365.2425,Sv=vv/12,AI=Sv*3,Pu=Symbol.for("constructDateFrom");function V(t,e){return typeof t=="function"?t(e):t&&typeof t=="object"&&Pu in t?t[Pu](e):t instanceof Date?new t.constructor(e):new Date(e)}function R(t,e){return V(e||t,t)}function Ui(t,e,r){let o=R(t,r?.in);return isNaN(e)?V(r?.in||t,NaN):(e&&o.setDate(o.getDate()+e),o)}function Dm(t,e,r){return V(r?.in||t,+R(t)+e)}function Vo(t,e,r){return Dm(t,e*Mi,r)}var xv={};function lt(){return xv}function Ve(t,e){let r=lt(),o=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=R(t,e?.in),s=n.getDay(),i=(s<o?7:0)+s-o;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function St(t,e){return Ve(t,{...e,weekStartsOn:1})}function Fi(t,e){let r=R(t,e?.in),o=r.getFullYear(),n=V(r,0);n.setFullYear(o+1,0,4),n.setHours(0,0,0,0);let s=St(n),i=V(r,0);i.setFullYear(o,0,4),i.setHours(0,0,0,0);let a=St(i);return r.getTime()>=s.getTime()?o+1:r.getTime()>=a.getTime()?o:o-1}function eo(t){let e=R(t),r=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return r.setUTCFullYear(e.getFullYear()),+t-+r}function Lm(t,...e){let r=V.bind(null,t||e.find(o=>typeof o=="object"));return e.map(r)}function xt(t,e){let r=R(t,e?.in);return r.setHours(0,0,0,0),r}function Nm(t,e,r){let[o,n]=Lm(r?.in,t,e),s=xt(o),i=xt(n),a=+s-eo(s),l=+i-eo(i);return Math.round((a-l)/Am)}function jm(t,e){let r=Fi(t,e),o=V(e?.in||t,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),St(o)}function Mm(t,e,r){let o=R(t,r?.in);return o.setTime(o.getTime()+e*ji),o}function Um(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function to(t){return!(!Um(t)&&typeof t!="number"||isNaN(+R(t)))}function Fm(t,e){return+R(t)-+R(e)}function $m(t,e){let r=R(t,e?.in);return r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0),r}var kv={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Bm=(t,e,r)=>{let o,n=kv[t];return typeof n=="string"?o=n:e===1?o=n.one:o=n.other.replace("{{count}}",e.toString()),r?.addSuffix?r.comparison&&r.comparison>0?"in "+o:o+" ago":o};function $i(t){return(e={})=>{let r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}var Tv={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Cv={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Ev={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},qm={date:$i({formats:Tv,defaultWidth:"full"}),time:$i({formats:Cv,defaultWidth:"full"}),dateTime:$i({formats:Ev,defaultWidth:"full"})};var Pv={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Vm=(t,e,r,o)=>Pv[t];function Wo(t){return(e,r)=>{let o=r?.context?String(r.context):"standalone",n;if(o==="formatting"&&t.formattingValues){let i=t.defaultFormattingWidth||t.defaultWidth,a=r?.width?String(r.width):i;n=t.formattingValues[a]||t.formattingValues[i]}else{let i=t.defaultWidth,a=r?.width?String(r.width):t.defaultWidth;n=t.values[a]||t.values[i]}let s=t.argumentCallback?t.argumentCallback(e):e;return n[s]}}var Ov={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Av={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Rv={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Iv={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Dv={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Lv={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},Nv=(t,e)=>{let r=Number(t),o=r%100;if(o>20||o<10)switch(o%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},Wm={ordinalNumber:Nv,era:Wo({values:Ov,defaultWidth:"wide"}),quarter:Wo({values:Av,defaultWidth:"wide",argumentCallback:t=>t-1}),month:Wo({values:Rv,defaultWidth:"wide"}),day:Wo({values:Iv,defaultWidth:"wide"}),dayPeriod:Wo({values:Dv,defaultWidth:"wide",formattingValues:Lv,defaultFormattingWidth:"wide"})};function Ho(t){return(e,r={})=>{let o=r.width,n=o&&t.matchPatterns[o]||t.matchPatterns[t.defaultMatchWidth],s=e.match(n);if(!s)return null;let i=s[0],a=o&&t.parsePatterns[o]||t.parsePatterns[t.defaultParseWidth],l=Array.isArray(a)?Mv(a,d=>d.test(i)):jv(a,d=>d.test(i)),u;u=t.valueCallback?t.valueCallback(l):l,u=r.valueCallback?r.valueCallback(u):u;let c=e.slice(i.length);return{value:u,rest:c}}}function jv(t,e){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function Mv(t,e){for(let r=0;r<t.length;r++)if(e(t[r]))return r}function Hm(t){return(e,r={})=>{let o=e.match(t.matchPattern);if(!o)return null;let n=o[0],s=e.match(t.parsePattern);if(!s)return null;let i=t.valueCallback?t.valueCallback(s[0]):s[0];i=r.valueCallback?r.valueCallback(i):i;let a=e.slice(n.length);return{value:i,rest:a}}}var Uv=/^(\d+)(th|st|nd|rd)?/i,Fv=/\d+/i,$v={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Bv={any:[/^b/i,/^(a|c)/i]},qv={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Vv={any:[/1/i,/2/i,/3/i,/4/i]},Wv={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},Hv={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},zv={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Gv={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Kv={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Jv={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},zm={ordinalNumber:Hm({matchPattern:Uv,parsePattern:Fv,valueCallback:t=>parseInt(t,10)}),era:Ho({matchPatterns:$v,defaultMatchWidth:"wide",parsePatterns:Bv,defaultParseWidth:"any"}),quarter:Ho({matchPatterns:qv,defaultMatchWidth:"wide",parsePatterns:Vv,defaultParseWidth:"any",valueCallback:t=>t+1}),month:Ho({matchPatterns:Wv,defaultMatchWidth:"wide",parsePatterns:Hv,defaultParseWidth:"any"}),day:Ho({matchPatterns:zv,defaultMatchWidth:"wide",parsePatterns:Gv,defaultParseWidth:"any"}),dayPeriod:Ho({matchPatterns:Kv,defaultMatchWidth:"any",parsePatterns:Jv,defaultParseWidth:"any"})};var ms={code:"en-US",formatDistance:Bm,formatLong:qm,formatRelative:Vm,localize:Wm,match:zm,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Gm(t,e){let r=R(t,e?.in);return Nm(r,$m(r))+1}function Bi(t,e){let r=R(t,e?.in),o=+St(r)-+jm(r);return Math.round(o/Ni)+1}function zo(t,e){let r=R(t,e?.in),o=r.getFullYear(),n=lt(),s=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=V(e?.in||t,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=Ve(i,e),l=V(e?.in||t,0);l.setFullYear(o,0,s),l.setHours(0,0,0,0);let u=Ve(l,e);return+r>=+a?o+1:+r>=+u?o:o-1}function Km(t,e){let r=lt(),o=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=zo(t,e),s=V(e?.in||t,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),Ve(s,e)}function qi(t,e){let r=R(t,e?.in),o=+Ve(r,e)-+Km(r,e);return Math.round(o/Ni)+1}function J(t,e){let r=t<0?"-":"",o=Math.abs(t).toString().padStart(e,"0");return r+o}var Qt={y(t,e){let r=t.getFullYear(),o=r>0?r:1-r;return J(e==="yy"?o%100:o,e.length)},M(t,e){let r=t.getMonth();return e==="M"?String(r+1):J(r+1,2)},d(t,e){return J(t.getDate(),e.length)},a(t,e){let r=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];default:return r==="am"?"a.m.":"p.m."}},h(t,e){return J(t.getHours()%12||12,e.length)},H(t,e){return J(t.getHours(),e.length)},m(t,e){return J(t.getMinutes(),e.length)},s(t,e){return J(t.getSeconds(),e.length)},S(t,e){let r=e.length,o=t.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return J(n,e.length)}};var Go={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ou={G:function(t,e,r){let o=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return r.era(o,{width:"abbreviated"});case"GGGGG":return r.era(o,{width:"narrow"});default:return r.era(o,{width:"wide"})}},y:function(t,e,r){if(e==="yo"){let o=t.getFullYear(),n=o>0?o:1-o;return r.ordinalNumber(n,{unit:"year"})}return Qt.y(t,e)},Y:function(t,e,r,o){let n=zo(t,o),s=n>0?n:1-n;if(e==="YY"){let i=s%100;return J(i,2)}return e==="Yo"?r.ordinalNumber(s,{unit:"year"}):J(s,e.length)},R:function(t,e){let r=Fi(t);return J(r,e.length)},u:function(t,e){let r=t.getFullYear();return J(r,e.length)},Q:function(t,e,r){let o=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(o);case"QQ":return J(o,2);case"Qo":return r.ordinalNumber(o,{unit:"quarter"});case"QQQ":return r.quarter(o,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(o,{width:"narrow",context:"formatting"});default:return r.quarter(o,{width:"wide",context:"formatting"})}},q:function(t,e,r){let o=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(o);case"qq":return J(o,2);case"qo":return r.ordinalNumber(o,{unit:"quarter"});case"qqq":return r.quarter(o,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(o,{width:"narrow",context:"standalone"});default:return r.quarter(o,{width:"wide",context:"standalone"})}},M:function(t,e,r){let o=t.getMonth();switch(e){case"M":case"MM":return Qt.M(t,e);case"Mo":return r.ordinalNumber(o+1,{unit:"month"});case"MMM":return r.month(o,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(o,{width:"narrow",context:"formatting"});default:return r.month(o,{width:"wide",context:"formatting"})}},L:function(t,e,r){let o=t.getMonth();switch(e){case"L":return String(o+1);case"LL":return J(o+1,2);case"Lo":return r.ordinalNumber(o+1,{unit:"month"});case"LLL":return r.month(o,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(o,{width:"narrow",context:"standalone"});default:return r.month(o,{width:"wide",context:"standalone"})}},w:function(t,e,r,o){let n=qi(t,o);return e==="wo"?r.ordinalNumber(n,{unit:"week"}):J(n,e.length)},I:function(t,e,r){let o=Bi(t);return e==="Io"?r.ordinalNumber(o,{unit:"week"}):J(o,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):Qt.d(t,e)},D:function(t,e,r){let o=Gm(t);return e==="Do"?r.ordinalNumber(o,{unit:"dayOfYear"}):J(o,e.length)},E:function(t,e,r){let o=t.getDay();switch(e){case"E":case"EE":case"EEE":return r.day(o,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(o,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(o,{width:"short",context:"formatting"});default:return r.day(o,{width:"wide",context:"formatting"})}},e:function(t,e,r,o){let n=t.getDay(),s=(n-o.weekStartsOn+8)%7||7;switch(e){case"e":return String(s);case"ee":return J(s,2);case"eo":return r.ordinalNumber(s,{unit:"day"});case"eee":return r.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(n,{width:"short",context:"formatting"});default:return r.day(n,{width:"wide",context:"formatting"})}},c:function(t,e,r,o){let n=t.getDay(),s=(n-o.weekStartsOn+8)%7||7;switch(e){case"c":return String(s);case"cc":return J(s,e.length);case"co":return r.ordinalNumber(s,{unit:"day"});case"ccc":return r.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(n,{width:"narrow",context:"standalone"});case"cccccc":return r.day(n,{width:"short",context:"standalone"});default:return r.day(n,{width:"wide",context:"standalone"})}},i:function(t,e,r){let o=t.getDay(),n=o===0?7:o;switch(e){case"i":return String(n);case"ii":return J(n,e.length);case"io":return r.ordinalNumber(n,{unit:"day"});case"iii":return r.day(o,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(o,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(o,{width:"short",context:"formatting"});default:return r.day(o,{width:"wide",context:"formatting"})}},a:function(t,e,r){let n=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(t,e,r){let o=t.getHours(),n;switch(o===12?n=Go.noon:o===0?n=Go.midnight:n=o/12>=1?"pm":"am",e){case"b":case"bb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(t,e,r){let o=t.getHours(),n;switch(o>=17?n=Go.evening:o>=12?n=Go.afternoon:o>=4?n=Go.morning:n=Go.night,e){case"B":case"BB":case"BBB":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(t,e,r){if(e==="ho"){let o=t.getHours()%12;return o===0&&(o=12),r.ordinalNumber(o,{unit:"hour"})}return Qt.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):Qt.H(t,e)},K:function(t,e,r){let o=t.getHours()%12;return e==="Ko"?r.ordinalNumber(o,{unit:"hour"}):J(o,e.length)},k:function(t,e,r){let o=t.getHours();return o===0&&(o=24),e==="ko"?r.ordinalNumber(o,{unit:"hour"}):J(o,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):Qt.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):Qt.s(t,e)},S:function(t,e){return Qt.S(t,e)},X:function(t,e,r){let o=t.getTimezoneOffset();if(o===0)return"Z";switch(e){case"X":return Ym(o);case"XXXX":case"XX":return ro(o);default:return ro(o,":")}},x:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"x":return Ym(o);case"xxxx":case"xx":return ro(o);default:return ro(o,":")}},O:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Jm(o,":");default:return"GMT"+ro(o,":")}},z:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Jm(o,":");default:return"GMT"+ro(o,":")}},t:function(t,e,r){let o=Math.trunc(+t/1e3);return J(o,e.length)},T:function(t,e,r){return J(+t,e.length)}};function Jm(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Math.trunc(o/60),s=o%60;return s===0?r+String(n):r+String(n)+e+J(s,2)}function Ym(t,e){return t%60===0?(t>0?"-":"+")+J(Math.abs(t)/60,2):ro(t,e)}function ro(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=J(Math.trunc(o/60),2),s=J(o%60,2);return r+n+e+s}var Xm=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});default:return e.date({width:"full"})}},Qm=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});default:return e.time({width:"full"})}},Yv=(t,e)=>{let r=t.match(/(P+)(p+)?/)||[],o=r[1],n=r[2];if(!n)return Xm(t,e);let s;switch(o){case"P":s=e.dateTime({width:"short"});break;case"PP":s=e.dateTime({width:"medium"});break;case"PPP":s=e.dateTime({width:"long"});break;default:s=e.dateTime({width:"full"});break}return s.replace("{{date}}",Xm(o,e)).replace("{{time}}",Qm(n,e))},hs={p:Qm,P:Yv};var Xv=/^D+$/,Qv=/^Y+$/,Zv=["D","DD","YY","YYYY"];function Vi(t){return Xv.test(t)}function Wi(t){return Qv.test(t)}function ps(t,e,r){let o=e0(t,e,r);if(console.warn(o),Zv.includes(t))throw new RangeError(o)}function e0(t,e,r){let o=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${o} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var t0=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,r0=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,o0=/^'([^]*?)'?$/,n0=/''/g,s0=/[a-zA-Z]/;function Ue(t,e,r){let o=lt(),n=r?.locale??o.locale??ms,s=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??o.firstWeekContainsDate??o.locale?.options?.firstWeekContainsDate??1,i=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,a=R(t,r?.in);if(!to(a))throw new RangeError("Invalid time value");let l=e.match(r0).map(c=>{let d=c[0];if(d==="p"||d==="P"){let f=hs[d];return f(c,n.formatLong)}return c}).join("").match(t0).map(c=>{if(c==="''")return{isToken:!1,value:"'"};let d=c[0];if(d==="'")return{isToken:!1,value:i0(c)};if(Ou[d])return{isToken:!0,value:c};if(d.match(s0))throw new RangeError("Format string contains an unescaped latin alphabet character `"+d+"`");return{isToken:!1,value:c}});n.localize.preprocessor&&(l=n.localize.preprocessor(a,l));let u={firstWeekContainsDate:s,weekStartsOn:i,locale:n};return l.map(c=>{if(!c.isToken)return c.value;let d=c.value;(!r?.useAdditionalWeekYearTokens&&Wi(d)||!r?.useAdditionalDayOfYearTokens&&Vi(d))&&ps(d,e,String(t));let f=Ou[d[0]];return f(a,d,n.localize,u)}).join("")}function i0(t){let e=t.match(o0);return e?e[1].replace(n0,"'"):t}function Hi(t,e){return R(t,e?.in).getDay()}function zi(){return Object.assign({},lt())}function Zm(t,e){let r=R(t,e?.in).getDay();return r===0?7:r}function jt(t,e){return+R(t)>+R(e)}function We(t,e){return+R(t)<+R(e)}function eh(t,e){let r=a0(e)?new e(0):V(e,0);return r.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),r.setHours(t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()),r}function a0(t){return typeof t=="function"&&t.prototype?.constructor===t}var l0=10,Gi=class{subPriority=0;validate(e,r){return!0}},Ki=class extends Gi{constructor(e,r,o,n,s){super(),this.value=e,this.validateValue=r,this.setValue=o,this.priority=n,s&&(this.subPriority=s)}validate(e,r){return this.validateValue(e,this.value,r)}set(e,r,o){return this.setValue(e,r,this.value,o)}},Ji=class extends Gi{priority=l0;subPriority=-1;constructor(e,r){super(),this.context=e||(o=>V(r,o))}set(e,r){return r.timestampIsSet?e:V(e,eh(e,this.context))}};var C=class{run(e,r,o,n){let s=this.parse(e,r,o,n);return s?{setter:new Ki(s.value,this.validate,this.set,this.priority,this.subPriority),rest:s.rest}:null}validate(e,r,o){return!0}};var Yi=class extends C{priority=140;parse(e,r,o){switch(r){case"G":case"GG":case"GGG":return o.era(e,{width:"abbreviated"})||o.era(e,{width:"narrow"});case"GGGGG":return o.era(e,{width:"narrow"});default:return o.era(e,{width:"wide"})||o.era(e,{width:"abbreviated"})||o.era(e,{width:"narrow"})}}set(e,r,o){return r.era=o,e.setFullYear(o,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["R","u","t","T"]};var z={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},ut={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function Y(t,e){return t&&{value:e(t.value),rest:t.rest}}function W(t,e){let r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function ct(t,e){let r=e.match(t);if(!r)return null;if(r[0]==="Z")return{value:0,rest:e.slice(1)};let o=r[1]==="+"?1:-1,n=r[2]?parseInt(r[2],10):0,s=r[3]?parseInt(r[3],10):0,i=r[5]?parseInt(r[5],10):0;return{value:o*(n*Mi+s*ji+i*Rm),rest:e.slice(r[0].length)}}function Xi(t){return W(z.anyDigitsSigned,t)}function U(t,e){switch(t){case 1:return W(z.singleDigit,e);case 2:return W(z.twoDigits,e);case 3:return W(z.threeDigits,e);case 4:return W(z.fourDigits,e);default:return W(new RegExp("^\\d{1,"+t+"}"),e)}}function Ko(t,e){switch(t){case 1:return W(z.singleDigitSigned,e);case 2:return W(z.twoDigitsSigned,e);case 3:return W(z.threeDigitsSigned,e);case 4:return W(z.fourDigitsSigned,e);default:return W(new RegExp("^-?\\d{1,"+t+"}"),e)}}function Jo(t){switch(t){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function Qi(t,e){let r=e>0,o=r?e:1-e,n;if(o<=50)n=t||100;else{let s=o+50,i=Math.trunc(s/100)*100,a=t>=s%100;n=t+i-(a?100:0)}return r?n:1-n}function Zi(t){return t%400===0||t%4===0&&t%100!==0}var ea=class extends C{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(e,r,o){let n=s=>({year:s,isTwoDigitYear:r==="yy"});switch(r){case"y":return Y(U(4,e),n);case"yo":return Y(o.ordinalNumber(e,{unit:"year"}),n);default:return Y(U(r.length,e),n)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,o){let n=e.getFullYear();if(o.isTwoDigitYear){let i=Qi(o.year,n);return e.setFullYear(i,0,1),e.setHours(0,0,0,0),e}let s=!("era"in r)||r.era===1?o.year:1-o.year;return e.setFullYear(s,0,1),e.setHours(0,0,0,0),e}};var ta=class extends C{priority=130;parse(e,r,o){let n=s=>({year:s,isTwoDigitYear:r==="YY"});switch(r){case"Y":return Y(U(4,e),n);case"Yo":return Y(o.ordinalNumber(e,{unit:"year"}),n);default:return Y(U(r.length,e),n)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,o,n){let s=zo(e,n);if(o.isTwoDigitYear){let a=Qi(o.year,s);return e.setFullYear(a,0,n.firstWeekContainsDate),e.setHours(0,0,0,0),Ve(e,n)}let i=!("era"in r)||r.era===1?o.year:1-o.year;return e.setFullYear(i,0,n.firstWeekContainsDate),e.setHours(0,0,0,0),Ve(e,n)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]};var ra=class extends C{priority=130;parse(e,r){return r==="R"?Ko(4,e):Ko(r.length,e)}set(e,r,o){let n=V(e,0);return n.setFullYear(o,0,4),n.setHours(0,0,0,0),St(n)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]};var oa=class extends C{priority=130;parse(e,r){return r==="u"?Ko(4,e):Ko(r.length,e)}set(e,r,o){return e.setFullYear(o,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]};var na=class extends C{priority=120;parse(e,r,o){switch(r){case"Q":case"QQ":return U(r.length,e);case"Qo":return o.ordinalNumber(e,{unit:"quarter"});case"QQQ":return o.quarter(e,{width:"abbreviated",context:"formatting"})||o.quarter(e,{width:"narrow",context:"formatting"});case"QQQQQ":return o.quarter(e,{width:"narrow",context:"formatting"});default:return o.quarter(e,{width:"wide",context:"formatting"})||o.quarter(e,{width:"abbreviated",context:"formatting"})||o.quarter(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=1&&r<=4}set(e,r,o){return e.setMonth((o-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]};var sa=class extends C{priority=120;parse(e,r,o){switch(r){case"q":case"qq":return U(r.length,e);case"qo":return o.ordinalNumber(e,{unit:"quarter"});case"qqq":return o.quarter(e,{width:"abbreviated",context:"standalone"})||o.quarter(e,{width:"narrow",context:"standalone"});case"qqqqq":return o.quarter(e,{width:"narrow",context:"standalone"});default:return o.quarter(e,{width:"wide",context:"standalone"})||o.quarter(e,{width:"abbreviated",context:"standalone"})||o.quarter(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=1&&r<=4}set(e,r,o){return e.setMonth((o-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]};var ia=class extends C{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(e,r,o){let n=s=>s-1;switch(r){case"M":return Y(W(z.month,e),n);case"MM":return Y(U(2,e),n);case"Mo":return Y(o.ordinalNumber(e,{unit:"month"}),n);case"MMM":return o.month(e,{width:"abbreviated",context:"formatting"})||o.month(e,{width:"narrow",context:"formatting"});case"MMMMM":return o.month(e,{width:"narrow",context:"formatting"});default:return o.month(e,{width:"wide",context:"formatting"})||o.month(e,{width:"abbreviated",context:"formatting"})||o.month(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.setMonth(o,1),e.setHours(0,0,0,0),e}};var aa=class extends C{priority=110;parse(e,r,o){let n=s=>s-1;switch(r){case"L":return Y(W(z.month,e),n);case"LL":return Y(U(2,e),n);case"Lo":return Y(o.ordinalNumber(e,{unit:"month"}),n);case"LLL":return o.month(e,{width:"abbreviated",context:"standalone"})||o.month(e,{width:"narrow",context:"standalone"});case"LLLLL":return o.month(e,{width:"narrow",context:"standalone"});default:return o.month(e,{width:"wide",context:"standalone"})||o.month(e,{width:"abbreviated",context:"standalone"})||o.month(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.setMonth(o,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]};function th(t,e,r){let o=R(t,r?.in),n=qi(o,r)-e;return o.setDate(o.getDate()-n*7),R(o,r?.in)}var la=class extends C{priority=100;parse(e,r,o){switch(r){case"w":return W(z.week,e);case"wo":return o.ordinalNumber(e,{unit:"week"});default:return U(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,o,n){return Ve(th(e,o,n),n)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]};function rh(t,e,r){let o=R(t,r?.in),n=Bi(o,r)-e;return o.setDate(o.getDate()-n*7),o}var ua=class extends C{priority=100;parse(e,r,o){switch(r){case"I":return W(z.week,e);case"Io":return o.ordinalNumber(e,{unit:"week"});default:return U(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,o){return St(rh(e,o))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]};var u0=[31,28,31,30,31,30,31,31,30,31,30,31],c0=[31,29,31,30,31,30,31,31,30,31,30,31],ca=class extends C{priority=90;subPriority=1;parse(e,r,o){switch(r){case"d":return W(z.date,e);case"do":return o.ordinalNumber(e,{unit:"date"});default:return U(r.length,e)}}validate(e,r){let o=e.getFullYear(),n=Zi(o),s=e.getMonth();return n?r>=1&&r<=c0[s]:r>=1&&r<=u0[s]}set(e,r,o){return e.setDate(o),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]};var da=class extends C{priority=90;subpriority=1;parse(e,r,o){switch(r){case"D":case"DD":return W(z.dayOfYear,e);case"Do":return o.ordinalNumber(e,{unit:"date"});default:return U(r.length,e)}}validate(e,r){let o=e.getFullYear();return Zi(o)?r>=1&&r<=366:r>=1&&r<=365}set(e,r,o){return e.setMonth(0,o),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]};function Yo(t,e,r){let o=lt(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,s=R(t,r?.in),i=s.getDay(),l=(e%7+7)%7,u=7-n,c=e<0||e>6?e-(i+u)%7:(l+u)%7-(i+u)%7;return Ui(s,c,r)}var fa=class extends C{priority=90;parse(e,r,o){switch(r){case"E":case"EE":case"EEE":return o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});case"EEEEE":return o.day(e,{width:"narrow",context:"formatting"});case"EEEEEE":return o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});default:return o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=Yo(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["D","i","e","c","t","T"]};var ma=class extends C{priority=90;parse(e,r,o,n){let s=i=>{let a=Math.floor((i-1)/7)*7;return(i+n.weekStartsOn+6)%7+a};switch(r){case"e":case"ee":return Y(U(r.length,e),s);case"eo":return Y(o.ordinalNumber(e,{unit:"day"}),s);case"eee":return o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});case"eeeee":return o.day(e,{width:"narrow",context:"formatting"});case"eeeeee":return o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});default:return o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=Yo(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]};var ha=class extends C{priority=90;parse(e,r,o,n){let s=i=>{let a=Math.floor((i-1)/7)*7;return(i+n.weekStartsOn+6)%7+a};switch(r){case"c":case"cc":return Y(U(r.length,e),s);case"co":return Y(o.ordinalNumber(e,{unit:"day"}),s);case"ccc":return o.day(e,{width:"abbreviated",context:"standalone"})||o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"});case"ccccc":return o.day(e,{width:"narrow",context:"standalone"});case"cccccc":return o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"});default:return o.day(e,{width:"wide",context:"standalone"})||o.day(e,{width:"abbreviated",context:"standalone"})||o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=Yo(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]};function oh(t,e,r){let o=R(t,r?.in),n=Zm(o,r),s=e-n;return Ui(o,s,r)}var pa=class extends C{priority=90;parse(e,r,o){let n=s=>s===0?7:s;switch(r){case"i":case"ii":return U(r.length,e);case"io":return o.ordinalNumber(e,{unit:"day"});case"iii":return Y(o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n);case"iiiii":return Y(o.day(e,{width:"narrow",context:"formatting"}),n);case"iiiiii":return Y(o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n);default:return Y(o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n)}}validate(e,r){return r>=1&&r<=7}set(e,r,o){return e=oh(e,o),e.setHours(0,0,0,0),e}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]};var ga=class extends C{priority=80;parse(e,r,o){switch(r){case"a":case"aa":case"aaa":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"aaaaa":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(Jo(o),0,0,0),e}incompatibleTokens=["b","B","H","k","t","T"]};var ya=class extends C{priority=80;parse(e,r,o){switch(r){case"b":case"bb":case"bbb":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"bbbbb":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(Jo(o),0,0,0),e}incompatibleTokens=["a","B","H","k","t","T"]};var ba=class extends C{priority=80;parse(e,r,o){switch(r){case"B":case"BB":case"BBB":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"BBBBB":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(Jo(o),0,0,0),e}incompatibleTokens=["a","b","t","T"]};var _a=class extends C{priority=70;parse(e,r,o){switch(r){case"h":return W(z.hour12h,e);case"ho":return o.ordinalNumber(e,{unit:"hour"});default:return U(r.length,e)}}validate(e,r){return r>=1&&r<=12}set(e,r,o){let n=e.getHours()>=12;return n&&o<12?e.setHours(o+12,0,0,0):!n&&o===12?e.setHours(0,0,0,0):e.setHours(o,0,0,0),e}incompatibleTokens=["H","K","k","t","T"]};var wa=class extends C{priority=70;parse(e,r,o){switch(r){case"H":return W(z.hour23h,e);case"Ho":return o.ordinalNumber(e,{unit:"hour"});default:return U(r.length,e)}}validate(e,r){return r>=0&&r<=23}set(e,r,o){return e.setHours(o,0,0,0),e}incompatibleTokens=["a","b","h","K","k","t","T"]};var va=class extends C{priority=70;parse(e,r,o){switch(r){case"K":return W(z.hour11h,e);case"Ko":return o.ordinalNumber(e,{unit:"hour"});default:return U(r.length,e)}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.getHours()>=12&&o<12?e.setHours(o+12,0,0,0):e.setHours(o,0,0,0),e}incompatibleTokens=["h","H","k","t","T"]};var Sa=class extends C{priority=70;parse(e,r,o){switch(r){case"k":return W(z.hour24h,e);case"ko":return o.ordinalNumber(e,{unit:"hour"});default:return U(r.length,e)}}validate(e,r){return r>=1&&r<=24}set(e,r,o){let n=o<=24?o%24:o;return e.setHours(n,0,0,0),e}incompatibleTokens=["a","b","h","H","K","t","T"]};var xa=class extends C{priority=60;parse(e,r,o){switch(r){case"m":return W(z.minute,e);case"mo":return o.ordinalNumber(e,{unit:"minute"});default:return U(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,o){return e.setMinutes(o,0,0),e}incompatibleTokens=["t","T"]};var ka=class extends C{priority=50;parse(e,r,o){switch(r){case"s":return W(z.second,e);case"so":return o.ordinalNumber(e,{unit:"second"});default:return U(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,o){return e.setSeconds(o,0),e}incompatibleTokens=["t","T"]};var Ta=class extends C{priority=30;parse(e,r){let o=n=>Math.trunc(n*Math.pow(10,-r.length+3));return Y(U(r.length,e),o)}set(e,r,o){return e.setMilliseconds(o),e}incompatibleTokens=["t","T"]};var Ca=class extends C{priority=10;parse(e,r){switch(r){case"X":return ct(ut.basicOptionalMinutes,e);case"XX":return ct(ut.basic,e);case"XXXX":return ct(ut.basicOptionalSeconds,e);case"XXXXX":return ct(ut.extendedOptionalSeconds,e);default:return ct(ut.extended,e)}}set(e,r,o){return r.timestampIsSet?e:V(e,e.getTime()-eo(e)-o)}incompatibleTokens=["t","T","x"]};var Ea=class extends C{priority=10;parse(e,r){switch(r){case"x":return ct(ut.basicOptionalMinutes,e);case"xx":return ct(ut.basic,e);case"xxxx":return ct(ut.basicOptionalSeconds,e);case"xxxxx":return ct(ut.extendedOptionalSeconds,e);default:return ct(ut.extended,e)}}set(e,r,o){return r.timestampIsSet?e:V(e,e.getTime()-eo(e)-o)}incompatibleTokens=["t","T","X"]};var Pa=class extends C{priority=40;parse(e){return Xi(e)}set(e,r,o){return[V(e,o*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"};var Oa=class extends C{priority=20;parse(e){return Xi(e)}set(e,r,o){return[V(e,o),{timestampIsSet:!0}]}incompatibleTokens="*"};var nh={G:new Yi,y:new ea,Y:new ta,R:new ra,u:new oa,Q:new na,q:new sa,M:new ia,L:new aa,w:new la,I:new ua,d:new ca,D:new da,E:new fa,e:new ma,c:new ha,i:new pa,a:new ga,b:new ya,B:new ba,h:new _a,H:new wa,K:new va,k:new Sa,m:new xa,s:new ka,S:new Ta,X:new Ca,x:new Ea,t:new Pa,T:new Oa};var d0=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,f0=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,m0=/^'([^]*?)'?$/,h0=/''/g,p0=/\S/,g0=/[a-zA-Z]/;function Je(t,e,r,o){let n=()=>V(o?.in||r,NaN),s=zi(),i=o?.locale??s.locale??ms,a=o?.firstWeekContainsDate??o?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,l=o?.weekStartsOn??o?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0;if(!e)return t?n():R(r,o?.in);let u={firstWeekContainsDate:a,weekStartsOn:l,locale:i},c=[new Ji(o?.in,r)],d=e.match(f0).map(y=>{let p=y[0];if(p in hs){let b=hs[p];return b(y,i.formatLong)}return y}).join("").match(d0),f=[];for(let y of d){!o?.useAdditionalWeekYearTokens&&Wi(y)&&ps(y,e,t),!o?.useAdditionalDayOfYearTokens&&Vi(y)&&ps(y,e,t);let p=y[0],b=nh[p];if(b){let{incompatibleTokens:_}=b;if(Array.isArray(_)){let L=f.find(x=>_.includes(x.token)||x.token===p);if(L)throw new RangeError(`The format string mustn't contain \`${L.fullToken}\` and \`${y}\` at the same time`)}else if(b.incompatibleTokens==="*"&&f.length>0)throw new RangeError(`The format string mustn't contain \`${y}\` and any other token at the same time`);f.push({token:p,fullToken:y});let v=b.run(t,y,i.match,u);if(!v)return n();c.push(v.setter),t=v.rest}else{if(p.match(g0))throw new RangeError("Format string contains an unescaped latin alphabet character `"+p+"`");if(y==="''"?y="'":p==="'"&&(y=y0(y)),t.indexOf(y)===0)t=t.slice(y.length);else return n()}}if(t.length>0&&p0.test(t))return n();let m=c.map(y=>y.priority).sort((y,p)=>p-y).filter((y,p,b)=>b.indexOf(y)===p).map(y=>c.filter(p=>p.priority===y).sort((p,b)=>b.subPriority-p.subPriority)).map(y=>y[0]),h=R(r,o?.in);if(isNaN(+h))return n();let g={};for(let y of m){if(!y.validate(h,u))return n();let p=y.set(h,g,u);Array.isArray(p)?(h=p[0],Object.assign(g,p[1])):h=p}return h}function y0(t){return t.match(m0)[1].replace(h0,"'")}function sh(t,e){let r=R(t,e?.in);return r.setSeconds(0,0),r}import{z as w}from"zod";import{z as Au}from"zod";var ih=["pos","kds","kiosk"],Tj=Au.enum(ih),b0=[...ih,"restaurant_site","developer_dashboard","zorgo_site","backend"],ah=Au.enum(b0),_0=["gateway","main_service","agent_service","background_workers"],Cj=Au.enum(_0);var Ru=w.object({settle_ms:w.number().nullable().default(null),interaction_wait_ms:w.number().nullable().default(null),capture_ms:w.number().nullable().default(null),print_ms:w.number().nullable().default(null)}),w0=w.object({global:w.object({font_family:w.enum(["sans-serif","serif","monospace"]).default("sans-serif"),base_font_size:w.enum(["small","medium","large"]).default("large"),text_alignment:w.enum(["left","center"]).default("left")}).prefault({}),header:w.object({show_logo:w.boolean().default(!0),show_customer_name:w.boolean().default(!0),show_time_info:w.boolean().default(!0),show_order_number:w.boolean().default(!0),order_number_style:w.enum(["bold","normal, small"]).default("bold")}).prefault({}),body:w.object({show_modifiers:w.boolean().default(!0),show_item_notes:w.boolean().default(!0),show_prices:w.boolean().default(!0),compact_view:w.boolean().default(!0)}).prefault({}),footer:w.object({show_tax_breakdown:w.boolean().default(!0),show_subtotal:w.boolean().default(!0),show_tax:w.boolean().default(!0),show_service_fee:w.boolean().default(!1),show_tip:w.boolean().default(!0),show_suggested_tips:w.boolean().default(!1),show_customer_signature:w.boolean().default(!1),show_grand_total:w.boolean().default(!0),total_line_label:w.string().max(24).default("Total"),suggested_tip_percentages:w.array(w.number().min(0).max(1)).default([.2,.15,.1]),custom_message:w.string().max(200).optional().default(""),customer_signature_agreement:w.string().max(300).default("I agree to pay the above amount per the cardholder and/or merchant agreement")}).prefault({})}),v0=w.enum(["kitchen","merchant","customer"]),Oj=w.object({id:w.uuid().optional(),franchise_id:w.number().default(-1),type:v0.default("kitchen"),config:w0.prefault({})}),lh=w.string().regex(/^[1-9][0-9]?\/[1-9][0-9]?$/,'portion must look like "1/2"').refine(t=>{let[e,r]=t.split("/").map(Number);return e<=r},"portion index cannot exceed its divisions"),S0=w.enum(["radial","grid","linear","count"]),Aj=w.object({id:w.number(),franchise_id:w.number(),geometry:S0,name:w.string().min(1),min_divisions:w.number().int().min(1).default(1),max_divisions:w.number().int().min(1).max(12)}).check(t=>{let e=t.value;e.max_divisions<e.min_divisions&&t.issues.push({code:"custom",input:e,path:["max_divisions"],message:"max_divisions must be >= min_divisions"})}),x0=w.object({type:w.enum(["item","component"]),id:w.number(),quantity:w.number(),upcharge:w.number(),serving_price:w.number().optional(),name:w.string(),portion:lh.nullish()}),k0=w.object({rule_id:w.number(),group_name:w.string(),selections:w.array(x0)}),T0=w.object({id:w.number(),servings_per_item:w.number().nullish(),is_base:w.boolean().nullish(),price_per_serving:w.number().nullish(),franchise_id:w.number().nullish(),component_type_id:w.number(),serving_weight:w.number().nullish(),name:w.string().default(""),item_id:w.number().nullish(),quantity_servings:w.number(),upcharge:w.number().nullish(),rule_id:w.number().nullish(),portion:lh.nullish()}),C0=w.object({item_id:w.number(),name:w.string(),quantity:w.number(),price:w.number(),order_item_id:w.number().nullish(),status:w.enum(["removed","modified"]).nullish(),category_id:w.number().nullish(),category_name:w.string().nullish(),is_catering:w.boolean().nullish(),per_person:w.boolean().nullish(),components:w.array(T0).nullish(),selections:w.array(k0).nullish(),comments:w.string().nullish()}),E0=w.object({customer_id:w.number().optional(),phone:w.string(),first_name:w.string(),last_name:w.string().nullish(),email:w.string().nullish(),allow_marketing:w.boolean().default(!1)}),Rj=w.object({first_name:w.string().min(2,"Enter at least 2 characters"),last_name:w.string().min(2,"Enter at least 2 characters"),phone:w.string().regex(/^\d{10}$/,"Enter a 10-digit phone number"),email:w.email().optional().or(w.literal("")),allow_marketing:w.boolean().optional().default(!1)});var P0=w.object({id:w.number(),order_id:w.number().nullish(),total:w.number(),subtotal:w.number(),tax:w.number(),tip:w.number().nullish(),discount:w.number().nullish(),service_fee:w.number().nullish(),charge_id:w.string().nullish(),charge_status:w.number().nullish(),created_at:w.coerce.date().nullish(),setup_intent_id:w.string().nullish(),payment_method_id:w.string().nullish(),stripe_customer_id:w.string().nullish()}),Ij=w.object({order_id:w.number(),customer:E0,location_id:w.number(),method_id:w.number().nullish(),type_id:w.number().nullish(),time_placed:w.coerce.date(),time_requested:w.coerce.date().nullish(),items:w.array(C0),order_status:w.number().nullish(),order_code:w.string().optional(),promo_code:w.string().nullish(),charges:w.array(P0),subtotal:w.number().nullish(),delivery_address:w.string().optional()}),O0=w.enum(["guest","requested_access","action_required","pending_approval","healthy"]).default("guest"),Dj=w.object({id:w.string(),user_id:w.string(),franchise_name:w.string(),number_of_locations:w.number(),phone:w.string(),email:w.string(),status:O0,metadata:w.record(w.string(),w.unknown()).default({}),created_at:w.coerce.date()}),Lj=w.object({location_id:w.number(),table_number:w.number(),label:w.string().nullish(),capacity:w.number(),shape:w.enum(["rect","round"]),reservable:w.boolean(),x:w.number(),y:w.number(),w:w.number(),h:w.number()}),Nj=w.object({salesCount:w.number().int().nonnegative(),grossRevenue:w.number().int().nonnegative(),totalRevenue:w.number().int().nonnegative(),totalRefunds:w.number().int().nonnegative(),totalDiscounts:w.number().int().nonnegative(),totalTips:w.number().int().nonnegative(),netRevenue:w.number().int()}),jj=w.object({requireTableForDineIn:w.boolean().default(!1)});var gs=()=>typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});function ch(t){let e=(t||"").replace(/\D/g,"");return e.length===11?`+${e}`:`+1${e}`}var _r=typeof globalThis.document<"u"&&globalThis.navigator?.product!=="ReactNative",uh={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function wr(){let t=globalThis;if(typeof t.window<"u"&&typeof t.window.localStorage<"u")return t.window.localStorage;if(t?.navigator?.product==="ReactNative"||typeof t?.document>"u"&&typeof process>"u")try{return(Cu(),Kc(Tu)).default}catch{return uh}return uh}function Aa(t){return`(${t.join(",")})`}var Iu=(n=>(n.Website="website",n.Kiosk="kiosk",n.Pos="pos",n.KitchenDisplay="kitchen_display",n))(Iu||{});var Vj={website:"Website",kiosk:"Kiosk",pos:"POS"},Mt=class extends Error{constructor(e){super(e),this.name="VisibilityConditionError"}};function dh(t){let e=t?.date??new Date,r=["su","m","t","w","th","f","sa"],o=e.getHours().toString().padStart(2,"0"),n=e.getMinutes().toString().padStart(2,"0");return{dayOfWeek:r[e.getDay()]??"m",currentTime:`${o}:${n}`,platform:t?.platform??"website"}}function A0(t){if(t.version!==1)throw new Mt("Unsupported visibility condition version.");mh(t.root)}function fh(t,e){return A0(t),Du(t.root,e)}function mh(t){switch(t.type){case"group":if(t.children.length===0)throw new Mt("Condition groups cannot be empty.");t.children.forEach(mh);return;case"constant":return;case"rule":R0(t);return;default:throw new Mt("Unknown visibility condition node.")}}function R0(t){if(t.variable==="dayOfWeek"){if(!Array.isArray(t.value)||t.value.length===0)throw new Mt("Day-of-week rules require at least one day.");return}if(t.variable==="platform"){if((Array.isArray(t.value)?t.value:[t.value]).length===0)throw new Mt("Platform rules require at least one platform.");return}if(t.variable==="currentTime"){if(t.operator==="between"){if(typeof t.value!="object"||t.value==null||!("start"in t.value)||!("end"in t.value))throw new Mt("Between rules require a start and end time.");Ia(t.value.start),Ia(t.value.end);return}if(typeof t.value!="string")throw new Mt("Time rules require a single time value.");Ia(t.value)}}function Du(t,e){return t.type==="group"?t.operator==="and"?t.children.every(r=>Du(r,e)):t.children.some(r=>Du(r,e)):t.type==="constant"?t.value:I0(t,e)}function I0(t,e){switch(t.variable){case"dayOfWeek":{let r=t.value;return t.operator==="is_any_of"?r.includes(e.dayOfWeek):!r.includes(e.dayOfWeek)}case"platform":{let r=Array.isArray(t.value)?t.value:[t.value];switch(t.operator){case"is":return e.platform===r[0];case"is_not":return e.platform!==r[0];case"is_any_of":return r.includes(e.platform)}}case"currentTime":{let r=Ra(e.currentTime);if(t.operator==="between"){let n=t.value,s=Ra(n.start),i=Ra(n.end);return r>=s&&r<=i}let o=Ra(t.value);switch(t.operator){case"before":return r<o;case"after":return r>o;case"on_or_before":return r<=o;case"on_or_after":return r>=o;default:return!1}}default:return!1}}function Ra(t){Ia(t);let e=t.split(":"),r=Number(e[0]),o=Number(e[1]);return r*60+o}function Ia(t){if(!/^\d{2}:\d{2}$/.test(t))throw new Mt(`Invalid time "${t}". Use HH:mm format.`)}var vr={ascending:!0,nullsFirst:!1},hh=Number.MAX_SAFE_INTEGER;function ju(t,e){let r=(t.sort_index??hh)-(e.sort_index??hh);return r!==0?r:t.name.localeCompare(e.name)}async function ph(t,e,r=bh(),o=!1){let n=await N0(t,e,r.categoryIds);if(n.length===0)return Nu([],[],[],[],[]);let s=await j0(t,e,r.baseItemIds,n);if(s.length===0)return Nu([],[],n,[],[]);let i=await U0(t,s,r.itemIds),a=await F0(t,i,o),l=await $0(t,s,n,i,o);return Nu(i,s,n,a,l)}function gh(t,e){let r=new Map,o=(i,a)=>a.promotion_type_id===1?Math.max(0,Math.floor(i*(1-a.discount_value/100))):a.promotion_type_id===2?Math.max(0,i-a.discount_value):i,n=t.items.map(i=>{let l=e.find(c=>{if(!c.is_active||c.id==null||!c.discount_target_ids?.length||!c.min_purchase_quantity)return!1;let d=c.discount_target_ids;return c.discount_target_type==="category"&&d.includes(i.category_id)||c.discount_target_type==="item"&&d.includes(i.base_item_id)})?.id,u=i.variants.map(c=>{let d,f=c.price;for(let m of e){if(!m.is_active||m.id==null||!m.discount_target_ids?.length||m.min_purchase_amount||m.min_purchase_quantity)continue;let h=m.discount_target_ids;if(!(m.discount_target_type==="category"&&h.includes(i.category_id)||m.discount_target_type==="item"&&h.includes(i.base_item_id)||m.discount_target_type==="item_variant"&&h.includes(c.item_id)))continue;let y=o(c.price,m);y<f&&(d=m,f=y)}return!d||f>=c.price?c:(l??=d.id,d.discount_target_type==="category"&&r.set(i.category_id,d.id),{...c,active_promo_id:d.id,display_price:f})});return{...i,variants:u,active_promo_id:l}}),s=t.categories.map(i=>{let{active_promo_id:a,...l}=i,u=r.get(l.category_id);return u==null?l:{...l,active_promo_id:u}});return{...t,items:n,categories:s}}async function yh(t,e,r,o){let n=await D0(t,e),s=await L0(t,e,o);if(s.length===0)return bh();let i=Lu(s,p=>p.category_id),a=Lu(s,p=>p.base_item_id),l=Lu(s,p=>p.item_id),u=new Map(n.baseItems.map(p=>[p.base_item_id,p])),c=new Map(n.items.map(p=>[p.item_id,p])),d=p=>i.get(p)!=="exclude",f=p=>{let b=a.get(p);if(b==="include")return!0;if(b==="exclude")return!1;let _=u.get(p)?.category_id;return _==null||d(_)},m=p=>{let b=l.get(p);if(b==="include")return!0;if(b==="exclude")return!1;let _=c.get(p);return _?.base_item_id==null?!0:f(_.base_item_id)},h=new Set(n.items.filter(p=>m(p.item_id)).map(p=>p.item_id)),g=new Set(n.baseItems.filter(p=>f(p.base_item_id)).map(p=>p.base_item_id));for(let p of n.items)h.has(p.item_id)&&p.base_item_id!=null&&g.add(p.base_item_id);let y=new Set(n.categories.filter(p=>d(p.category_id)).map(p=>p.category_id));for(let p of n.baseItems)g.has(p.base_item_id)&&y.add(p.category_id);return{categoryIds:n.categories.map(p=>p.category_id).filter(p=>!y.has(p)),baseItemIds:n.baseItems.map(p=>p.base_item_id).filter(p=>!g.has(p)),itemIds:n.items.map(p=>p.item_id).filter(p=>!h.has(p))}}function bh(){return{categoryIds:[],baseItemIds:[],itemIds:[]}}async function D0(t,e){let{data:r,error:o}=await t.from("categories").select("category_id").eq("franchise_id",e);if(o)throw o;let{data:n,error:s}=await t.from("base_items").select("base_item_id, category_id").eq("franchise_id",e);if(s)throw s;let i=(n??[]).map(u=>u.base_item_id),{data:a,error:l}=i.length>0?await t.from("items").select("item_id, base_item_id").in("base_item_id",i):{data:[],error:null};if(l)throw l;return{categories:r??[],baseItems:n??[],items:a??[]}}async function L0(t,e,r){let{data:o,error:n}=await t.from("visibility_condition_group_assignments").select("*, visibility_condition_groups (*)").eq("visibility_condition_groups.franchise_id",e).eq("visibility_condition_groups.platform",r);if(n||!o)return[];let s=dh({platform:r});return o.filter(i=>{let a=i.visibility_condition_groups;if(!a?.condition||a.platform!==s.platform)return!1;try{return fh(a.condition,s)}catch{return!1}})}function Lu(t,e){let r=new Map;for(let o of t){let n=e(o);n!=null&&r.set(n,[...r.get(n)??[],o.effect])}return new Map(Array.from(r.entries()).map(([o,n])=>[o,n.includes("exclude")?"exclude":"include"]))}async function N0(t,e,r){let o=t.from("categories").select("*").eq("franchise_id",e).order("sort_index",vr).order("name",vr);r&&r.length>0&&(o=o.not("category_id","in",Aa(r)));let{data:n,error:s}=await o;if(s)throw s;return n??[]}async function j0(t,e,r,o){if(o&&o.length===0)return[];let n=t.from("base_items").select("*").eq("franchise_id",e).order("sort_index",vr).order("name",vr);r&&r.length>0&&(n=n.not("base_item_id","in",Aa(r))),o&&(n=n.in("category_id",o.map(u=>u.category_id)));let{data:s,error:i}=await n;if(i)throw i;if(!s||s.length===0)return[];let{data:a,error:l}=await t.from("base_item_images").select("*").in("base_item_id",s.map(u=>u.base_item_id)).order("sort_index",{ascending:!0}).order("image_id",{ascending:!0});if(l)throw l;return M0(s,a??[])}function M0(t,e){let r=new Map;for(let o of e){let n=r.get(o.base_item_id);n?n.push(o):r.set(o.base_item_id,[o])}return t.map(o=>({...o,images:r.get(o.base_item_id)??[]}))}async function U0(t,e,r){if(e&&e.length===0)return[];let o=t.from("items").select("*, portion_scheme:portion_schemes(*)").in("base_item_id",e.map(i=>i.base_item_id)).order("sort_index",vr).order("price",vr);r&&r.length>0&&(o=o.not("item_id","in",Aa(r)));let{data:n,error:s}=await o;if(s)throw s;return n??[]}async function F0(t,e,r=!1){let o=e.length>0&&typeof e[0]=="number"?e:e.map(i=>i.item_id);if(o.length===0)return[];let n=r?"components(*), item_id, servings_per_item, behavior_id, component_quantity_behaviors(headcount_threshold, starting_amount, step_size, step_interval, maximum)":"components(*), item_id, servings_per_item",{data:s}=await t.from("item_components").select(n).in("item_id",o).throwOnError();return s.map(i=>({servings_per_item:i.servings_per_item,is_base:i.components?.is_base,serving_weight:i.components?.serving_weight,component_type_id:i.components?.component_type_id,id:i.components?.id,name:i.components?.name,item_id:i.item_id,...r&&{behavior:i.component_quantity_behaviors??void 0}}))}function _h(t){return[...(t.components??[]).map(e=>({key:`component:${e.component_id}`,id:e.component_id,type:"component",name:e.name,basePrice:e.upcharge_price||0,description:e.description,sort_index:e.sort_index??null})),...(t.items??[]).map(e=>({key:`item:${e.item_id}`,id:e.item_id,type:"item",name:e.name,basePrice:e.upcharge_price||0,description:e.description,sort_index:e.sort_index??null}))].sort(ju)}async function $0(t,e,r,o,n=!1,s){let i=o?.map(g=>g.item_id)??[],a=e?.map(g=>g.base_item_id)??[],l=r?.map(g=>g.category_id)??[];if(i.length===0&&a.length===0&&l.length===0&&!s?.length)return[];let u=[`item_id.in.(${i.length>0?i.join(","):-1})`,`base_item_id.in.(${a.length>0?a.join(","):-1})`,`category_id.in.(${l.length>0?l.join(","):-1})`,...s?.length?[`rule_id.in.(${s.join(",")})`]:[]].join(","),c=n?"component_quantity_behaviors(headcount_threshold, starting_amount, step_size, step_interval, maximum)":null,d=["component_id, upcharge_price, sort_index, components(name, description, serving_weight)",c].filter(Boolean).join(", "),f=["item_id, upcharge_price, sort_index, items(item_id, name, description)",c].filter(Boolean).join(", "),{data:m,error:h}=await t.from("item_rules").select(`
|
|
140
|
+
`};var gm=null;var ku=(t,e)=>{if(!gm)return fetch(t,e);let r=new Headers(e?.headers);return r.set("Authorization",`Bearer ${gm}`),fetch(t,{...e,headers:r})};var Ou=globalThis?.navigator?.product==="ReactNative",Rm=typeof process<"u"&&process.versions?.node,yv=!Ou&&!Rm&&typeof globalThis?.document<"u";function Am(){if(!Rm&&Ou)try{return(Pu(),Yc(Eu)).default}catch{return}}function bv(){return yv?pm(Su,xu,{global:{fetch:ku}}):of(Su,xu,{auth:{autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!Ou,...Am()?{storage:Am()}:{},lock:Ul},global:{fetch:ku}})}var M=bv();import{immer as jS}from"zustand/middleware/immer";import{createJSONStorage as MS,devtools as US,persist as FS}from"zustand/middleware";var _v=Math.pow(10,8)*24*60*60*1e3,PI=-_v,Ni=6048e5,Im=864e5,ji=6e4,Mi=36e5,Dm=1e3;var wv=3600;var Lm=wv*24,OI=Lm*7,vv=Lm*365.2425,Sv=vv/12,AI=Sv*3,Au=Symbol.for("constructDateFrom");function V(t,e){return typeof t=="function"?t(e):t&&typeof t=="object"&&Au in t?t[Au](e):t instanceof Date?new t.constructor(e):new Date(e)}function R(t,e){return V(e||t,t)}function Ui(t,e,r){let o=R(t,r?.in);return isNaN(e)?V(r?.in||t,NaN):(e&&o.setDate(o.getDate()+e),o)}function Nm(t,e,r){return V(r?.in||t,+R(t)+e)}function Vo(t,e,r){return Nm(t,e*Mi,r)}var xv={};function lt(){return xv}function Ve(t,e){let r=lt(),o=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=R(t,e?.in),s=n.getDay(),i=(s<o?7:0)+s-o;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function St(t,e){return Ve(t,{...e,weekStartsOn:1})}function Fi(t,e){let r=R(t,e?.in),o=r.getFullYear(),n=V(r,0);n.setFullYear(o+1,0,4),n.setHours(0,0,0,0);let s=St(n),i=V(r,0);i.setFullYear(o,0,4),i.setHours(0,0,0,0);let a=St(i);return r.getTime()>=s.getTime()?o+1:r.getTime()>=a.getTime()?o:o-1}function eo(t){let e=R(t),r=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return r.setUTCFullYear(e.getFullYear()),+t-+r}function jm(t,...e){let r=V.bind(null,t||e.find(o=>typeof o=="object"));return e.map(r)}function xt(t,e){let r=R(t,e?.in);return r.setHours(0,0,0,0),r}function Mm(t,e,r){let[o,n]=jm(r?.in,t,e),s=xt(o),i=xt(n),a=+s-eo(s),l=+i-eo(i);return Math.round((a-l)/Im)}function Um(t,e){let r=Fi(t,e),o=V(e?.in||t,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),St(o)}function Fm(t,e,r){let o=R(t,r?.in);return o.setTime(o.getTime()+e*ji),o}function $m(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function to(t){return!(!$m(t)&&typeof t!="number"||isNaN(+R(t)))}function Bm(t,e){return+R(t)-+R(e)}function qm(t,e){let r=R(t,e?.in);return r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0),r}var kv={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Vm=(t,e,r)=>{let o,n=kv[t];return typeof n=="string"?o=n:e===1?o=n.one:o=n.other.replace("{{count}}",e.toString()),r?.addSuffix?r.comparison&&r.comparison>0?"in "+o:o+" ago":o};function $i(t){return(e={})=>{let r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}var Tv={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Cv={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Ev={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Wm={date:$i({formats:Tv,defaultWidth:"full"}),time:$i({formats:Cv,defaultWidth:"full"}),dateTime:$i({formats:Ev,defaultWidth:"full"})};var Pv={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Hm=(t,e,r,o)=>Pv[t];function Wo(t){return(e,r)=>{let o=r?.context?String(r.context):"standalone",n;if(o==="formatting"&&t.formattingValues){let i=t.defaultFormattingWidth||t.defaultWidth,a=r?.width?String(r.width):i;n=t.formattingValues[a]||t.formattingValues[i]}else{let i=t.defaultWidth,a=r?.width?String(r.width):t.defaultWidth;n=t.values[a]||t.values[i]}let s=t.argumentCallback?t.argumentCallback(e):e;return n[s]}}var Ov={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Av={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Rv={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Iv={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Dv={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Lv={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},Nv=(t,e)=>{let r=Number(t),o=r%100;if(o>20||o<10)switch(o%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},zm={ordinalNumber:Nv,era:Wo({values:Ov,defaultWidth:"wide"}),quarter:Wo({values:Av,defaultWidth:"wide",argumentCallback:t=>t-1}),month:Wo({values:Rv,defaultWidth:"wide"}),day:Wo({values:Iv,defaultWidth:"wide"}),dayPeriod:Wo({values:Dv,defaultWidth:"wide",formattingValues:Lv,defaultFormattingWidth:"wide"})};function Ho(t){return(e,r={})=>{let o=r.width,n=o&&t.matchPatterns[o]||t.matchPatterns[t.defaultMatchWidth],s=e.match(n);if(!s)return null;let i=s[0],a=o&&t.parsePatterns[o]||t.parsePatterns[t.defaultParseWidth],l=Array.isArray(a)?Mv(a,d=>d.test(i)):jv(a,d=>d.test(i)),u;u=t.valueCallback?t.valueCallback(l):l,u=r.valueCallback?r.valueCallback(u):u;let c=e.slice(i.length);return{value:u,rest:c}}}function jv(t,e){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function Mv(t,e){for(let r=0;r<t.length;r++)if(e(t[r]))return r}function Gm(t){return(e,r={})=>{let o=e.match(t.matchPattern);if(!o)return null;let n=o[0],s=e.match(t.parsePattern);if(!s)return null;let i=t.valueCallback?t.valueCallback(s[0]):s[0];i=r.valueCallback?r.valueCallback(i):i;let a=e.slice(n.length);return{value:i,rest:a}}}var Uv=/^(\d+)(th|st|nd|rd)?/i,Fv=/\d+/i,$v={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Bv={any:[/^b/i,/^(a|c)/i]},qv={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Vv={any:[/1/i,/2/i,/3/i,/4/i]},Wv={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},Hv={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},zv={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Gv={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},Kv={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Jv={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},Km={ordinalNumber:Gm({matchPattern:Uv,parsePattern:Fv,valueCallback:t=>parseInt(t,10)}),era:Ho({matchPatterns:$v,defaultMatchWidth:"wide",parsePatterns:Bv,defaultParseWidth:"any"}),quarter:Ho({matchPatterns:qv,defaultMatchWidth:"wide",parsePatterns:Vv,defaultParseWidth:"any",valueCallback:t=>t+1}),month:Ho({matchPatterns:Wv,defaultMatchWidth:"wide",parsePatterns:Hv,defaultParseWidth:"any"}),day:Ho({matchPatterns:zv,defaultMatchWidth:"wide",parsePatterns:Gv,defaultParseWidth:"any"}),dayPeriod:Ho({matchPatterns:Kv,defaultMatchWidth:"any",parsePatterns:Jv,defaultParseWidth:"any"})};var ms={code:"en-US",formatDistance:Vm,formatLong:Wm,formatRelative:Hm,localize:zm,match:Km,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Jm(t,e){let r=R(t,e?.in);return Mm(r,qm(r))+1}function Bi(t,e){let r=R(t,e?.in),o=+St(r)-+Um(r);return Math.round(o/Ni)+1}function zo(t,e){let r=R(t,e?.in),o=r.getFullYear(),n=lt(),s=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=V(e?.in||t,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=Ve(i,e),l=V(e?.in||t,0);l.setFullYear(o,0,s),l.setHours(0,0,0,0);let u=Ve(l,e);return+r>=+a?o+1:+r>=+u?o:o-1}function Ym(t,e){let r=lt(),o=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=zo(t,e),s=V(e?.in||t,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),Ve(s,e)}function qi(t,e){let r=R(t,e?.in),o=+Ve(r,e)-+Ym(r,e);return Math.round(o/Ni)+1}function J(t,e){let r=t<0?"-":"",o=Math.abs(t).toString().padStart(e,"0");return r+o}var Qt={y(t,e){let r=t.getFullYear(),o=r>0?r:1-r;return J(e==="yy"?o%100:o,e.length)},M(t,e){let r=t.getMonth();return e==="M"?String(r+1):J(r+1,2)},d(t,e){return J(t.getDate(),e.length)},a(t,e){let r=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];default:return r==="am"?"a.m.":"p.m."}},h(t,e){return J(t.getHours()%12||12,e.length)},H(t,e){return J(t.getHours(),e.length)},m(t,e){return J(t.getMinutes(),e.length)},s(t,e){return J(t.getSeconds(),e.length)},S(t,e){let r=e.length,o=t.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return J(n,e.length)}};var Go={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ru={G:function(t,e,r){let o=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return r.era(o,{width:"abbreviated"});case"GGGGG":return r.era(o,{width:"narrow"});default:return r.era(o,{width:"wide"})}},y:function(t,e,r){if(e==="yo"){let o=t.getFullYear(),n=o>0?o:1-o;return r.ordinalNumber(n,{unit:"year"})}return Qt.y(t,e)},Y:function(t,e,r,o){let n=zo(t,o),s=n>0?n:1-n;if(e==="YY"){let i=s%100;return J(i,2)}return e==="Yo"?r.ordinalNumber(s,{unit:"year"}):J(s,e.length)},R:function(t,e){let r=Fi(t);return J(r,e.length)},u:function(t,e){let r=t.getFullYear();return J(r,e.length)},Q:function(t,e,r){let o=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(o);case"QQ":return J(o,2);case"Qo":return r.ordinalNumber(o,{unit:"quarter"});case"QQQ":return r.quarter(o,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(o,{width:"narrow",context:"formatting"});default:return r.quarter(o,{width:"wide",context:"formatting"})}},q:function(t,e,r){let o=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(o);case"qq":return J(o,2);case"qo":return r.ordinalNumber(o,{unit:"quarter"});case"qqq":return r.quarter(o,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(o,{width:"narrow",context:"standalone"});default:return r.quarter(o,{width:"wide",context:"standalone"})}},M:function(t,e,r){let o=t.getMonth();switch(e){case"M":case"MM":return Qt.M(t,e);case"Mo":return r.ordinalNumber(o+1,{unit:"month"});case"MMM":return r.month(o,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(o,{width:"narrow",context:"formatting"});default:return r.month(o,{width:"wide",context:"formatting"})}},L:function(t,e,r){let o=t.getMonth();switch(e){case"L":return String(o+1);case"LL":return J(o+1,2);case"Lo":return r.ordinalNumber(o+1,{unit:"month"});case"LLL":return r.month(o,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(o,{width:"narrow",context:"standalone"});default:return r.month(o,{width:"wide",context:"standalone"})}},w:function(t,e,r,o){let n=qi(t,o);return e==="wo"?r.ordinalNumber(n,{unit:"week"}):J(n,e.length)},I:function(t,e,r){let o=Bi(t);return e==="Io"?r.ordinalNumber(o,{unit:"week"}):J(o,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):Qt.d(t,e)},D:function(t,e,r){let o=Jm(t);return e==="Do"?r.ordinalNumber(o,{unit:"dayOfYear"}):J(o,e.length)},E:function(t,e,r){let o=t.getDay();switch(e){case"E":case"EE":case"EEE":return r.day(o,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(o,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(o,{width:"short",context:"formatting"});default:return r.day(o,{width:"wide",context:"formatting"})}},e:function(t,e,r,o){let n=t.getDay(),s=(n-o.weekStartsOn+8)%7||7;switch(e){case"e":return String(s);case"ee":return J(s,2);case"eo":return r.ordinalNumber(s,{unit:"day"});case"eee":return r.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(n,{width:"short",context:"formatting"});default:return r.day(n,{width:"wide",context:"formatting"})}},c:function(t,e,r,o){let n=t.getDay(),s=(n-o.weekStartsOn+8)%7||7;switch(e){case"c":return String(s);case"cc":return J(s,e.length);case"co":return r.ordinalNumber(s,{unit:"day"});case"ccc":return r.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(n,{width:"narrow",context:"standalone"});case"cccccc":return r.day(n,{width:"short",context:"standalone"});default:return r.day(n,{width:"wide",context:"standalone"})}},i:function(t,e,r){let o=t.getDay(),n=o===0?7:o;switch(e){case"i":return String(n);case"ii":return J(n,e.length);case"io":return r.ordinalNumber(n,{unit:"day"});case"iii":return r.day(o,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(o,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(o,{width:"short",context:"formatting"});default:return r.day(o,{width:"wide",context:"formatting"})}},a:function(t,e,r){let n=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(t,e,r){let o=t.getHours(),n;switch(o===12?n=Go.noon:o===0?n=Go.midnight:n=o/12>=1?"pm":"am",e){case"b":case"bb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(t,e,r){let o=t.getHours(),n;switch(o>=17?n=Go.evening:o>=12?n=Go.afternoon:o>=4?n=Go.morning:n=Go.night,e){case"B":case"BB":case"BBB":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(t,e,r){if(e==="ho"){let o=t.getHours()%12;return o===0&&(o=12),r.ordinalNumber(o,{unit:"hour"})}return Qt.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):Qt.H(t,e)},K:function(t,e,r){let o=t.getHours()%12;return e==="Ko"?r.ordinalNumber(o,{unit:"hour"}):J(o,e.length)},k:function(t,e,r){let o=t.getHours();return o===0&&(o=24),e==="ko"?r.ordinalNumber(o,{unit:"hour"}):J(o,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):Qt.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):Qt.s(t,e)},S:function(t,e){return Qt.S(t,e)},X:function(t,e,r){let o=t.getTimezoneOffset();if(o===0)return"Z";switch(e){case"X":return Qm(o);case"XXXX":case"XX":return ro(o);default:return ro(o,":")}},x:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"x":return Qm(o);case"xxxx":case"xx":return ro(o);default:return ro(o,":")}},O:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Xm(o,":");default:return"GMT"+ro(o,":")}},z:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Xm(o,":");default:return"GMT"+ro(o,":")}},t:function(t,e,r){let o=Math.trunc(+t/1e3);return J(o,e.length)},T:function(t,e,r){return J(+t,e.length)}};function Xm(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Math.trunc(o/60),s=o%60;return s===0?r+String(n):r+String(n)+e+J(s,2)}function Qm(t,e){return t%60===0?(t>0?"-":"+")+J(Math.abs(t)/60,2):ro(t,e)}function ro(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=J(Math.trunc(o/60),2),s=J(o%60,2);return r+n+e+s}var Zm=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});default:return e.date({width:"full"})}},eh=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});default:return e.time({width:"full"})}},Yv=(t,e)=>{let r=t.match(/(P+)(p+)?/)||[],o=r[1],n=r[2];if(!n)return Zm(t,e);let s;switch(o){case"P":s=e.dateTime({width:"short"});break;case"PP":s=e.dateTime({width:"medium"});break;case"PPP":s=e.dateTime({width:"long"});break;default:s=e.dateTime({width:"full"});break}return s.replace("{{date}}",Zm(o,e)).replace("{{time}}",eh(n,e))},hs={p:eh,P:Yv};var Xv=/^D+$/,Qv=/^Y+$/,Zv=["D","DD","YY","YYYY"];function Vi(t){return Xv.test(t)}function Wi(t){return Qv.test(t)}function ps(t,e,r){let o=e0(t,e,r);if(console.warn(o),Zv.includes(t))throw new RangeError(o)}function e0(t,e,r){let o=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${o} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var t0=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,r0=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,o0=/^'([^]*?)'?$/,n0=/''/g,s0=/[a-zA-Z]/;function Ue(t,e,r){let o=lt(),n=r?.locale??o.locale??ms,s=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??o.firstWeekContainsDate??o.locale?.options?.firstWeekContainsDate??1,i=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,a=R(t,r?.in);if(!to(a))throw new RangeError("Invalid time value");let l=e.match(r0).map(c=>{let d=c[0];if(d==="p"||d==="P"){let f=hs[d];return f(c,n.formatLong)}return c}).join("").match(t0).map(c=>{if(c==="''")return{isToken:!1,value:"'"};let d=c[0];if(d==="'")return{isToken:!1,value:i0(c)};if(Ru[d])return{isToken:!0,value:c};if(d.match(s0))throw new RangeError("Format string contains an unescaped latin alphabet character `"+d+"`");return{isToken:!1,value:c}});n.localize.preprocessor&&(l=n.localize.preprocessor(a,l));let u={firstWeekContainsDate:s,weekStartsOn:i,locale:n};return l.map(c=>{if(!c.isToken)return c.value;let d=c.value;(!r?.useAdditionalWeekYearTokens&&Wi(d)||!r?.useAdditionalDayOfYearTokens&&Vi(d))&&ps(d,e,String(t));let f=Ru[d[0]];return f(a,d,n.localize,u)}).join("")}function i0(t){let e=t.match(o0);return e?e[1].replace(n0,"'"):t}function Hi(t,e){return R(t,e?.in).getDay()}function zi(){return Object.assign({},lt())}function th(t,e){let r=R(t,e?.in).getDay();return r===0?7:r}function jt(t,e){return+R(t)>+R(e)}function We(t,e){return+R(t)<+R(e)}function rh(t,e){let r=a0(e)?new e(0):V(e,0);return r.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),r.setHours(t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()),r}function a0(t){return typeof t=="function"&&t.prototype?.constructor===t}var l0=10,Gi=class{subPriority=0;validate(e,r){return!0}},Ki=class extends Gi{constructor(e,r,o,n,s){super(),this.value=e,this.validateValue=r,this.setValue=o,this.priority=n,s&&(this.subPriority=s)}validate(e,r){return this.validateValue(e,this.value,r)}set(e,r,o){return this.setValue(e,r,this.value,o)}},Ji=class extends Gi{priority=l0;subPriority=-1;constructor(e,r){super(),this.context=e||(o=>V(r,o))}set(e,r){return r.timestampIsSet?e:V(e,rh(e,this.context))}};var C=class{run(e,r,o,n){let s=this.parse(e,r,o,n);return s?{setter:new Ki(s.value,this.validate,this.set,this.priority,this.subPriority),rest:s.rest}:null}validate(e,r,o){return!0}};var Yi=class extends C{priority=140;parse(e,r,o){switch(r){case"G":case"GG":case"GGG":return o.era(e,{width:"abbreviated"})||o.era(e,{width:"narrow"});case"GGGGG":return o.era(e,{width:"narrow"});default:return o.era(e,{width:"wide"})||o.era(e,{width:"abbreviated"})||o.era(e,{width:"narrow"})}}set(e,r,o){return r.era=o,e.setFullYear(o,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["R","u","t","T"]};var z={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},ut={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function Y(t,e){return t&&{value:e(t.value),rest:t.rest}}function W(t,e){let r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function ct(t,e){let r=e.match(t);if(!r)return null;if(r[0]==="Z")return{value:0,rest:e.slice(1)};let o=r[1]==="+"?1:-1,n=r[2]?parseInt(r[2],10):0,s=r[3]?parseInt(r[3],10):0,i=r[5]?parseInt(r[5],10):0;return{value:o*(n*Mi+s*ji+i*Dm),rest:e.slice(r[0].length)}}function Xi(t){return W(z.anyDigitsSigned,t)}function U(t,e){switch(t){case 1:return W(z.singleDigit,e);case 2:return W(z.twoDigits,e);case 3:return W(z.threeDigits,e);case 4:return W(z.fourDigits,e);default:return W(new RegExp("^\\d{1,"+t+"}"),e)}}function Ko(t,e){switch(t){case 1:return W(z.singleDigitSigned,e);case 2:return W(z.twoDigitsSigned,e);case 3:return W(z.threeDigitsSigned,e);case 4:return W(z.fourDigitsSigned,e);default:return W(new RegExp("^-?\\d{1,"+t+"}"),e)}}function Jo(t){switch(t){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function Qi(t,e){let r=e>0,o=r?e:1-e,n;if(o<=50)n=t||100;else{let s=o+50,i=Math.trunc(s/100)*100,a=t>=s%100;n=t+i-(a?100:0)}return r?n:1-n}function Zi(t){return t%400===0||t%4===0&&t%100!==0}var ea=class extends C{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(e,r,o){let n=s=>({year:s,isTwoDigitYear:r==="yy"});switch(r){case"y":return Y(U(4,e),n);case"yo":return Y(o.ordinalNumber(e,{unit:"year"}),n);default:return Y(U(r.length,e),n)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,o){let n=e.getFullYear();if(o.isTwoDigitYear){let i=Qi(o.year,n);return e.setFullYear(i,0,1),e.setHours(0,0,0,0),e}let s=!("era"in r)||r.era===1?o.year:1-o.year;return e.setFullYear(s,0,1),e.setHours(0,0,0,0),e}};var ta=class extends C{priority=130;parse(e,r,o){let n=s=>({year:s,isTwoDigitYear:r==="YY"});switch(r){case"Y":return Y(U(4,e),n);case"Yo":return Y(o.ordinalNumber(e,{unit:"year"}),n);default:return Y(U(r.length,e),n)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,o,n){let s=zo(e,n);if(o.isTwoDigitYear){let a=Qi(o.year,s);return e.setFullYear(a,0,n.firstWeekContainsDate),e.setHours(0,0,0,0),Ve(e,n)}let i=!("era"in r)||r.era===1?o.year:1-o.year;return e.setFullYear(i,0,n.firstWeekContainsDate),e.setHours(0,0,0,0),Ve(e,n)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]};var ra=class extends C{priority=130;parse(e,r){return r==="R"?Ko(4,e):Ko(r.length,e)}set(e,r,o){let n=V(e,0);return n.setFullYear(o,0,4),n.setHours(0,0,0,0),St(n)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]};var oa=class extends C{priority=130;parse(e,r){return r==="u"?Ko(4,e):Ko(r.length,e)}set(e,r,o){return e.setFullYear(o,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]};var na=class extends C{priority=120;parse(e,r,o){switch(r){case"Q":case"QQ":return U(r.length,e);case"Qo":return o.ordinalNumber(e,{unit:"quarter"});case"QQQ":return o.quarter(e,{width:"abbreviated",context:"formatting"})||o.quarter(e,{width:"narrow",context:"formatting"});case"QQQQQ":return o.quarter(e,{width:"narrow",context:"formatting"});default:return o.quarter(e,{width:"wide",context:"formatting"})||o.quarter(e,{width:"abbreviated",context:"formatting"})||o.quarter(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=1&&r<=4}set(e,r,o){return e.setMonth((o-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]};var sa=class extends C{priority=120;parse(e,r,o){switch(r){case"q":case"qq":return U(r.length,e);case"qo":return o.ordinalNumber(e,{unit:"quarter"});case"qqq":return o.quarter(e,{width:"abbreviated",context:"standalone"})||o.quarter(e,{width:"narrow",context:"standalone"});case"qqqqq":return o.quarter(e,{width:"narrow",context:"standalone"});default:return o.quarter(e,{width:"wide",context:"standalone"})||o.quarter(e,{width:"abbreviated",context:"standalone"})||o.quarter(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=1&&r<=4}set(e,r,o){return e.setMonth((o-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]};var ia=class extends C{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(e,r,o){let n=s=>s-1;switch(r){case"M":return Y(W(z.month,e),n);case"MM":return Y(U(2,e),n);case"Mo":return Y(o.ordinalNumber(e,{unit:"month"}),n);case"MMM":return o.month(e,{width:"abbreviated",context:"formatting"})||o.month(e,{width:"narrow",context:"formatting"});case"MMMMM":return o.month(e,{width:"narrow",context:"formatting"});default:return o.month(e,{width:"wide",context:"formatting"})||o.month(e,{width:"abbreviated",context:"formatting"})||o.month(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.setMonth(o,1),e.setHours(0,0,0,0),e}};var aa=class extends C{priority=110;parse(e,r,o){let n=s=>s-1;switch(r){case"L":return Y(W(z.month,e),n);case"LL":return Y(U(2,e),n);case"Lo":return Y(o.ordinalNumber(e,{unit:"month"}),n);case"LLL":return o.month(e,{width:"abbreviated",context:"standalone"})||o.month(e,{width:"narrow",context:"standalone"});case"LLLLL":return o.month(e,{width:"narrow",context:"standalone"});default:return o.month(e,{width:"wide",context:"standalone"})||o.month(e,{width:"abbreviated",context:"standalone"})||o.month(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.setMonth(o,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]};function oh(t,e,r){let o=R(t,r?.in),n=qi(o,r)-e;return o.setDate(o.getDate()-n*7),R(o,r?.in)}var la=class extends C{priority=100;parse(e,r,o){switch(r){case"w":return W(z.week,e);case"wo":return o.ordinalNumber(e,{unit:"week"});default:return U(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,o,n){return Ve(oh(e,o,n),n)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]};function nh(t,e,r){let o=R(t,r?.in),n=Bi(o,r)-e;return o.setDate(o.getDate()-n*7),o}var ua=class extends C{priority=100;parse(e,r,o){switch(r){case"I":return W(z.week,e);case"Io":return o.ordinalNumber(e,{unit:"week"});default:return U(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,o){return St(nh(e,o))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]};var u0=[31,28,31,30,31,30,31,31,30,31,30,31],c0=[31,29,31,30,31,30,31,31,30,31,30,31],ca=class extends C{priority=90;subPriority=1;parse(e,r,o){switch(r){case"d":return W(z.date,e);case"do":return o.ordinalNumber(e,{unit:"date"});default:return U(r.length,e)}}validate(e,r){let o=e.getFullYear(),n=Zi(o),s=e.getMonth();return n?r>=1&&r<=c0[s]:r>=1&&r<=u0[s]}set(e,r,o){return e.setDate(o),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]};var da=class extends C{priority=90;subpriority=1;parse(e,r,o){switch(r){case"D":case"DD":return W(z.dayOfYear,e);case"Do":return o.ordinalNumber(e,{unit:"date"});default:return U(r.length,e)}}validate(e,r){let o=e.getFullYear();return Zi(o)?r>=1&&r<=366:r>=1&&r<=365}set(e,r,o){return e.setMonth(0,o),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]};function Yo(t,e,r){let o=lt(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,s=R(t,r?.in),i=s.getDay(),l=(e%7+7)%7,u=7-n,c=e<0||e>6?e-(i+u)%7:(l+u)%7-(i+u)%7;return Ui(s,c,r)}var fa=class extends C{priority=90;parse(e,r,o){switch(r){case"E":case"EE":case"EEE":return o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});case"EEEEE":return o.day(e,{width:"narrow",context:"formatting"});case"EEEEEE":return o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});default:return o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=Yo(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["D","i","e","c","t","T"]};var ma=class extends C{priority=90;parse(e,r,o,n){let s=i=>{let a=Math.floor((i-1)/7)*7;return(i+n.weekStartsOn+6)%7+a};switch(r){case"e":case"ee":return Y(U(r.length,e),s);case"eo":return Y(o.ordinalNumber(e,{unit:"day"}),s);case"eee":return o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});case"eeeee":return o.day(e,{width:"narrow",context:"formatting"});case"eeeeee":return o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});default:return o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=Yo(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]};var ha=class extends C{priority=90;parse(e,r,o,n){let s=i=>{let a=Math.floor((i-1)/7)*7;return(i+n.weekStartsOn+6)%7+a};switch(r){case"c":case"cc":return Y(U(r.length,e),s);case"co":return Y(o.ordinalNumber(e,{unit:"day"}),s);case"ccc":return o.day(e,{width:"abbreviated",context:"standalone"})||o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"});case"ccccc":return o.day(e,{width:"narrow",context:"standalone"});case"cccccc":return o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"});default:return o.day(e,{width:"wide",context:"standalone"})||o.day(e,{width:"abbreviated",context:"standalone"})||o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=Yo(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]};function sh(t,e,r){let o=R(t,r?.in),n=th(o,r),s=e-n;return Ui(o,s,r)}var pa=class extends C{priority=90;parse(e,r,o){let n=s=>s===0?7:s;switch(r){case"i":case"ii":return U(r.length,e);case"io":return o.ordinalNumber(e,{unit:"day"});case"iii":return Y(o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n);case"iiiii":return Y(o.day(e,{width:"narrow",context:"formatting"}),n);case"iiiiii":return Y(o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n);default:return Y(o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n)}}validate(e,r){return r>=1&&r<=7}set(e,r,o){return e=sh(e,o),e.setHours(0,0,0,0),e}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]};var ga=class extends C{priority=80;parse(e,r,o){switch(r){case"a":case"aa":case"aaa":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"aaaaa":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(Jo(o),0,0,0),e}incompatibleTokens=["b","B","H","k","t","T"]};var ya=class extends C{priority=80;parse(e,r,o){switch(r){case"b":case"bb":case"bbb":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"bbbbb":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(Jo(o),0,0,0),e}incompatibleTokens=["a","B","H","k","t","T"]};var ba=class extends C{priority=80;parse(e,r,o){switch(r){case"B":case"BB":case"BBB":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"BBBBB":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(Jo(o),0,0,0),e}incompatibleTokens=["a","b","t","T"]};var _a=class extends C{priority=70;parse(e,r,o){switch(r){case"h":return W(z.hour12h,e);case"ho":return o.ordinalNumber(e,{unit:"hour"});default:return U(r.length,e)}}validate(e,r){return r>=1&&r<=12}set(e,r,o){let n=e.getHours()>=12;return n&&o<12?e.setHours(o+12,0,0,0):!n&&o===12?e.setHours(0,0,0,0):e.setHours(o,0,0,0),e}incompatibleTokens=["H","K","k","t","T"]};var wa=class extends C{priority=70;parse(e,r,o){switch(r){case"H":return W(z.hour23h,e);case"Ho":return o.ordinalNumber(e,{unit:"hour"});default:return U(r.length,e)}}validate(e,r){return r>=0&&r<=23}set(e,r,o){return e.setHours(o,0,0,0),e}incompatibleTokens=["a","b","h","K","k","t","T"]};var va=class extends C{priority=70;parse(e,r,o){switch(r){case"K":return W(z.hour11h,e);case"Ko":return o.ordinalNumber(e,{unit:"hour"});default:return U(r.length,e)}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.getHours()>=12&&o<12?e.setHours(o+12,0,0,0):e.setHours(o,0,0,0),e}incompatibleTokens=["h","H","k","t","T"]};var Sa=class extends C{priority=70;parse(e,r,o){switch(r){case"k":return W(z.hour24h,e);case"ko":return o.ordinalNumber(e,{unit:"hour"});default:return U(r.length,e)}}validate(e,r){return r>=1&&r<=24}set(e,r,o){let n=o<=24?o%24:o;return e.setHours(n,0,0,0),e}incompatibleTokens=["a","b","h","H","K","t","T"]};var xa=class extends C{priority=60;parse(e,r,o){switch(r){case"m":return W(z.minute,e);case"mo":return o.ordinalNumber(e,{unit:"minute"});default:return U(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,o){return e.setMinutes(o,0,0),e}incompatibleTokens=["t","T"]};var ka=class extends C{priority=50;parse(e,r,o){switch(r){case"s":return W(z.second,e);case"so":return o.ordinalNumber(e,{unit:"second"});default:return U(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,o){return e.setSeconds(o,0),e}incompatibleTokens=["t","T"]};var Ta=class extends C{priority=30;parse(e,r){let o=n=>Math.trunc(n*Math.pow(10,-r.length+3));return Y(U(r.length,e),o)}set(e,r,o){return e.setMilliseconds(o),e}incompatibleTokens=["t","T"]};var Ca=class extends C{priority=10;parse(e,r){switch(r){case"X":return ct(ut.basicOptionalMinutes,e);case"XX":return ct(ut.basic,e);case"XXXX":return ct(ut.basicOptionalSeconds,e);case"XXXXX":return ct(ut.extendedOptionalSeconds,e);default:return ct(ut.extended,e)}}set(e,r,o){return r.timestampIsSet?e:V(e,e.getTime()-eo(e)-o)}incompatibleTokens=["t","T","x"]};var Ea=class extends C{priority=10;parse(e,r){switch(r){case"x":return ct(ut.basicOptionalMinutes,e);case"xx":return ct(ut.basic,e);case"xxxx":return ct(ut.basicOptionalSeconds,e);case"xxxxx":return ct(ut.extendedOptionalSeconds,e);default:return ct(ut.extended,e)}}set(e,r,o){return r.timestampIsSet?e:V(e,e.getTime()-eo(e)-o)}incompatibleTokens=["t","T","X"]};var Pa=class extends C{priority=40;parse(e){return Xi(e)}set(e,r,o){return[V(e,o*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"};var Oa=class extends C{priority=20;parse(e){return Xi(e)}set(e,r,o){return[V(e,o),{timestampIsSet:!0}]}incompatibleTokens="*"};var ih={G:new Yi,y:new ea,Y:new ta,R:new ra,u:new oa,Q:new na,q:new sa,M:new ia,L:new aa,w:new la,I:new ua,d:new ca,D:new da,E:new fa,e:new ma,c:new ha,i:new pa,a:new ga,b:new ya,B:new ba,h:new _a,H:new wa,K:new va,k:new Sa,m:new xa,s:new ka,S:new Ta,X:new Ca,x:new Ea,t:new Pa,T:new Oa};var d0=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,f0=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,m0=/^'([^]*?)'?$/,h0=/''/g,p0=/\S/,g0=/[a-zA-Z]/;function Je(t,e,r,o){let n=()=>V(o?.in||r,NaN),s=zi(),i=o?.locale??s.locale??ms,a=o?.firstWeekContainsDate??o?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,l=o?.weekStartsOn??o?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0;if(!e)return t?n():R(r,o?.in);let u={firstWeekContainsDate:a,weekStartsOn:l,locale:i},c=[new Ji(o?.in,r)],d=e.match(f0).map(y=>{let p=y[0];if(p in hs){let b=hs[p];return b(y,i.formatLong)}return y}).join("").match(d0),f=[];for(let y of d){!o?.useAdditionalWeekYearTokens&&Wi(y)&&ps(y,e,t),!o?.useAdditionalDayOfYearTokens&&Vi(y)&&ps(y,e,t);let p=y[0],b=ih[p];if(b){let{incompatibleTokens:_}=b;if(Array.isArray(_)){let L=f.find(x=>_.includes(x.token)||x.token===p);if(L)throw new RangeError(`The format string mustn't contain \`${L.fullToken}\` and \`${y}\` at the same time`)}else if(b.incompatibleTokens==="*"&&f.length>0)throw new RangeError(`The format string mustn't contain \`${y}\` and any other token at the same time`);f.push({token:p,fullToken:y});let v=b.run(t,y,i.match,u);if(!v)return n();c.push(v.setter),t=v.rest}else{if(p.match(g0))throw new RangeError("Format string contains an unescaped latin alphabet character `"+p+"`");if(y==="''"?y="'":p==="'"&&(y=y0(y)),t.indexOf(y)===0)t=t.slice(y.length);else return n()}}if(t.length>0&&p0.test(t))return n();let m=c.map(y=>y.priority).sort((y,p)=>p-y).filter((y,p,b)=>b.indexOf(y)===p).map(y=>c.filter(p=>p.priority===y).sort((p,b)=>b.subPriority-p.subPriority)).map(y=>y[0]),h=R(r,o?.in);if(isNaN(+h))return n();let g={};for(let y of m){if(!y.validate(h,u))return n();let p=y.set(h,g,u);Array.isArray(p)?(h=p[0],Object.assign(g,p[1])):h=p}return h}function y0(t){return t.match(m0)[1].replace(h0,"'")}function ah(t,e){let r=R(t,e?.in);return r.setSeconds(0,0),r}import{z as w}from"zod";import{z as Iu}from"zod";var lh=["pos","kds","kiosk"],Tj=Iu.enum(lh),b0=[...lh,"restaurant_site","developer_dashboard","zorgo_site","backend"],uh=Iu.enum(b0),_0=["gateway","main_service","agent_service","background_workers"],Cj=Iu.enum(_0);var Du=w.object({settle_ms:w.number().nullable().default(null),interaction_wait_ms:w.number().nullable().default(null),capture_ms:w.number().nullable().default(null),print_ms:w.number().nullable().default(null)}),w0=w.object({global:w.object({font_family:w.enum(["sans-serif","serif","monospace"]).default("sans-serif"),base_font_size:w.enum(["small","medium","large"]).default("large"),text_alignment:w.enum(["left","center"]).default("left")}).prefault({}),header:w.object({show_logo:w.boolean().default(!0),show_customer_name:w.boolean().default(!0),show_time_info:w.boolean().default(!0),show_order_number:w.boolean().default(!0),order_number_style:w.enum(["bold","normal, small"]).default("bold")}).prefault({}),body:w.object({show_modifiers:w.boolean().default(!0),show_item_notes:w.boolean().default(!0),show_prices:w.boolean().default(!0),compact_view:w.boolean().default(!0)}).prefault({}),footer:w.object({show_tax_breakdown:w.boolean().default(!0),show_subtotal:w.boolean().default(!0),show_tax:w.boolean().default(!0),show_service_fee:w.boolean().default(!1),show_tip:w.boolean().default(!0),show_suggested_tips:w.boolean().default(!1),show_customer_signature:w.boolean().default(!1),show_grand_total:w.boolean().default(!0),total_line_label:w.string().max(24).default("Total"),suggested_tip_percentages:w.array(w.number().min(0).max(1)).default([.2,.15,.1]),custom_message:w.string().max(200).optional().default(""),customer_signature_agreement:w.string().max(300).default("I agree to pay the above amount per the cardholder and/or merchant agreement")}).prefault({})}),v0=w.enum(["kitchen","merchant","customer"]),Oj=w.object({id:w.uuid().optional(),franchise_id:w.number().default(-1),type:v0.default("kitchen"),config:w0.prefault({})}),ch=w.string().regex(/^[1-9][0-9]?\/[1-9][0-9]?$/,'portion must look like "1/2"').refine(t=>{let[e,r]=t.split("/").map(Number);return e<=r},"portion index cannot exceed its divisions"),S0=w.enum(["radial","grid","linear","count"]),Aj=w.object({id:w.number(),franchise_id:w.number(),geometry:S0,name:w.string().min(1),min_divisions:w.number().int().min(1).default(1),max_divisions:w.number().int().min(1).max(12)}).check(t=>{let e=t.value;e.max_divisions<e.min_divisions&&t.issues.push({code:"custom",input:e,path:["max_divisions"],message:"max_divisions must be >= min_divisions"})}),x0=w.object({type:w.enum(["item","component"]),id:w.number(),quantity:w.number(),upcharge:w.number(),serving_price:w.number().optional(),name:w.string(),portion:ch.nullish()}),k0=w.object({rule_id:w.number(),group_name:w.string(),selections:w.array(x0)}),T0=w.object({id:w.number(),servings_per_item:w.number().nullish(),is_base:w.boolean().nullish(),price_per_serving:w.number().nullish(),franchise_id:w.number().nullish(),component_type_id:w.number(),serving_weight:w.number().nullish(),name:w.string().default(""),item_id:w.number().nullish(),quantity_servings:w.number(),upcharge:w.number().nullish(),rule_id:w.number().nullish(),portion:ch.nullish()}),C0=w.object({item_id:w.number(),name:w.string(),quantity:w.number(),price:w.number(),order_item_id:w.number().nullish(),status:w.enum(["removed","modified"]).nullish(),category_id:w.number().nullish(),category_name:w.string().nullish(),is_catering:w.boolean().nullish(),per_person:w.boolean().nullish(),components:w.array(T0).nullish(),selections:w.array(k0).nullish(),comments:w.string().nullish()}),E0=w.object({customer_id:w.number().optional(),phone:w.string(),first_name:w.string(),last_name:w.string().nullish(),email:w.string().nullish(),allow_marketing:w.boolean().default(!1)}),Rj=w.object({first_name:w.string().min(2,"Enter at least 2 characters"),last_name:w.string().min(2,"Enter at least 2 characters"),phone:w.string().regex(/^\d{10}$/,"Enter a 10-digit phone number"),email:w.email().optional().or(w.literal("")),allow_marketing:w.boolean().optional().default(!1)});var P0=w.object({id:w.number(),order_id:w.number().nullish(),total:w.number(),subtotal:w.number(),tax:w.number(),tip:w.number().nullish(),discount:w.number().nullish(),service_fee:w.number().nullish(),charge_id:w.string().nullish(),charge_status:w.number().nullish(),created_at:w.coerce.date().nullish(),setup_intent_id:w.string().nullish(),payment_method_id:w.string().nullish(),stripe_customer_id:w.string().nullish()}),Ij=w.object({order_id:w.number(),customer:E0,location_id:w.number(),method_id:w.number().nullish(),type_id:w.number().nullish(),time_placed:w.coerce.date(),time_requested:w.coerce.date().nullish(),items:w.array(C0),order_status:w.number().nullish(),order_code:w.string().optional(),promo_code:w.string().nullish(),charges:w.array(P0),subtotal:w.number().nullish(),delivery_address:w.string().optional()}),O0=w.enum(["guest","requested_access","action_required","pending_approval","healthy"]).default("guest"),Dj=w.object({id:w.string(),user_id:w.string(),franchise_name:w.string(),number_of_locations:w.number(),phone:w.string(),email:w.string(),status:O0,metadata:w.record(w.string(),w.unknown()).default({}),created_at:w.coerce.date()}),Lj=w.object({location_id:w.number(),table_number:w.number(),label:w.string().nullish(),capacity:w.number(),shape:w.enum(["rect","round"]),reservable:w.boolean(),x:w.number(),y:w.number(),w:w.number(),h:w.number()}),Nj=w.object({salesCount:w.number().int().nonnegative(),grossRevenue:w.number().int().nonnegative(),totalRevenue:w.number().int().nonnegative(),totalRefunds:w.number().int().nonnegative(),totalDiscounts:w.number().int().nonnegative(),totalTips:w.number().int().nonnegative(),netRevenue:w.number().int()}),jj=w.object({requireTableForDineIn:w.boolean().default(!1)});var gs=()=>typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});function fh(t){let e=(t||"").replace(/\D/g,"");return e.length===11?`+${e}`:`+1${e}`}var _r=typeof globalThis.document<"u"&&globalThis.navigator?.product!=="ReactNative",dh={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function wr(){let t=globalThis;if(typeof t.window<"u"&&typeof t.window.localStorage<"u")return t.window.localStorage;if(t?.navigator?.product==="ReactNative"||typeof t?.document>"u"&&typeof process>"u")try{return(Pu(),Yc(Eu)).default}catch{return dh}return dh}function Aa(t){return`(${t.join(",")})`}var Lu=(n=>(n.Website="website",n.Kiosk="kiosk",n.Pos="pos",n.KitchenDisplay="kitchen_display",n))(Lu||{});var Vj={website:"Website",kiosk:"Kiosk",pos:"POS"},Mt=class extends Error{constructor(e){super(e),this.name="VisibilityConditionError"}};function mh(t){let e=t?.date??new Date,r=["su","m","t","w","th","f","sa"],o=e.getHours().toString().padStart(2,"0"),n=e.getMinutes().toString().padStart(2,"0");return{dayOfWeek:r[e.getDay()]??"m",currentTime:`${o}:${n}`,platform:t?.platform??"website"}}function A0(t){if(t.version!==1)throw new Mt("Unsupported visibility condition version.");ph(t.root)}function hh(t,e){return A0(t),Nu(t.root,e)}function ph(t){switch(t.type){case"group":if(t.children.length===0)throw new Mt("Condition groups cannot be empty.");t.children.forEach(ph);return;case"constant":return;case"rule":R0(t);return;default:throw new Mt("Unknown visibility condition node.")}}function R0(t){if(t.variable==="dayOfWeek"){if(!Array.isArray(t.value)||t.value.length===0)throw new Mt("Day-of-week rules require at least one day.");return}if(t.variable==="platform"){if((Array.isArray(t.value)?t.value:[t.value]).length===0)throw new Mt("Platform rules require at least one platform.");return}if(t.variable==="currentTime"){if(t.operator==="between"){if(typeof t.value!="object"||t.value==null||!("start"in t.value)||!("end"in t.value))throw new Mt("Between rules require a start and end time.");Ia(t.value.start),Ia(t.value.end);return}if(typeof t.value!="string")throw new Mt("Time rules require a single time value.");Ia(t.value)}}function Nu(t,e){return t.type==="group"?t.operator==="and"?t.children.every(r=>Nu(r,e)):t.children.some(r=>Nu(r,e)):t.type==="constant"?t.value:I0(t,e)}function I0(t,e){switch(t.variable){case"dayOfWeek":{let r=t.value;return t.operator==="is_any_of"?r.includes(e.dayOfWeek):!r.includes(e.dayOfWeek)}case"platform":{let r=Array.isArray(t.value)?t.value:[t.value];switch(t.operator){case"is":return e.platform===r[0];case"is_not":return e.platform!==r[0];case"is_any_of":return r.includes(e.platform)}}case"currentTime":{let r=Ra(e.currentTime);if(t.operator==="between"){let n=t.value,s=Ra(n.start),i=Ra(n.end);return r>=s&&r<=i}let o=Ra(t.value);switch(t.operator){case"before":return r<o;case"after":return r>o;case"on_or_before":return r<=o;case"on_or_after":return r>=o;default:return!1}}default:return!1}}function Ra(t){Ia(t);let e=t.split(":"),r=Number(e[0]),o=Number(e[1]);return r*60+o}function Ia(t){if(!/^\d{2}:\d{2}$/.test(t))throw new Mt(`Invalid time "${t}". Use HH:mm format.`)}var vr={ascending:!0,nullsFirst:!1},gh=Number.MAX_SAFE_INTEGER;function Uu(t,e){let r=(t.sort_index??gh)-(e.sort_index??gh);return r!==0?r:t.name.localeCompare(e.name)}async function yh(t,e,r=wh(),o=!1){let n=await N0(t,e,r.categoryIds);if(n.length===0)return Mu([],[],[],[],[]);let s=await j0(t,e,r.baseItemIds,n);if(s.length===0)return Mu([],[],n,[],[]);let i=await U0(t,s,r.itemIds),a=await F0(t,i,o),l=await $0(t,s,n,i,o);return Mu(i,s,n,a,l)}function bh(t,e){let r=new Map,o=(i,a)=>a.promotion_type_id===1?Math.max(0,Math.floor(i*(1-a.discount_value/100))):a.promotion_type_id===2?Math.max(0,i-a.discount_value):i,n=t.items.map(i=>{let l=e.find(c=>{if(!c.is_active||c.id==null||!c.discount_target_ids?.length||!c.min_purchase_quantity)return!1;let d=c.discount_target_ids;return c.discount_target_type==="category"&&d.includes(i.category_id)||c.discount_target_type==="item"&&d.includes(i.base_item_id)})?.id,u=i.variants.map(c=>{let d,f=c.price;for(let m of e){if(!m.is_active||m.id==null||!m.discount_target_ids?.length||m.min_purchase_amount||m.min_purchase_quantity)continue;let h=m.discount_target_ids;if(!(m.discount_target_type==="category"&&h.includes(i.category_id)||m.discount_target_type==="item"&&h.includes(i.base_item_id)||m.discount_target_type==="item_variant"&&h.includes(c.item_id)))continue;let y=o(c.price,m);y<f&&(d=m,f=y)}return!d||f>=c.price?c:(l??=d.id,d.discount_target_type==="category"&&r.set(i.category_id,d.id),{...c,active_promo_id:d.id,display_price:f})});return{...i,variants:u,active_promo_id:l}}),s=t.categories.map(i=>{let{active_promo_id:a,...l}=i,u=r.get(l.category_id);return u==null?l:{...l,active_promo_id:u}});return{...t,items:n,categories:s}}async function _h(t,e,r,o){let n=await D0(t,e),s=await L0(t,e,o);if(s.length===0)return wh();let i=ju(s,p=>p.category_id),a=ju(s,p=>p.base_item_id),l=ju(s,p=>p.item_id),u=new Map(n.baseItems.map(p=>[p.base_item_id,p])),c=new Map(n.items.map(p=>[p.item_id,p])),d=p=>i.get(p)!=="exclude",f=p=>{let b=a.get(p);if(b==="include")return!0;if(b==="exclude")return!1;let _=u.get(p)?.category_id;return _==null||d(_)},m=p=>{let b=l.get(p);if(b==="include")return!0;if(b==="exclude")return!1;let _=c.get(p);return _?.base_item_id==null?!0:f(_.base_item_id)},h=new Set(n.items.filter(p=>m(p.item_id)).map(p=>p.item_id)),g=new Set(n.baseItems.filter(p=>f(p.base_item_id)).map(p=>p.base_item_id));for(let p of n.items)h.has(p.item_id)&&p.base_item_id!=null&&g.add(p.base_item_id);let y=new Set(n.categories.filter(p=>d(p.category_id)).map(p=>p.category_id));for(let p of n.baseItems)g.has(p.base_item_id)&&y.add(p.category_id);return{categoryIds:n.categories.map(p=>p.category_id).filter(p=>!y.has(p)),baseItemIds:n.baseItems.map(p=>p.base_item_id).filter(p=>!g.has(p)),itemIds:n.items.map(p=>p.item_id).filter(p=>!h.has(p))}}function wh(){return{categoryIds:[],baseItemIds:[],itemIds:[]}}async function D0(t,e){let{data:r,error:o}=await t.from("categories").select("category_id").eq("franchise_id",e);if(o)throw o;let{data:n,error:s}=await t.from("base_items").select("base_item_id, category_id").eq("franchise_id",e);if(s)throw s;let i=(n??[]).map(u=>u.base_item_id),{data:a,error:l}=i.length>0?await t.from("items").select("item_id, base_item_id").in("base_item_id",i):{data:[],error:null};if(l)throw l;return{categories:r??[],baseItems:n??[],items:a??[]}}async function L0(t,e,r){let{data:o,error:n}=await t.from("visibility_condition_group_assignments").select("*, visibility_condition_groups (*)").eq("visibility_condition_groups.franchise_id",e).eq("visibility_condition_groups.platform",r);if(n||!o)return[];let s=mh({platform:r});return o.filter(i=>{let a=i.visibility_condition_groups;if(!a?.condition||a.platform!==s.platform)return!1;try{return hh(a.condition,s)}catch{return!1}})}function ju(t,e){let r=new Map;for(let o of t){let n=e(o);n!=null&&r.set(n,[...r.get(n)??[],o.effect])}return new Map(Array.from(r.entries()).map(([o,n])=>[o,n.includes("exclude")?"exclude":"include"]))}async function N0(t,e,r){let o=t.from("categories").select("*").eq("franchise_id",e).order("sort_index",vr).order("name",vr);r&&r.length>0&&(o=o.not("category_id","in",Aa(r)));let{data:n,error:s}=await o;if(s)throw s;return n??[]}async function j0(t,e,r,o){if(o&&o.length===0)return[];let n=t.from("base_items").select("*").eq("franchise_id",e).order("sort_index",vr).order("name",vr);r&&r.length>0&&(n=n.not("base_item_id","in",Aa(r))),o&&(n=n.in("category_id",o.map(u=>u.category_id)));let{data:s,error:i}=await n;if(i)throw i;if(!s||s.length===0)return[];let{data:a,error:l}=await t.from("base_item_images").select("*").in("base_item_id",s.map(u=>u.base_item_id)).order("sort_index",{ascending:!0}).order("image_id",{ascending:!0});if(l)throw l;return M0(s,a??[])}function M0(t,e){let r=new Map;for(let o of e){let n=r.get(o.base_item_id);n?n.push(o):r.set(o.base_item_id,[o])}return t.map(o=>({...o,images:r.get(o.base_item_id)??[]}))}async function U0(t,e,r){if(e&&e.length===0)return[];let o=t.from("items").select("*, portion_scheme:portion_schemes(*)").in("base_item_id",e.map(i=>i.base_item_id)).order("sort_index",vr).order("price",vr);r&&r.length>0&&(o=o.not("item_id","in",Aa(r)));let{data:n,error:s}=await o;if(s)throw s;return n??[]}async function F0(t,e,r=!1){let o=e.length>0&&typeof e[0]=="number"?e:e.map(i=>i.item_id);if(o.length===0)return[];let n=r?"components(*), item_id, servings_per_item, behavior_id, component_quantity_behaviors(headcount_threshold, starting_amount, step_size, step_interval, maximum)":"components(*), item_id, servings_per_item",{data:s}=await t.from("item_components").select(n).in("item_id",o).throwOnError();return s.map(i=>({servings_per_item:i.servings_per_item,is_base:i.components?.is_base,serving_weight:i.components?.serving_weight,component_type_id:i.components?.component_type_id,id:i.components?.id,name:i.components?.name,item_id:i.item_id,...r&&{behavior:i.component_quantity_behaviors??void 0}}))}function vh(t){return[...(t.components??[]).map(e=>({key:`component:${e.component_id}`,id:e.component_id,type:"component",name:e.name,basePrice:e.upcharge_price||0,description:e.description,sort_index:e.sort_index??null})),...(t.items??[]).map(e=>({key:`item:${e.item_id}`,id:e.item_id,type:"item",name:e.name,basePrice:e.upcharge_price||0,description:e.description,sort_index:e.sort_index??null}))].sort(Uu)}async function $0(t,e,r,o,n=!1,s){let i=o?.map(g=>g.item_id)??[],a=e?.map(g=>g.base_item_id)??[],l=r?.map(g=>g.category_id)??[];if(i.length===0&&a.length===0&&l.length===0&&!s?.length)return[];let u=[`item_id.in.(${i.length>0?i.join(","):-1})`,`base_item_id.in.(${a.length>0?a.join(","):-1})`,`category_id.in.(${l.length>0?l.join(","):-1})`,...s?.length?[`rule_id.in.(${s.join(",")})`]:[]].join(","),c=n?"component_quantity_behaviors(headcount_threshold, starting_amount, step_size, step_interval, maximum)":null,d=["component_id, upcharge_price, sort_index, components(name, description, serving_weight)",c].filter(Boolean).join(", "),f=["item_id, upcharge_price, sort_index, items(item_id, name, description)",c].filter(Boolean).join(", "),{data:m,error:h}=await t.from("item_rules").select(`
|
|
141
141
|
rule_id,
|
|
142
142
|
category_id,
|
|
143
143
|
item_id,
|
|
@@ -150,12 +150,12 @@ https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=bu({...r,
|
|
|
150
150
|
sort_index,
|
|
151
151
|
rule_components (${d}),
|
|
152
152
|
rule_items (${f})
|
|
153
|
-
`).or(u).order("sort_index",vr).order("rule_id",vr);if(h)throw h;return(m??[]).map(g=>({rule_id:g.rule_id,group_name:g.group_name,min_selection:g.min_selection,max_selection:g.max_selection,included_quantity:g.included_quantity,is_portionable:g.is_portionable,category_id:g.category_id,item_id:g.item_id,base_item_id:g.base_item_id,sort_index:g.sort_index??null,components:(g.rule_components??[]).map(y=>({component_id:y.component_id,upcharge_price:y.upcharge_price??0,name:y.components?.name??"",description:y.components?.description??void 0,serving_weight:y.components?.serving_weight??void 0,sort_index:y.sort_index??null,...n&&{behavior:y.component_quantity_behaviors??void 0}})).sort(ju),items:(g.rule_items??[]).map(y=>({item_id:y.item_id,name:y.items?.name??"",description:y.items?.description??void 0,upcharge_price:y.upcharge_price??0,sort_index:y.sort_index??null,...n&&{behavior:y.component_quantity_behaviors??void 0}})).sort(ju)}))}function Nu(t,e,r,o,n){let s={items:[],categories:[],rules:n,components:o};return s.items=e.map(i=>{let a=n.filter(c=>c.category_id===i.category_id),l=n.filter(c=>c.base_item_id===i.base_item_id),u=r.find(c=>c.category_id===i.category_id);return{...i,is_catering:u?.is_catering??!1,variants:t.filter(c=>c.base_item_id===i.base_item_id).map(c=>({...c,components:o.filter(d=>d.item_id===c.item_id),rules:[...a,...l,...n.filter(d=>d.item_id===c.item_id)]})),rules:l}}),s.categories=r.map(i=>({...i,rules:n.filter(a=>a.category_id===i.category_id)})),s}function ys(t,e,r,o=new Date){return t.filter(n=>{if(n.start_date&&new Date(n.start_date)>o||n.end_date&&new Date(n.end_date)<o||n.platforms&&n.platforms.length>0&&!n.platforms.includes(e)||!n.is_automatic)return!1;if(n.location_id!=null&&r!==void 0){if(n.location_id!==r)return!1}else if(n.location_id!=null&&r===void 0)return!1;if(n.schedule_details_json){let{interval:s,days:i,start_time:a,end_time:l}=n.schedule_details_json;if(s==="weekly"&&i&&!i.includes(Hi(o)+1))return!1;let u=xt(o);if(a&&We(o,Je(a,"HH:mm",u))||l&&jt(o,Je(l,"HH:mm",u)))return!1}return!0})}var Mu=null;function wh(t){Mu=t}async function B0(){if(!Mu)throw new Error("apiFetch called before registerTokenProvider");return Mu()}async function Ut(t,e={}){let r=await B0(),o={...e.headers};return o["x-request-id"]||(o["x-request-id"]=gs()),fetch(`${Ri}${t}`,{...e,headers:{"Content-Type":"application/json",...r&&{Authorization:`Bearer ${r}`},...o}})}function Zt(t){let[e,r]=t.split("/").map(Number);return{index:e,divisions:r}}function Da(t){return t?1/Zt(t).divisions:1}function Xo(t,e){return e?`${t}@${e}`:t}function kt(t){let e=t.indexOf("@");return e===-1?{baseKey:t,portion:null}:{baseKey:t.slice(0,e),portion:t.slice(e+1)}}function Qj(t,e){return Math.ceil(t/e)}function Zj(t){let{min_divisions:e,max_divisions:r}=t;return Array.from({length:r-e+1},(o,n)=>e+n)}var q0={radial:{2:["Left","Right"],4:["Top left","Bottom left","Bottom right","Top right"]},grid:{2:["Left","Right"],4:["Top left","Bottom left","Top right","Bottom right"]},linear:{2:["First half","Second half"]},count:{2:["First half","Second half"]}};function eM(t,e){if(!t)return"Whole";let{index:r,divisions:o}=Zt(t);return q0[e.geometry][o]?.[r-1]??`Part ${r} of ${o}`}function Sh(t,e,r){let o=e[t]??r,n=Object.entries(e).flatMap(([a,l])=>{let u=kt(a);return u.baseKey===t&&u.portion?[{portion:u.portion,value:l}]:[]});if(!n.length)return[{portion:null,value:o}];let{divisions:s}=Zt(n[0].portion),i=Array.from({length:s},(a,l)=>{let u=`${l+1}/${s}`;return{portion:u,value:n.find(c=>c.portion===u)?.value??o}});return i.every(a=>a.value===i[0].value)?[{portion:null,value:i[0].value}]:i}function Uu(t){return t.reduce((e,r)=>e+Da(kt(r).portion),0)}function xh(t,e,r){let o=new Map,n=new Map;for(let s of t){let{baseKey:i,portion:a}=kt(s);n.has(i)||n.set(i,n.size),o.set(s,n.get(i)<r?0:Math.ceil(e(i)*Da(a)))}return o}function kh(t,e){let{index:r,divisions:o}=Zt(t);if(o===e)return[t];if(e%o===0){let n=e/o,s=(r-1)*n+1;return Array.from({length:n},(i,a)=>`${s+a}/${e}`)}return o%e===0?[`${Math.ceil(r*e/o)}/${e}`]:null}function V0(t){if(!t)return"Whole";let{index:e,divisions:r}=Zt(t);return`Section ${e} of ${r}`}var W0={radial:"\u25CF",grid:"\u25A0",linear:"\u25A0",count:null},H0={radial:{2:["\u25D0","\u25D1"]},grid:{2:["\u25E7","\u25E8"]},linear:{2:["\u25E7","\u25E8"]},count:{}};function z0(t,e){if(!e)return null;if(!t)return W0[e];let{index:r,divisions:o}=Zt(t);return H0[e][o]?.[r-1]??null}function tM(t){let e=t.portion_scheme?.geometry,r=new Map,o=s=>{let i=s??"",a=r.get(i);return a||r.set(i,a={selections:[],removals:[],additions:[]}),a};for(let s of t.selections??[])for(let i of s.selections){let{selections:a}=o(i.portion),l=a.find(u=>u.rule_id===s.rule_id);l||a.push(l={...s,selections:[]}),l.selections.push(i)}for(let s of t.components??[])s.quantity_servings<=0?o(s.portion).removals.push(s):s.portion&&o(s.portion).additions.push(s);let n=s=>s?Zt(s).index:-1;return[...r.entries()].sort(([s],[i])=>n(s)-n(i)).map(([s,i])=>({portion:s||null,label:V0(s||null),glyph:z0(s||null,e),...i}))}var vh=t=>Math.round(t*100)/100;function rM(t,e,r=48){if(e===1)return`M 50 ${50-r} A ${r} ${r} 0 1 0 49.9 ${50-r} Z`;let o=2*Math.PI/e,n=-Math.PI/2-(t-1)*o,s=n-o,i=a=>`${vh(50+r*Math.cos(a))} ${vh(50+r*Math.sin(a))}`;return`M 50 50 L ${i(n)} A ${r} ${r} 0 ${o>Math.PI?1:0} 0 ${i(s)} Z`}function Th(t,e){return t.map(r=>!e.discount_target_type||e.discount_target_type==="item"&&r.base_item_id!=null&&e.discount_target_ids?.includes(r.base_item_id)||e.discount_target_type==="item_variant"&&e.discount_target_ids?.includes(r.item_id)||e.discount_target_type==="category"&&e.discount_target_ids?.includes(r.category_id)?{...r,applied_promo_id:e.id}:r)}function Ch(t){switch(t){case 1:return"Kiosk";case 2:return"Website";case 3:return"POS";default:return""}}function Eh(t){let{max_selection:e,min_selection:r}=t,o=e!=null&&e!==1/0,n=t.included_quantity??0,s=o?r===e?`Choose ${r}`:r>0?`Choose ${r} to ${e}`:`Choose up to ${e}`:r>0?`Choose at least ${r}`:"Choose any";return n>0?`${s}. ${n} included`:s}function Fu(t,e,r,o){let n=o/2,s=Math.log(99)/(o-n),i=1/(1+Math.exp(-s*(e-n))),a=1/(1+Math.exp(s*n)),l=(i-a)/(1-a);return t*(1-r*l)}var G0=.06;var K0=.02,J0=.015;function Y0(t,e,r=!1){return e!==2?0:Math.floor(r?J0*t:K0*t)}function Sr(t,e=!1){let r=e?t.display_price||0:t.price||0,o=t.selections?.reduce((s,i)=>s+i.selections.reduce((a,l)=>a+l.upcharge,0),0)||0;return(r+o)*t.quantity}function Qo({order:t}){return t.items.filter(e=>e.status!=="removed").reduce((e,r)=>e+Sr(r),0)}function X0(t,e){let r=Qo({order:t}),{discount:o}=eS(t,e),n=r-o,s=tS(n),i=Y0(n,t.method_id,t.is_catering??!1),a=n+s+i;return{subtotal:r,tax:s,service_fee:i,discount:o,total:a}}function bs(t,e,r=0){let o=Q0(t.charges),{subtotal:n,discount:s,tax:i,service_fee:a,total:l}=o.length?Z0(o):X0(t,e);return{lines:t.items.filter(u=>u.status!=="removed").map(u=>({name:u.name,quantity:u.quantity,unitPrice:Sr({...u,quantity:1}),lineTotal:Sr(u),perPerson:u.per_person,addOns:(u.selections??[]).flatMap(c=>c.selections.map(d=>({name:d.name,groupName:c.group_name,upcharge:d.upcharge})))})),subtotal:n,discount:s??0,tax:i,serviceFee:a??0,tip:r,total:l+r}}function Q0(t){return(t??[]).filter(e=>e.charge_status===1)}function Z0(t){return(Array.isArray(t)?t:[]).reduce((r,o)=>({subtotal:r.subtotal+o.subtotal,tax:r.tax+o.tax,tip:(r.tip||0)+(o.tip||0),discount:(r.discount||0)+(o.discount||0),service_fee:(r.service_fee||0)+(o.service_fee||0),total:r.total+o.total}),{subtotal:0,tax:0,tip:0,discount:0,service_fee:0,total:0})}function er(t,e,r){if(!e.method_id)throw new Error("Attach method_id to order to calculate promo discount.");if(!e.location_id)throw new Error("Attach location_id to order to calculate promo discount.");if(!t.is_active)return 0;let o=Ch(e.method_id).toLowerCase();if(t.platforms&&t.platforms.length>0&&!t.platforms.includes(o)||t.location_id&&t.location_id!==e.location_id||t.start_date&&We(r,new Date(t.start_date))||t.end_date&&jt(r,new Date(t.end_date)))return 0;if(t.schedule_details_json){let{interval:d,days:f,start_time:m,end_time:h}=t.schedule_details_json;if(d==="weekly"&&f&&!f.includes(Hi(r)+1))return 0;let g=xt(r);if(m){let y=Je(m,"HH:mm",g);if(We(r,y))return 0}if(h){let y=Je(h,"HH:mm",g);if(jt(r,y))return 0}}let n=e.is_catering||e.items.some(d=>d.is_catering);if(t.is_catering_only&&!n)return 0;let s=Qo({order:e});if(t.min_purchase_amount&&s<t.min_purchase_amount)return 0;let i=e.items.reduce((d,f)=>d+f.quantity,0),a=t.is_catering_only&&t.min_purchase_quantity;if(!a&&t.min_purchase_quantity&&i<t.min_purchase_quantity)return 0;let l=e.items,u=s;if(t.discount_target_type&&t.discount_target_ids?.length&&(l=e.items.filter(d=>t.discount_target_type==="category"?t.discount_target_ids.includes(d.category_id):t.discount_target_type==="item"?t.discount_target_ids.includes(d.base_item_id):t.discount_target_type==="item_variant"?t.discount_target_ids.includes(d.item_id):!1),u=l.reduce((d,f)=>d+Sr(f),0)),l.length===0)return 0;let c=0;if(a&&t.promotion_type_id===1){let d=l.reduce((m,h)=>m+h.quantity,0),f=Fu(u,d,t.discount_value/100,t.min_purchase_quantity);c=u-f}else t.promotion_type_id===1?c=u*(t.discount_value/100):t.promotion_type_id===2&&(c=t.discount_value);return Math.min(Math.floor(c),u)}function La(t){return t.is_automatic?t.discount_target_type?"item":"order":"private"}function Ph(t,e,r){if(!e.length)return{discount:0};let o,n=0;for(let u of e){if(La(u)!=="order")continue;let c=er(u,t,r);c>n&&(n=c,o=u)}let s=t.items.filter(u=>u.status!=="removed"),i=e.filter(u=>La(u)==="item"),a=[];i.length>0&&s.forEach((u,c)=>{let d=0,f;for(let m of i){let h={...t,items:[u]},g=er(m,h,r);g>d&&(d=g,f=m.id)}d>0&&f!==void 0&&a.push({itemIndex:c,itemId:u.item_id,promotionId:f,discount:d})});let l=a.reduce((u,c)=>u+c.discount,0);return n===0&&l===0?{discount:0}:n>=l?{discount:n,orderPromo:o}:{discount:l,itemDiscounts:a}}function eS(t,e,r=new Date){if(e)try{let n=er(e,t,r);return{name:e.name,discount:n}}catch{return{name:e.name,discount:0}}let o=t.items.reduce((n,s)=>n+(s.discount_amount??0),0);return o>0?{name:"Item discounts",discount:o}:{discount:0}}function tS(t){return Math.round(t*G0)}import{create as CS}from"zustand";function $u(t,e,r){let o=zi(),n=nS(t,r.timeZone,r.locale??o.locale);return"formatToParts"in n?rS(n,e):oS(n,e)}function rS(t,e){let r=t.formatToParts(e);for(let o=r.length-1;o>=0;--o)if(r[o].type==="timeZoneName")return r[o].value}function oS(t,e){let r=t.format(e).replace(/\u200E/g,""),o=/ [\w-+ ]+$/.exec(r);return o?o[0].substr(1):""}function nS(t,e,r){return new Intl.DateTimeFormat(r?[r.code,"en-US"]:void 0,{timeZone:e,timeZoneName:t})}function Ah(t,e){let r=uS(e);return"formatToParts"in r?iS(r,t):aS(r,t)}var sS={year:0,month:1,day:2,hour:3,minute:4,second:5};function iS(t,e){try{let r=t.formatToParts(e),o=[];for(let n=0;n<r.length;n++){let s=sS[r[n].type];s!==void 0&&(o[s]=parseInt(r[n].value,10))}return o}catch(r){if(r instanceof RangeError)return[NaN];throw r}}function aS(t,e){let r=t.format(e),o=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(r);return[parseInt(o[3],10),parseInt(o[1],10),parseInt(o[2],10),parseInt(o[4],10),parseInt(o[5],10),parseInt(o[6],10)]}var Bu={},Oh=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),lS=Oh==="06/25/2014, 00:00:00"||Oh==="\u200E06\u200E/\u200E25\u200E/\u200E2014\u200E \u200E00\u200E:\u200E00\u200E:\u200E00";function uS(t){return Bu[t]||(Bu[t]=lS?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})),Bu[t]}function _s(t,e,r,o,n,s,i){let a=new Date(0);return a.setUTCFullYear(t,e,r),a.setUTCHours(o,n,s,i),a}var Rh=36e5,cS=6e4,qu={timezone:/([Z+-].*)$/,timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function tr(t,e,r){if(!t)return 0;let o=qu.timezoneZ.exec(t);if(o)return 0;let n,s;if(o=qu.timezoneHH.exec(t),o)return n=parseInt(o[1],10),Ih(n)?-(n*Rh):NaN;if(o=qu.timezoneHHMM.exec(t),o){n=parseInt(o[2],10);let i=parseInt(o[3],10);return Ih(n,i)?(s=Math.abs(n)*Rh+i*cS,o[1]==="+"?-s:s):NaN}if(mS(t)){e=new Date(e||Date.now());let i=r?e:dS(e),a=Vu(i,t);return-(r?a:fS(e,a,t))}return NaN}function dS(t){return _s(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds())}function Vu(t,e){let r=Ah(t,e),o=_s(r[0],r[1]-1,r[2],r[3]%24,r[4],r[5],0).getTime(),n=t.getTime(),s=n%1e3;return n-=s>=0?s:1e3+s,o-n}function fS(t,e,r){let n=t.getTime()-e,s=Vu(new Date(n),r);if(e===s)return e;n-=s-e;let i=Vu(new Date(n),r);return s===i?s:Math.max(s,i)}function Ih(t,e){return-23<=t&&t<=23&&(e==null||0<=e&&e<=59)}var Dh={};function mS(t){if(Dh[t])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:t}),Dh[t]=!0,!0}catch{return!1}}var hS=60*1e3,Nh={X:function(t,e,r){let o=Wu(r.timeZone,t);if(o===0)return"Z";switch(e){case"X":return Lh(o);case"XXXX":case"XX":return Zo(o);default:return Zo(o,":")}},x:function(t,e,r){let o=Wu(r.timeZone,t);switch(e){case"x":return Lh(o);case"xxxx":case"xx":return Zo(o);default:return Zo(o,":")}},O:function(t,e,r){let o=Wu(r.timeZone,t);switch(e){case"O":case"OO":case"OOO":return"GMT"+pS(o,":");default:return"GMT"+Zo(o,":")}},z:function(t,e,r){switch(e){case"z":case"zz":case"zzz":return $u("short",t,r);default:return $u("long",t,r)}}};function Wu(t,e){let r=t?tr(t,e,!0)/hS:e?.getTimezoneOffset()??0;if(Number.isNaN(r))throw new RangeError("Invalid time zone specified: "+t);return r}function Na(t,e){let r=t<0?"-":"",o=Math.abs(t).toString();for(;o.length<e;)o="0"+o;return r+o}function Zo(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Na(Math.floor(o/60),2),s=Na(Math.floor(o%60),2);return r+n+e+s}function Lh(t,e){return t%60===0?(t>0?"-":"+")+Na(Math.abs(t)/60,2):Zo(t,e)}function pS(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Math.floor(o/60),s=o%60;return s===0?r+String(n):r+String(n)+e+Na(s,2)}function Hu(t){let e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),+t-+e}var ja=/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/;var zu=36e5,jh=6e4,gS=2,Fe={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,plainTime:/:/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:ja};function dt(t,e={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(t===null)return new Date(NaN);let r=e.additionalDigits==null?gS:Number(e.additionalDigits);if(r!==2&&r!==1&&r!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]")return new Date(t.getTime());if(typeof t=="number"||Object.prototype.toString.call(t)==="[object Number]")return new Date(t);if(Object.prototype.toString.call(t)!=="[object String]")return new Date(NaN);let o=yS(t),{year:n,restDateString:s}=bS(o.date,r),i=_S(s,n);if(i===null||isNaN(i.getTime()))return new Date(NaN);if(i){let a=i.getTime(),l=0,u;if(o.time&&(l=wS(o.time),l===null||isNaN(l)))return new Date(NaN);if(o.timeZone||e.timeZone){if(u=tr(o.timeZone||e.timeZone,new Date(a+l)),isNaN(u))return new Date(NaN)}else u=Hu(new Date(a+l)),u=Hu(new Date(a+l+u));return new Date(a+l+u)}else return new Date(NaN)}function yS(t){let e={},r=Fe.dateTimePattern.exec(t),o;if(r?(e.date=r[1],o=r[3]):(r=Fe.datePattern.exec(t),r?(e.date=r[1],o=r[2]):(e.date=null,o=t)),o){let n=Fe.timeZone.exec(o);n?(e.time=o.replace(n[1],""),e.timeZone=n[1].trim()):e.time=o}return e}function bS(t,e){if(t){let r=Fe.YYY[e],o=Fe.YYYYY[e],n=Fe.YYYY.exec(t)||o.exec(t);if(n){let s=n[1];return{year:parseInt(s,10),restDateString:t.slice(s.length)}}if(n=Fe.YY.exec(t)||r.exec(t),n){let s=n[1];return{year:parseInt(s,10)*100,restDateString:t.slice(s.length)}}}return{year:null}}function _S(t,e){if(e===null)return null;let r,o,n;if(!t||!t.length)return r=new Date(0),r.setUTCFullYear(e),r;let s=Fe.MM.exec(t);if(s)return r=new Date(0),o=parseInt(s[1],10)-1,Uh(e,o)?(r.setUTCFullYear(e,o),r):new Date(NaN);if(s=Fe.DDD.exec(t),s){r=new Date(0);let i=parseInt(s[1],10);return xS(e,i)?(r.setUTCFullYear(e,0,i),r):new Date(NaN)}if(s=Fe.MMDD.exec(t),s){r=new Date(0),o=parseInt(s[1],10)-1;let i=parseInt(s[2],10);return Uh(e,o,i)?(r.setUTCFullYear(e,o,i),r):new Date(NaN)}if(s=Fe.Www.exec(t),s)return n=parseInt(s[1],10)-1,Fh(n)?Mh(e,n):new Date(NaN);if(s=Fe.WwwD.exec(t),s){n=parseInt(s[1],10)-1;let i=parseInt(s[2],10)-1;return Fh(n,i)?Mh(e,n,i):new Date(NaN)}return null}function wS(t){let e,r,o=Fe.HH.exec(t);if(o)return e=parseFloat(o[1].replace(",",".")),Gu(e)?e%24*zu:NaN;if(o=Fe.HHMM.exec(t),o)return e=parseInt(o[1],10),r=parseFloat(o[2].replace(",",".")),Gu(e,r)?e%24*zu+r*jh:NaN;if(o=Fe.HHMMSS.exec(t),o){e=parseInt(o[1],10),r=parseInt(o[2],10);let n=parseFloat(o[3].replace(",","."));return Gu(e,r,n)?e%24*zu+r*jh+n*1e3:NaN}return null}function Mh(t,e,r){e=e||0,r=r||0;let o=new Date(0);o.setUTCFullYear(t,0,4);let n=o.getUTCDay()||7,s=e*7+r+1-n;return o.setUTCDate(o.getUTCDate()+s),o}var vS=[31,28,31,30,31,30,31,31,30,31,30,31],SS=[31,29,31,30,31,30,31,31,30,31,30,31];function $h(t){return t%400===0||t%4===0&&t%100!==0}function Uh(t,e,r){if(e<0||e>11)return!1;if(r!=null){if(r<1)return!1;let o=$h(t);if(o&&r>SS[e]||!o&&r>vS[e])return!1}return!0}function xS(t,e){if(e<1)return!1;let r=$h(t);return!(r&&e>366||!r&&e>365)}function Fh(t,e){return!(t<0||t>52||e!=null&&(e<0||e>6))}function Gu(t,e,r){return!(t<0||t>=25||e!=null&&(e<0||e>=60)||r!=null&&(r<0||r>=60))}var kS=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function Ku(t,e,r={}){e=String(e);let o=e.match(kS);if(o){let n=dt(r.originalDate||t,r);e=o.reduce(function(s,i){if(i[0]==="'")return s;let a=s.indexOf(i),l=s[a-1]==="'",u=s.replace(i,"'"+Nh[i[0]](n,i,r)+"'");return l?u.substring(0,a-1)+u.substring(a+1):u},e)}return Ue(t,e,r)}function ws(t,e,r){t=dt(t,r);let o=tr(e,t,!0),n=new Date(t.getTime()-o),s=new Date(0);return s.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),s.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),s}function Ma(t,e,r,o){return o={...o,timeZone:e,originalDate:t},Ku(ws(t,e,{timeZone:o.timeZone}),r,o)}function Ju(t,e,r){if(typeof t=="string"&&!t.match(ja))return dt(t,{...r,timeZone:e});t=dt(t,r);let o=_s(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()).getTime(),n=tr(e,new Date(o));return new Date(o+n)}var Ua="America/New_York",TS=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function Bh(t){return t.replace(/[+-].*$/,"").trim().slice(0,5)}function qh(t,e,r=0){let o=new Date(`${Ma(t,Ua,"yyyy-MM-dd")}T12:00:00Z`);o.setUTCDate(o.getUTCDate()+r);let n=o.toISOString().slice(0,10),s=TS[o.getUTCDay()],i=e[`${s}_open`],a=e[`${s}_close`];if(!i||!a)return null;let l=dt(`${n}T${Bh(i)}`,{timeZone:Ua}),u=dt(`${n}T${Bh(a)}`,{timeZone:Ua});return u<=l&&(u=new Date(u.getTime()+1440*60*1e3)),{day:s,open:l,close:u}}function Yu(t,e){if(e.force_close)return!0;for(let r of[-1,0]){let o=qh(t,e,r);if(o&&!We(t,o.open)&&We(t,o.close))return!1}return!0}import{devtools as ES,persist as PS,createJSONStorage as OS,subscribeWithSelector as AS}from"zustand/middleware";async function Vh(t,e){let r=e||M,{data:o,error:n}=await r.from("permissions").select("franchise_id, location_ids, portal_role").eq("user_id",t);if(n)throw n;if(o?.some(f=>f.portal_role==="admin")){let[f,m]=await Promise.all([r.from("franchises").select("*").throwOnError(),r.from("locations").select("*").throwOnError()]);return{franchises:f.data,locations:m.data}}let s=new Set(o?.map(f=>f.franchise_id).filter(f=>f!=null)??[]),i=new Set(o?.filter(f=>!f.location_ids?.length&&f.franchise_id!==null).map(f=>f.franchise_id)),a=o?.flatMap(f=>f.location_ids??[])??[],{data:l,error:u}=await r.from("franchises").select("*").in("franchise_id",Array.from(s));if(u)throw u;let{data:c,error:d}=await r.from("locations").select("*").or(`location_id.in.(${a.join(",")}), franchise_id.in.(${Array.from(i).join(",")})`);if(d)throw d;return{franchises:l,locations:c}}async function Wh(t,e){let r=e||M,{data:o,error:n}=await r.from("franchises").select("*").eq("franchise_id",t);if(n)throw n;let{data:s,error:i}=await r.from("locations").select("*").eq("franchise_id",t).or("status.is.null,status.neq.permanently_closed");if(i)throw i;return{franchises:o,locations:s}}async function Hh(t,e,r){let o=r||M,n={...e,...t},{data:s,error:i}=await o.from("locations").update(n).eq("location_id",e.location_id).select().single();if(i)throw i;return s}async function zh(t,e,r){let o=r||M,{data:n,error:s}=await o.from("locations").update({force_close:e}).eq("location_id",t);if(s)throw s;return n}async function Gh(t,e){let r=e||M,{data:o,error:n}=await r.from("locations").insert(t).select().single();if(n)throw n;return o}async function Kh(t,e){let r=e||M,{data:o,error:n}=await r.from("locations").delete().eq("location_id",t);if(n)throw n;return o}async function Jh(t,e,r){let o=r||M,n={...t,...e},{data:s,error:i}=await o.from("franchises").update(n).eq("franchise_id",t.franchise_id).select().single();if(i)throw i;return s}function Yh(t){try{let e=(t.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")))}catch{return{}}}var vs=CS()(AS(PS(ES((t,e)=>({selectedLocation:null,franchises:[],locations:[],userId:null,navScope:"franchise",initialize:async({userId:r,token:o,locationId:n})=>{if(r&&t({userId:r}),n){let{data:a}=await M.from("locations").select("*").eq("location_id",n).throwOnError().single(),{data:l}=await M.from("franchises").select("*").eq("franchise_id",a.franchise_id).throwOnError().single();t({selectedLocation:a,franchiseId:a.franchise_id,locations:[a],franchises:[l]});return}else if(o){let l=Yh(o).franchise_ids?.[0],{locations:u,franchises:c}=await Wh(l),d=e().selectedLocation,f=d?u.find(m=>m.location_id===d.location_id)??null:null;t({locations:u,franchises:c,franchiseId:l,selectedLocation:f});return}else if(r){let{locations:a,franchises:l}=await Vh(r);t({locations:a,franchises:l})}let i=e().locations[0];t({selectedLocation:i,...i&&{franchiseId:i.franchise_id}})},hydrate:({franchises:r,locations:o})=>t({franchises:r??[],locations:o??[]},!1,"hydrate"),getCurrentLocation:()=>e().selectedLocation,getIsCurrentLocationOpen:()=>{let r=e().selectedLocation;return r?!Yu(new Date,r):!1},getAllLocations:()=>e().locations,setForceClose:async(r,o)=>{await zh(o,r),t(n=>({locations:n.locations.map(s=>s.location_id===o?{...s,force_close:r}:s),selectedLocation:n.selectedLocation?.location_id===o?{...n.selectedLocation,force_close:r}:n.selectedLocation}))},setSelectedLocation:r=>{t({selectedLocation:r}),t({franchiseId:r.franchise_id})},setFranchiseId:r=>{if(t({franchiseId:r}),e().selectedLocation?.franchise_id!==r){let o=e().locations.find(n=>n.franchise_id===r&&n.location_id!==0)??e().locations.find(n=>n.franchise_id===r)??null;t({selectedLocation:o})}},enterFranchise:r=>{let o=e();if(t({franchiseId:r,navScope:"franchise"}),o.selectedLocation?.franchise_id!==r){let n=o.locations.find(s=>s.franchise_id===r&&s.location_id!==0)??o.locations.find(s=>s.franchise_id===r)??null;t({selectedLocation:n})}},enterLocation:r=>{t({selectedLocation:r,franchiseId:r.franchise_id,navScope:"location"})},exitToFranchise:()=>{t({navScope:"franchise"})},exitToAccount:()=>{t({navScope:"account"})},updateLocation:async(r,o)=>{await Hh(r,o),t(n=>({locations:n.locations.map(s=>s.location_id===o.location_id?{...s,...r}:s)}))},createLocation:async r=>{let o=await Gh(r);return t(n=>({locations:[...n.locations,o]})),o},deleteLocation:async r=>{await Kh(r),t(o=>({locations:o.locations.filter(n=>n.location_id!==r)}))},updateFranchise:async(r,o)=>{let n=await Jh(r,o);return t(s=>({franchises:s.franchises.map(i=>i.franchise_id===r.franchise_id?n:i)})),n}})),{name:"location",version:3,migrate:(t,e)=>{let r=t??{};return e<3?{...r,navScope:r.navScope??"franchise",franchiseId:r.franchiseId??r.selectedLocation?.franchise_id}:r},storage:OS(()=>wr()),skipHydration:_r,partialize:t=>({selectedLocation:t.selectedLocation,franchises:t.franchises,locations:t.locations,userId:t.userId,franchiseId:t.franchiseId,navScope:t.navScope})}))),K=vs;import{create as RS}from"zustand";import{immer as IS}from"zustand/middleware/immer";import{devtools as DS}from"zustand/middleware";async function Xh(t){let{data:e,error:r}=await M.from("promotions").select("*").eq("franchise_id",t);if(r)throw r;return e}async function Qh(t,e="website",r){let{data:o,error:n}=await M.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",t);if(n)throw n;let s=ys(o,e,r);return{all:o,active:s}}async function Zh(t,e){let{data:r,error:o}=await M.from("promotions").select("*").eq("promo_code",t).eq("franchise_id",e).eq("is_active",!0).single();return o||!r?null:r}async function ep(t){let{data:e,error:r}=await M.from("promotions").insert(t).select("*").single();if(r)throw r;return e}async function tp(t){let{data:e,error:r}=await M.from("promotions").update(t).eq("id",t.id).select("*").single();if(r)throw r;return e}async function rp(t){let{data:e,error:r}=await M.from("promotions").delete().eq("id",t).select("*").single();if(r)throw r;e||console.log("No promotion deleted")}async function op(t){let{data:e,error:r}=await M.from("franchise_marketing").select("personal_marketer").eq("franchise_id",t).maybeSingle();if(r)throw r;return e?.personal_marketer??!1}async function np(t,e){let{error:r}=await M.from("franchise_marketing").upsert({franchise_id:t,personal_marketer:e},{onConflict:"franchise_id"});if(r)throw r;let{error:o}=await M.from("agent_skill_config").upsert({franchise_id:t,skill_id:"personal-marketer",enabled:e,updated_at:new Date().toISOString()},{onConflict:"franchise_id,skill_id"});if(o)throw o}async function sp(t,e=10){let{data:r,error:o}=await M.from("personal_marketer_runs").select("*").eq("franchise_id",t).order("created_at",{ascending:!1}).limit(e);if(o)throw o;return r}var LS=RS()(DS(IS((t,e)=>({logLevel:1,promotions:[],allPromotions:[],activePromotions:[],personalMarketerEnabled:!1,recentRuns:[],recentOutboundMessages:[],getPromotions:async r=>{let o=await Xh(r);return t({promotions:o},!1,"getPromotions"),o},getActivePromotions:async(r,o,n="website")=>{let{active:s,all:i}=await Qh(r,n,o);return t({allPromotions:i,activePromotions:s},!1,"getActivePromotions"),s},getPromotionByCode:async(r,o)=>await Zh(r,o),addPromotion:async r=>{let o=await ep(r);t(n=>{n.promotions.push(o)})},updatePromotion:async r=>{let o=await tp(r);t(n=>{n.promotions=n.promotions.map(s=>s.id===o.id?o:s)})},deletePromotion:async r=>{await rp(r),t(o=>{o.promotions=o.promotions.filter(n=>n.id!==r)})},getPersonalMarketerSettings:async()=>{let r=vs.getState().franchiseId;if(!r){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}let o=await op(r);t({personalMarketerEnabled:o},!1,"getPersonalMarketerSettings")},setPersonalMarketerEnabled:async r=>{let o=vs.getState().selectedLocation?.franchise_id;if(!o){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}await np(o,r),t({personalMarketerEnabled:r},!1,"setPersonalMarketerEnabled")},getRecentRuns:async(r=10)=>{let o=vs.getState().franchiseId;if(!o)return e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found"),[];let n=await sp(o,r);return t({recentRuns:n},!1,"getRecentRuns"),n},createBlastRun:async(r,o)=>{let n=await Ut("/marketing/create-run",{method:"POST",body:JSON.stringify({franchiseId:r,source:"blast",strategyId:"promotionalBlast",promotionId:o,dryRun:!1})});if(!n.ok){let i=await n.json().catch(()=>({}));throw new Error(i?.error??`HTTP ${n.status}`)}let{run:s}=await n.json();return await e().getRecentRuns(),s}})),{name:"PromotionStore"})),we=LS;var lp=yn(ap(),1);import{useMemo as $S}from"react";function Fa(t){return t===2?2:1}var up=!1;function cp(){up=!0}var $a=NS()(FS(US(jS((t,e)=>({deliveryFeeCents:0,workingOrder:{time_placed:new Date,time_requested:void 0,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},location_id:K.getState().selectedLocation?.location_id||0,order_status:1,method_id:1,order_id:0,type_id:1,items:[],promo_code:void 0,charges:[],table_number:void 0},status:"idle",editingSourceOrder:null,promoOverrideActive:!1,addItem:(r,o)=>{let n=r;if(o){t(a=>{a.promoOverrideActive=!0,a.selectedPromotion=void 0,a.workingOrder.promo_code=void 0});let s=e().workingOrder.location_id,i=er(o,{items:[r],location_id:s,method_id:3},new Date);n={...r,applied_promo_id:o.id,discount_amount:i>0?i:void 0}}t(s=>{s.workingOrder.items.push(n),n.is_catering&&(s.workingOrder.is_catering=!0),s.status!=="editing"&&(s.workingOrder.order_id=0)}),e().checkBestPromo()},setTip:r=>t(o=>{o.selectedTip=r}),removeItem:r=>{t(o=>{o.workingOrder.items.splice(r,1),o.status!=="editing"&&(o.workingOrder.order_id=0)}),e().checkBestPromo()},updateItem:(r,o,n)=>{let s=r;if(n!==void 0)if(t(i=>{i.promoOverrideActive=!0,n&&(i.selectedPromotion=void 0,i.workingOrder.promo_code=void 0)}),n){let i=e().workingOrder.location_id,a=er(n,{items:[r],location_id:i,method_id:3},new Date);s={...r,applied_promo_id:n.id,discount_amount:a>0?a:void 0}}else s={...r,applied_promo_id:void 0,discount_amount:void 0};t(i=>{i.workingOrder.items[o]=s,i.status!=="editing"&&(i.workingOrder.order_id=0)}),e().checkBestPromo()},setCustomer:r=>t(o=>{o.workingOrder.customer=r}),getAnonCustomer:()=>({customer_id:0,first_name:"Customer",last_name:"Customer",phone:"0"}),setCart:r=>t(o=>{o.workingOrder=r}),createCustomer:async()=>{let r=e().workingOrder.customer,{data:o,error:n}=await M.from("customers").insert({first_name:r.first_name,last_name:r.last_name,email:r.email,phone_number:parseInt(r.phone)}).select("*").single();return n?(console.log("Error creating customer:",n),null):(console.log("customer created",o),o)},setLocationId:r=>t(o=>{o.workingOrder.location_id=r}),setOrderType:r=>t(o=>{o.workingOrder.type_id=Fa(r)}),setTableNumber:r=>t(o=>{o.workingOrder.table_number=r}),setTimeRequested:r=>t(o=>{o.workingOrder.time_requested=r}),applyCateringPreflight:r=>t(o=>{if(o.workingOrder.type_id=r.type_id,o.workingOrder.location_id=r.location_id,o.workingOrder.time_requested=r.time_requested,r.type_id===ds.ORDER_TYPE.DELIVERY){let n=r.delivery_address?.trim();o.workingOrder.delivery_address=n&&n.length>0?n:void 0}else o.workingOrder.delivery_address=void 0}),clearCateringSchedule:()=>t(r=>{r.workingOrder.time_requested=void 0}),setDeliveryFee:r=>t(o=>{o.deliveryFeeCents=r}),setPromoCode:r=>t(o=>{o.workingOrder.promo_code=r}),resetOrder:()=>t(r=>({workingOrder:{...r.workingOrder,order_id:0,location_id:K.getState().selectedLocation?.location_id??0,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},items:[],promo_code:void 0,type_id:1,is_catering:!1,time_requested:void 0,delivery_address:void 0,table_number:void 0},selectedTip:void 0,deliveryFeeCents:0})),setOrder:r=>t(o=>{o.workingOrder={...r,type_id:Fa(r.type_id)}}),startEdit:r=>t(o=>{let n={...r,type_id:Fa(r.type_id),charges:r.charges??[]};o.workingOrder=n,o.editingSourceOrder=n,o.status="editing",o.selectedTip=void 0;let s=Number(r.promo_code);o.selectedPromotion=s?we.getState().activePromotions.find(i=>i.id===s):void 0,o.promoOverrideActive=!!o.selectedPromotion}),cancelEdit:(r=!0)=>t(o=>{o.status="idle",o.editingSourceOrder=null,o.selectedTip=void 0,o.selectedPromotion=void 0,o.promoOverrideActive=!1,r&&(o.workingOrder={...o.workingOrder,location_id:K.getState().selectedLocation?.location_id??0,type_id:1,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},order_status:1,order_id:0,items:[],promo_code:void 0,charges:[],revision:void 0,updated_at:void 0,table_number:void 0})}),finishEdit:()=>t(r=>({workingOrder:{...r.workingOrder,location_id:K.getState().selectedLocation?.location_id??0,type_id:1,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},order_status:1,order_id:0,items:[],promo_code:void 0,charges:[],revision:void 0,updated_at:void 0,table_number:void 0},status:"idle",editingSourceOrder:null,selectedTip:void 0,selectedPromotion:void 0,promoOverrideActive:!1})),hasMeaningfulEditChanges:()=>{let{status:r,editingSourceOrder:o,workingOrder:n}=e();return r!=="editing"||!o?!1:!(0,lp.default)(o.items,n.items)},getOrderTotal:()=>Qo({order:e().workingOrder}),setCartFromURL:async(r,o)=>{try{let n={"Content-Type":"application/json",...o?{"X-Zorgo-Api-Key":o}:{}},s=await fetch(`${Ri}/s/${r}`,{headers:n});if(!s.ok)return!1;let{cart_data:i,promotion_id:a}=await s.json();return i?(t(l=>{if(l.workingOrder={...l.workingOrder,...i,type_id:Fa(i.type_id),order_id:0,order_status:1},l.workingOrder.time_requested=void 0,!a||i?.promo_code||i?.items?.some(d=>d.applied_promo_id))return;let c=we.getState().activePromotions.find(d=>d.id===a);if(!c){l.workingOrder.promo_code=String(a);return}if(c.promo_code){l.workingOrder.promo_code=c.promo_code;return}l.workingOrder.items=Th(l.workingOrder.items,c)}),e().checkBestPromo(),!0):!1}catch(n){return console.error("[CartStore] setCartFromURL failed:",n),!1}},dismissPromo:r=>{t(o=>{o.dismissedPromoIds=[...o.dismissedPromoIds||[],r]})},checkBestPromo:()=>{if(e().promoOverrideActive)return;let{workingOrder:r}=e();if(!r.location_id||!r.method_id)return;let o=we.getState().activePromotions,n=new Date,s=e().selectedPromotion;if(s&&La(s)==="private")return;let i=s?er(s,r,n):0;if(s&&i===0){e().removeOrderPromotion();return}let a=Ph(r,o,n);if(s){a.orderPromo&&a.orderPromo.id!==s.id&&a.discount>i&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo);return}if(a.itemDiscounts?.length?t(u=>{for(let c of u.workingOrder.items)c.display_price=void 0,c.applied_promo_id=void 0,c.discount_amount=void 0;for(let c of a.itemDiscounts){let d=u.workingOrder.items[c.itemIndex];d&&(d.applied_promo_id=c.promotionId,d.discount_amount=c.discount,d.display_price=d.price-Math.round(c.discount/d.quantity))}}):e().wipeItemPromos(),a.discount===0||!a.orderPromo)return;let l=e().workingOrder.items.reduce((u,c)=>u+(c.discount_amount??0),0);l===0?e().applyOrderPromotion(a.orderPromo):a.discount>l&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo)},setOnBestPromoChange:r=>{t(o=>(o.onBestPromoChange=r,o))},wipeItemPromos:()=>{t(r=>{r.workingOrder.items=r.workingOrder.items.map(o=>({...o,display_price:void 0,applied_promo_id:void 0,discount_amount:void 0}))})},applyOrderPromotion:r=>{t(o=>{o.selectedPromotion=r,o.workingOrder.promo_code=String(r.id)}),e().wipeItemPromos()},removeOrderPromotion:()=>{t(r=>{r.selectedPromotion=void 0,r.workingOrder.promo_code=void 0}),e().checkBestPromo()},overrideOrderPromotion:r=>{t(o=>{o.promoOverrideActive=!0}),r?e().applyOrderPromotion(r):(t(o=>{o.selectedPromotion=void 0,o.workingOrder.promo_code=void 0}),e().wipeItemPromos())}}))),{name:"cart",version:1,storage:MS(()=>wr()),skipHydration:_r,partialize:t=>({editingSourceOrder:t.editingSourceOrder,...up&&{workingOrder:t.workingOrder,selectedTip:t.selectedTip,deliveryFeeCents:t.deliveryFeeCents}})})),Z=$a;function dp(){let t=$a(o=>o.workingOrder),e=$a(o=>o.selectedPromotion),r=$a(o=>o.selectedTip??0);return $S(()=>{let{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}=bs(t,e,r);return{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}},[t,e,r])}import{create as XS}from"zustand";import{z as $}from"zod";function Ft(t){return(t/100).toLocaleString("en-US",{style:"currency",currency:"USD"})}var BS=$.object({email:$.email(),location_id:$.number().int().nullish()}),qS=$.object({notification_emails:$.array(BS).nullish(),minimum_notice_hours:$.number().int().nullish(),minimum_people_required:$.number().int().positive().nullish(),minimum_price:$.number().nonnegative().nullish(),does_cater:$.boolean().nullish(),preferred_time:$.string().regex(/^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/,"expected HH:mm:ss").nullish()}),VS=$.preprocess(t=>{if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(e.notification_email&&e.notification_emails==null){let{notification_email:r,...o}=e;return{...o,notification_emails:[{email:r,location_id:null}]}}}return t},qS),WS=$.object({does_deliver:$.boolean().nullish(),delivery_fee_cents:$.number().int().nullish(),max_delivery_radius_miles:$.number().nullish(),cents_per_mile:$.number().int().nullish()}),HS=$.object({key:$.string().min(1),enabled:$.boolean().default(!0),email:$.email().nullish(),label:$.string().nullish()}),zS=$.object({forms:$.array(HS).nullish()}),GS=$.object({is_active:$.boolean().nullish(),full_discount_at:$.number().int().positive().nullish(),maximum_percent_off:$.number().min(0).max(1).nullish()}),KS=$.object({key:$.string().min(1),label:$.string().min(1),description:$.string().nullish(),price_per_person_cents:$.number().int().nonnegative()}),JS=$.object({base_price_per_person_cents:$.number().int().nonnegative(),default_service_hours:$.number().int().positive(),additional_hour_rate_cents:$.number().int().nonnegative(),service_fee_percent:$.number().min(0).max(100),sales_tax_percent:$.number().min(0).max(100),minimum_booking_fee_cents:$.number().int().nonnegative(),date_hold_deposit_cents:$.number().int().nonnegative(),add_ons:$.array(KS).default([])}).refine(t=>new Set(t.add_ons.map(e=>e.key)).size===t.add_ons.length,{message:"add_on keys must be unique"}),YS={catering:VS,delivery:WS,contact:zS,catering_bulk_discount:GS,food_truck:JS};async function Xu(t,e,r=M){let{data:o}=await r.from("franchise_feature_config").select("config").eq("franchise_id",t).eq("feature",e).maybeSingle();return o?YS[e].parse(o.config):null}import{createJSONStorage as QS,devtools as ZS,persist as ex}from"zustand/middleware";var ft=null,rr=null,or=null,Ss=null;function tx(t){return typeof t=="number"?{franchiseId:t}:t??{}}function fp(){return Qu.getState().platform??"website"}var Qu=XS()(ex(ZS((t,e)=>({logLevel:3,location_id:void 0,franchiseId:void 0,franchiseCateringConfig:{does_cater:null,minimum_notice_hours:null,minimum_people_required:null,minimum_price:null},franchiseDeliveryConfig:{does_deliver:null,delivery_fee_cents:null,max_delivery_radius_miles:null,cents_per_mile:null},platform:"website",visibilityMode:"editor",lastUpdatedAt:new Date(0),setFranchiseId:r=>t({franchiseId:r}),remoteMenuLastUpdated:async()=>{let{data:r,error:o}=await M.from("items").select("updated_at").order("updated_at",{ascending:!1}).limit(1).single();if(o)throw e().logLevel<=2&&console.warn(o,"error getting menu last updated"),new Error("error getting menu last updated");return!r||!r.updated_at?new Date(0):new Date(r.updated_at)},start:async r=>{let o=tx(r),n=o.franchiseId??e().franchiseId??K.getState().franchiseId;if(e().logLevel<=1&&console.debug("starting menu manager"),!n){e().logLevel<=3&&console.warn("franchise id is not set, cannot start menu manager");return}t({franchiseId:n}),o.platform&&t({platform:o.platform}),e().refreshLocalMenu(),e().menuChangeListener(),e().promotionsChangeListener()},items:[],hydrate:({items:r,categories:o,rules:n,components:s})=>t({items:r??[],categories:o??[],rules:n??[],components:s??[]},!1,"hydrate"),setItems:r=>{t({items:r})},addItem:r=>{t({items:[...e().items,r]})},updateItem:r=>{t({items:e().items.map(o=>o.base_item_id===r.base_item_id?r:o)})},deleteItem:r=>{t({items:e().items.filter(o=>o.base_item_id!==r)})},addVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:[...n.variants,r]}:n)})},updateVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:n.variants.map(s=>s.item_id===r.item_id?r:s)}:n)})},deleteVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:n.variants.filter(s=>s.item_id!==r)}:n)})},categories:[],setCategories:r=>t({categories:r}),addCategory:r=>{t({categories:[...e().categories,r]})},updateCategory:r=>{t({categories:e().categories.map(o=>o.category_id===r.category_id?r:o)})},deleteCategory:r=>{t({categories:e().categories.filter(o=>o.category_id!==r)})},rules:[],setRules:r=>{t({rules:r})},addRule:r=>{t({rules:[...e().rules,r]})},updateRule:r=>{t({rules:e().rules.map(o=>o.rule_id===r.rule_id?r:o)})},deleteRule:r=>{t({rules:e().rules.filter(o=>o.rule_id!==r)})},components:[],setComponents:r=>{t({components:r})},addComponent:r=>{t({components:[...e().components,r]})},updateComponent:r=>{t({components:e().components.map(o=>o.id===r.id?r:o)})},deleteComponent:r=>{t({components:e().components.filter(o=>o.id!==r)})},isLocalMenuFresh:async()=>{let r=await e().remoteMenuLastUpdated(),o=e().lastUpdatedAt;return r>=o},refreshLocalMenu:async()=>{let r=e().franchiseId;if(!r){e().logLevel<=2&&console.warn("franchise id is not set, cannot refresh menu");return}let o=fp(),n=K.getState().selectedLocation?.location_id||0;e().logLevel<=1&&console.log("[MenuStore] refreshing menu:",{franchiseId:r,locationId:n,platform:o});let s=await yh(M,r,n,o),i=ys(we.getState().allPromotions,o,n||void 0,new Date);we.setState({activePromotions:i});let[a,l,u]=await Promise.all([ph(M,r,s),Xu(r,"catering"),Xu(r,"delivery")]),{items:c,categories:d,rules:f,components:m}=gh(a,i);t({items:c,categories:d,rules:f,components:m,franchiseCateringConfig:l??{},franchiseDeliveryConfig:u??{}},!1,"refreshLocalMenu"),Ss||(Ss=setInterval(()=>{let h=we.getState().allPromotions;if(!h.length)return;let g=fp(),y=K.getState().selectedLocation?.location_id??void 0,p=ys(h,g,y,new Date),b=we.getState().activePromotions;(p.length!==b.length||p.some((v,L)=>v.id!==b[L]?.id))&&e().refreshLocalMenu()},6e4)),t({lastUpdatedAt:new Date})},menuChangeListener:async()=>{let r=e().franchiseId;if(!r){e().logLevel<=2&&console.warn("[MenuStore] Cannot subscribe to menu changes without franchiseId");return}if(rr&&(clearTimeout(rr),rr=null),ft){try{ft.unsubscribe?.()}catch{}try{M.removeChannel?.(ft)}catch{}ft=null}let o=M.channel(`menu-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"items",filter:`franchise_id=eq.${r}`},()=>{e().refreshLocalMenu()});ft=o,o.subscribe(n=>{if(n==="SUBSCRIBED"){e().logLevel<=1&&console.log("[MenuStore] Subscribed to menu changes");return}if(n==="CLOSED"){e().logLevel<=1&&console.log(`[MenuStore] Subscription status: ${n}`);return}if(n!=="CHANNEL_ERROR"&&n!=="TIMED_OUT"){e().logLevel<=2&&console.warn(`[MenuStore] Subscription status: ${n}`);return}console.warn(`[MenuStore] Subscription status: ${n}. Reconnecting in 5s...`);try{ft?.unsubscribe?.()}catch{}try{M.removeChannel?.(ft)}catch{}ft=null,rr&&clearTimeout(rr),rr=setTimeout(()=>{e().menuChangeListener()},5e3)})},promotionsChangeListener:()=>{let r=e().franchiseId;if(!r)return;if(or){try{or.unsubscribe?.()}catch{}try{M.removeChannel?.(or)}catch{}or=null}or=M.channel(`promotions-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"promotions",filter:`franchise_id=eq.${r}`},async()=>{let{data:n}=await M.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",r);we.setState({allPromotions:n||[]}),e().refreshLocalMenu()}).subscribe()},cleanup:()=>{if(rr&&(clearTimeout(rr),rr=null),ft){try{ft.unsubscribe?.()}catch{}try{M.removeChannel?.(ft)}catch{}ft=null}if(or){try{or.unsubscribe?.()}catch{}try{M.removeChannel?.(or)}catch{}or=null}Ss&&(clearInterval(Ss),Ss=null)},setLastUpdatedAt:r=>t({lastUpdatedAt:r}),uploadMenuImage:async r=>{let o=K.getState().franchiseId;if(!o)throw e().logLevel<=2&&console.warn("[MenuStore] Cannot upload menu image without franchiseId"),new Error("franchise id is not set");let n=`franchise_id_${o}/menu-${Date.now()}`,{error:s}=await M.storage.from("menu-images").upload(n,r);if(s)throw s;return n}}),{name:"MenuStore"}),{name:"menu",onRehydrateStorage:()=>(t,e)=>{if(e||!t)return;let r=t.items;Qu.setState({items:r??[]})},storage:QS(()=>wr()),skipHydration:_r}));var $t=Qu;import{z as ve}from"zod";import{z as oo}from"zod";var Tt=t=>({schema:t,actionable:!0}),rx=t=>typeof t=="object"&&t!==null&&t.actionable===!0;function je(t,e){let r={};for(let[o,n]of Object.entries(e)){let s=`${t}.${o}`;r[o]=n instanceof oo.ZodType?{name:s,schema:n,actionable:!1}:rx(n)?{name:s,schema:n.schema,actionable:!0}:je(s,n)}return r}var ox=t=>typeof t=="object"&&t!==null&&"name"in t&&t.schema instanceof oo.ZodType;function Ba(t,e=[]){if(ox(t))return e.push(t),e;if(t&&typeof t=="object")for(let r of Object.values(t))Ba(r,e);return e}if(process.env.NODE_ENV!=="production"){let t=je("order",{placed:oo.object({orderId:oo.number()}),catering:{placed:Tt(oo.object({orderId:oo.number(),headcount:oo.number()}))}}),e=(r,o)=>{if(!r)throw new Error(`define.ts assert: ${o}`)};e(t.placed.name==="order.placed","leaf name"),e(t.catering.placed.name==="order.catering.placed","nested name"),e(t.placed.schema.safeParse({orderId:1}).success,"leaf schema parses"),e(t.catering.placed.schema.safeParse({orderId:1,headcount:2}).success,"marked schema parses"),e(t.placed.actionable===!1,"bare leaf is not actionable"),e(t.catering.placed.actionable===!0,"marked leaf is actionable"),e(Ba(t).length===2,"descriptorsIn walks nested"),console.log("define.ts ok")}import{z as H}from"zod";var no={franchiseId:H.number(),locationId:H.number()},en={placed:H.object({orderId:H.number(),...no,total:H.number(),itemCount:H.number().int()}),requested:H.object({orderId:H.number(),...no}),confirmed:H.object({orderId:H.number(),...no,via:H.enum(["pos","email_link","dashboard"]),userId:H.string().optional(),deviceId:H.number().optional()}),paid:H.object({orderId:H.number(),...no,paymentMethod:H.string()}),completed:H.object({orderId:H.number(),...no}),canceled:H.object({orderId:H.number(),...no,reason:H.string().nullable()})},mp=je("order",{...en,placed:Tt(en.placed),completed:Tt(en.completed),failed:H.object({orderId:H.number().nullable(),total:H.number(),reason:H.string(),phase:H.enum(["create","modify","refund","complete","kitchen_complete"]).optional()}),confirmation_email_sent:H.object({orderId:H.number(),recipient:H.string()}),realtime_disconnected:H.object({status:H.string(),location_id:H.number().nullable()}),catering:{...en,requested:Tt(en.requested),confirmed:Tt(en.confirmed),charge_failed:Tt(H.object({orderId:H.number(),...no,chargeId:H.number()}))}});import{z as nr}from"zod";var Zu={franchiseId:nr.number(),locationId:nr.number()},hp=je("inventory",{stock_changed:Tt(nr.object(Zu)),ingredient_added:Tt(nr.object({...Zu,locationIngredientId:nr.number(),ingredientName:nr.string()})),component_added:Tt(nr.object({...Zu,locationComponentId:nr.number(),componentName:nr.string()}))});import{z as Ae}from"zod";var pp=je("payment",{captured:Ae.object({orderId:Ae.number(),amount:Ae.number(),method:Ae.string()}),failed:Ae.object({orderId:Ae.number(),amount:Ae.number(),method:Ae.string(),reason:Ae.string(),phase:Ae.enum(["create_payment_intent","retrieve_payment_intent","collect_payment_method","confirm_payment_intent","unexpected"]).optional(),code:Ae.string().nullable().optional(),decline_code:Ae.string().nullable().optional(),payment_intent_id:Ae.string().nullable().optional()}),refunded:Ae.object({orderId:Ae.number(),amount:Ae.number(),method:Ae.string()})});import{z as B}from"zod";import{z as Re}from"zod";var gp=["healthy","degraded","unhealthy","offline"];function Ye(t,e){return{severity:t,detail:e}}function ec(t){let e=Object.fromEntries(Object.entries(t).map(([r,o])=>[r,Re.object({healthy:Re.boolean(),detail:(o.detail??Re.unknown()).optional()})]));return Re.object(e)}var tc={pos:{authenticated:Ye("critical"),menu_loaded:Ye("critical"),reader_connected:Ye("critical"),printer_connected:Ye("critical"),order_listener:Ye("critical"),battery_healthy:Ye("warning",Re.object({percentage:Re.number()}))},kiosk:{authenticated:Ye("critical"),menu_loaded:Ye("critical"),reader_connected:Ye("critical"),battery_healthy:Ye("warning",Re.object({percentage:Re.number()}))},kitchen_display:{authenticated:Ye("critical"),order_listener:Ye("critical"),battery_healthy:Ye("warning",Re.object({percentage:Re.number()}))}},_F=Re.discriminatedUnion("platform",[Re.object({platform:Re.literal("pos"),checks:ec(tc.pos)}),Re.object({platform:Re.literal("kiosk"),checks:ec(tc.kiosk)}),Re.object({platform:Re.literal("kitchen_display"),checks:ec(tc.kitchen_display)})]);var yp=B.enum(gp),bp=je("device",{status_changed:B.object({from:yp.nullable(),to:yp,reason:B.string().nullable()}),check_failed:B.object({check_key:B.string(),reason:B.string()}),check_recovered:B.object({check_key:B.string()}),auth_failed:B.object({phase:B.enum(["init","verify_403"]),reason:B.string()}),connection_error:B.object({reason:B.string()}),verified:B.object({device_id:B.number()}),printer_disconnected:B.object({printer_id:B.string(),reason:B.string()}),print_failed:B.object({printer_id:B.string().nullable(),job_type:B.string(),reason:B.string(),order_id:B.number().nullable(),timings:Ru}),print_succeeded:B.object({printer_id:B.string().nullable(),job_type:B.string(),order_id:B.number().nullable(),timings:Ru}),reader_connected:B.object({reader_serial:B.string().nullable()}),reader_disconnected:B.object({reader_serial:B.string().nullable(),reason:B.string()}),reader_connect_failed:B.object({reader_serial:B.string().nullable(),reason:B.string()}),order_received:B.object({orderId:B.number(),method_id:B.number().nullable()}),order_acknowledged:B.object({orderId:B.number(),method_id:B.number().nullable()})});import{z as ce}from"zod";var tn=je("api",{supabase_failed:ce.object({table:ce.string(),op:ce.string(),code:ce.string().nullable(),message:ce.string()}),unhandled:ce.object({message:ce.string(),where:ce.string().nullable()}),rate_limited:ce.object({path:ce.string(),method:ce.string(),retryAfterMs:ce.number().nullable()}),timeout:ce.object({path:ce.string(),method:ce.string(),durationMs:ce.number()}),log_invalid_payload:ce.object({event:ce.string(),issues:ce.string()}),log_enqueue_failed:ce.object({event:ce.string(),message:ce.string()})});import{z as oe}from"zod";var _p=oe.object({source:oe.string().optional(),medium:oe.string().optional(),campaign:oe.string().optional()}),sr=je("website",{session_started:oe.object({landing_page:oe.string(),referrer:oe.string().optional(),utm:_p.optional()}),session_ended:oe.object({duration_ms:oe.number(),pages_visited:oe.number()}),page_viewed:oe.object({path:oe.string(),referrer:oe.string().optional(),utm:_p.optional()}),page_exited:oe.object({path:oe.string(),duration_ms:oe.number()}),short_url_clicked:oe.object({slug:oe.string(),referrer:oe.string().optional(),run_id:oe.string().uuid().optional(),outbound_message_id:oe.string().uuid().optional(),strategy_id:oe.string().optional(),strategy_variant_id:oe.string().optional(),dry_run:oe.boolean().optional()})});import{z as xr}from"zod";var wp=je("integration",{pushed:xr.object({orderId:xr.number(),provider:xr.string(),externalId:xr.string()}),failed:xr.object({orderId:xr.number(),provider:xr.string(),reason:xr.string()})});var VF=new Set(Ba([mp,hp,pp,bp,tn,sr,wp]).filter(t=>t.actionable).map(t=>t.name));var XF=ve.object({id:ve.number(),created_at:ve.string(),severity:ve.enum(["debug","info","warn","error"]),event_name:ve.string(),source:ah,service:ve.string().nullable(),device_id:ve.number().nullable(),session_id:ve.string().nullable(),request_id:ve.string().nullable(),franchise_id:ve.number().nullable(),location_id:ve.number().nullable(),user_id:ve.string().nullable(),anonymous_id:ve.string().nullable(),customer_id:ve.number().nullable(),order_id:ve.number().nullable(),payload:ve.record(ve.string(),ve.unknown()),stack_trace:ve.string().nullable()}),nx=()=>({}),vp=null,QF=new Proxy({},{get(t,e){return vp?.[e]??(()=>{})}});function Sp(t){let{source:e,getContext:r=nx,dev:o=!1}=t,n=(i,a,l,u,c)=>{let d=a.schema.safeParse(l);if(!d.success){console.error(`[log] invalid payload for ${a.name}:`,d.error.issues),a.name!==tn.log_invalid_payload.name&&n("error",tn.log_invalid_payload,{event:a.name,issues:JSON.stringify(d.error.issues)});return}let f=r(),m=i==="error"?(u instanceof Error?u.stack:null)??new Error().stack??null:null;if(o){console.log(`[${i}] ${a.name}`,d.data);return}Ut("/events",{method:"POST",body:JSON.stringify({severity:i,event_name:a.name,source:e,session_id:f.session_id??null,request_id:c?.request_id??f.request_id??null,location_id:f.location_id??null,franchise_id:f.franchise_id??null,anonymous_id:f.anonymous_id??null,customer_id:f.customer_id??null,payload:d.data,stack_trace:m})}).then(h=>{h.ok||h.text().then(g=>console.error(`[log] POST /events ${h.status} for ${a.name}:`,g))}).catch(h=>{console.error(`[log] POST /events failed for ${a.name}:`,h)})},s={info:(i,a,l)=>n("info",i,a,void 0,l),warn:(i,a,l)=>n("warn",i,a,void 0,l),error:(i,a,l,u)=>n("error",i,a,l,u)};return vp=s,s}var so=class{diff(e,r,o={}){let n;typeof o=="function"?(n=o,o={}):"callback"in o&&(n=o.callback);let s=this.castInput(e,o),i=this.castInput(r,o),a=this.removeEmpty(this.tokenize(s,o)),l=this.removeEmpty(this.tokenize(i,o));return this.diffWithOptionsObj(a,l,o,n)}diffWithOptionsObj(e,r,o,n){var s;let i=b=>{if(b=this.postProcess(b,o),n){setTimeout(function(){n(b)},0);return}else return b},a=r.length,l=e.length,u=1,c=a+l;o.maxEditLength!=null&&(c=Math.min(c,o.maxEditLength));let d=(s=o.timeout)!==null&&s!==void 0?s:1/0,f=Date.now()+d,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],r,e,0,o);if(m[0].oldPos+1>=l&&h+1>=a)return i(this.buildValues(m[0].lastComponent,r,e));let g=-1/0,y=1/0,p=()=>{for(let b=Math.max(g,-u);b<=Math.min(y,u);b+=2){let _,v=m[b-1],L=m[b+1];v&&(m[b-1]=void 0);let x=!1;if(L){let X=L.oldPos-b;x=L&&0<=X&&X<a}let P=v&&v.oldPos+1<l;if(!x&&!P){m[b]=void 0;continue}if(!P||x&&v.oldPos<L.oldPos?_=this.addToPath(L,!0,!1,0,o):_=this.addToPath(v,!1,!0,1,o),h=this.extractCommon(_,r,e,b,o),_.oldPos+1>=l&&h+1>=a)return i(this.buildValues(_.lastComponent,r,e))||!0;m[b]=_,_.oldPos+1>=l&&(y=Math.min(y,b-1)),h+1>=a&&(g=Math.max(g,b+1))}u++};if(n)(function b(){setTimeout(function(){if(u>c||Date.now()>f)return n(void 0);p()||b()},0)})();else for(;u<=c&&Date.now()<=f;){let b=p();if(b)return b}}addToPath(e,r,o,n,s){let i=e.lastComponent;return i&&!s.oneChangePerToken&&i.added===r&&i.removed===o?{oldPos:e.oldPos+n,lastComponent:{count:i.count+1,added:r,removed:o,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+n,lastComponent:{count:1,added:r,removed:o,previousComponent:i}}}extractCommon(e,r,o,n,s){let i=r.length,a=o.length,l=e.oldPos,u=l-n,c=0;for(;u+1<i&&l+1<a&&this.equals(o[l+1],r[u+1],s);)u++,l++,c++,s.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return c&&!s.oneChangePerToken&&(e.lastComponent={count:c,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,u}equals(e,r,o){return o.comparator?o.comparator(e,r):e===r||!!o.ignoreCase&&e.toLowerCase()===r.toLowerCase()}removeEmpty(e){let r=[];for(let o=0;o<e.length;o++)e[o]&&r.push(e[o]);return r}castInput(e,r){return e}tokenize(e,r){return Array.from(e)}join(e){return e.join("")}postProcess(e,r){return e}get useLongestToken(){return!1}buildValues(e,r,o){let n=[],s;for(;e;)n.push(e),s=e.previousComponent,delete e.previousComponent,e=s;n.reverse();let i=n.length,a=0,l=0,u=0;for(;a<i;a++){let c=n[a];if(c.removed)c.value=this.join(o.slice(u,u+c.count)),u+=c.count;else{if(!c.added&&this.useLongestToken){let d=r.slice(l,l+c.count);d=d.map(function(f,m){let h=o[u+m];return h.length>f.length?h:f}),c.value=this.join(d)}else c.value=this.join(r.slice(l,l+c.count));l+=c.count,c.added||(u+=c.count)}}return n}};var rc=class extends so{constructor(){super(...arguments),this.tokenize=oc}equals(e,r,o){return o.ignoreWhitespace?((!o.newlineIsToken||!e.includes(`
|
|
153
|
+
`).or(u).order("sort_index",vr).order("rule_id",vr);if(h)throw h;return(m??[]).map(g=>({rule_id:g.rule_id,group_name:g.group_name,min_selection:g.min_selection,max_selection:g.max_selection,included_quantity:g.included_quantity,is_portionable:g.is_portionable,category_id:g.category_id,item_id:g.item_id,base_item_id:g.base_item_id,sort_index:g.sort_index??null,components:(g.rule_components??[]).map(y=>({component_id:y.component_id,upcharge_price:y.upcharge_price??0,name:y.components?.name??"",description:y.components?.description??void 0,serving_weight:y.components?.serving_weight??void 0,sort_index:y.sort_index??null,...n&&{behavior:y.component_quantity_behaviors??void 0}})).sort(Uu),items:(g.rule_items??[]).map(y=>({item_id:y.item_id,name:y.items?.name??"",description:y.items?.description??void 0,upcharge_price:y.upcharge_price??0,sort_index:y.sort_index??null,...n&&{behavior:y.component_quantity_behaviors??void 0}})).sort(Uu)}))}function Mu(t,e,r,o,n){let s={items:[],categories:[],rules:n,components:o};return s.items=e.map(i=>{let a=n.filter(c=>c.category_id===i.category_id),l=n.filter(c=>c.base_item_id===i.base_item_id),u=r.find(c=>c.category_id===i.category_id);return{...i,is_catering:u?.is_catering??!1,variants:t.filter(c=>c.base_item_id===i.base_item_id).map(c=>({...c,components:o.filter(d=>d.item_id===c.item_id),rules:[...a,...l,...n.filter(d=>d.item_id===c.item_id)]})),rules:l}}),s.categories=r.map(i=>({...i,rules:n.filter(a=>a.category_id===i.category_id)})),s}function ys(t,e,r,o=new Date){return t.filter(n=>{if(n.start_date&&new Date(n.start_date)>o||n.end_date&&new Date(n.end_date)<o||n.platforms&&n.platforms.length>0&&!n.platforms.includes(e)||!n.is_automatic)return!1;if(n.location_id!=null&&r!==void 0){if(n.location_id!==r)return!1}else if(n.location_id!=null&&r===void 0)return!1;if(n.schedule_details_json){let{interval:s,days:i,start_time:a,end_time:l}=n.schedule_details_json;if(s==="weekly"&&i&&!i.includes(Hi(o)+1))return!1;let u=xt(o);if(a&&We(o,Je(a,"HH:mm",u))||l&&jt(o,Je(l,"HH:mm",u)))return!1}return!0})}var Fu=null;function Sh(t){Fu=t}async function B0(){if(!Fu)throw new Error("apiFetch called before registerTokenProvider");return Fu()}async function Ut(t,e={}){let r=await B0(),o={...e.headers};return o["x-request-id"]||(o["x-request-id"]=gs()),fetch(`${Ri}${t}`,{...e,headers:{"Content-Type":"application/json",...r&&{Authorization:`Bearer ${r}`},...o}})}function Zt(t){let[e,r]=t.split("/").map(Number);return{index:e,divisions:r}}function Da(t){return t?1/Zt(t).divisions:1}function Xo(t,e){return e?`${t}@${e}`:t}function kt(t){let e=t.indexOf("@");return e===-1?{baseKey:t,portion:null}:{baseKey:t.slice(0,e),portion:t.slice(e+1)}}function Qj(t,e){return Math.ceil(t/e)}function Zj(t){let{min_divisions:e,max_divisions:r}=t;return Array.from({length:r-e+1},(o,n)=>e+n)}var q0={radial:{2:["Left","Right"],4:["Top left","Bottom left","Bottom right","Top right"]},grid:{2:["Left","Right"],4:["Top left","Bottom left","Top right","Bottom right"]},linear:{2:["First half","Second half"]},count:{2:["First half","Second half"]}};function eM(t,e){if(!t)return"Whole";let{index:r,divisions:o}=Zt(t);return q0[e.geometry][o]?.[r-1]??`Part ${r} of ${o}`}function kh(t,e,r){let o=e[t]??r,n=Object.entries(e).flatMap(([a,l])=>{let u=kt(a);return u.baseKey===t&&u.portion?[{portion:u.portion,value:l}]:[]});if(!n.length)return[{portion:null,value:o}];let{divisions:s}=Zt(n[0].portion),i=Array.from({length:s},(a,l)=>{let u=`${l+1}/${s}`;return{portion:u,value:n.find(c=>c.portion===u)?.value??o}});return i.every(a=>a.value===i[0].value)?[{portion:null,value:i[0].value}]:i}function $u(t){return t.reduce((e,r)=>e+Da(kt(r).portion),0)}function Th(t,e,r){let o=new Map,n=new Map;for(let s of t){let{baseKey:i,portion:a}=kt(s);n.has(i)||n.set(i,n.size),o.set(s,n.get(i)<r?0:Math.ceil(e(i)*Da(a)))}return o}function Ch(t,e){let{index:r,divisions:o}=Zt(t);if(o===e)return[t];if(e%o===0){let n=e/o,s=(r-1)*n+1;return Array.from({length:n},(i,a)=>`${s+a}/${e}`)}return o%e===0?[`${Math.ceil(r*e/o)}/${e}`]:null}function V0(t){if(!t)return"Whole";let{index:e,divisions:r}=Zt(t);return`Section ${e} of ${r}`}var W0={radial:"\u25CF",grid:"\u25A0",linear:"\u25A0",count:null},H0={radial:{2:["\u25D0","\u25D1"]},grid:{2:["\u25E7","\u25E8"]},linear:{2:["\u25E7","\u25E8"]},count:{}};function z0(t,e){if(!e)return null;if(!t)return W0[e];let{index:r,divisions:o}=Zt(t);return H0[e][o]?.[r-1]??null}function tM(t){let e=t.portion_scheme?.geometry,r=new Map,o=s=>{let i=s??"",a=r.get(i);return a||r.set(i,a={selections:[],removals:[],additions:[]}),a};for(let s of t.selections??[])for(let i of s.selections){let{selections:a}=o(i.portion),l=a.find(u=>u.rule_id===s.rule_id);l||a.push(l={...s,selections:[]}),l.selections.push(i)}for(let s of t.components??[])s.quantity_servings<=0?o(s.portion).removals.push(s):s.portion&&o(s.portion).additions.push(s);let n=s=>s?Zt(s).index:-1;return[...r.entries()].sort(([s],[i])=>n(s)-n(i)).map(([s,i])=>({portion:s||null,label:V0(s||null),glyph:z0(s||null,e),...i}))}var xh=t=>Math.round(t*100)/100;function rM(t,e,r=48){if(e===1)return`M 50 ${50-r} A ${r} ${r} 0 1 0 49.9 ${50-r} Z`;let o=2*Math.PI/e,n=-Math.PI/2-(t-1)*o,s=n-o,i=a=>`${xh(50+r*Math.cos(a))} ${xh(50+r*Math.sin(a))}`;return`M 50 50 L ${i(n)} A ${r} ${r} 0 ${o>Math.PI?1:0} 0 ${i(s)} Z`}function Eh(t,e){return t.map(r=>!e.discount_target_type||e.discount_target_type==="item"&&r.base_item_id!=null&&e.discount_target_ids?.includes(r.base_item_id)||e.discount_target_type==="item_variant"&&e.discount_target_ids?.includes(r.item_id)||e.discount_target_type==="category"&&e.discount_target_ids?.includes(r.category_id)?{...r,applied_promo_id:e.id}:r)}function Ph(t){switch(t){case 1:return"Kiosk";case 2:return"Website";case 3:return"POS";default:return""}}function Oh(t){let{max_selection:e,min_selection:r}=t,o=e!=null&&e!==1/0,n=t.included_quantity??0,s=o?r===e?`Choose ${r}`:r>0?`Choose ${r} to ${e}`:`Choose up to ${e}`:r>0?`Choose at least ${r}`:"Choose any";return n>0?`${s}. ${n} included`:s}function Bu(t,e,r,o){let n=o/2,s=Math.log(99)/(o-n),i=1/(1+Math.exp(-s*(e-n))),a=1/(1+Math.exp(s*n)),l=(i-a)/(1-a);return t*(1-r*l)}var G0=.06;var K0=.02,J0=.015;function Y0(t,e,r=!1){return e!==2?0:Math.floor(r?J0*t:K0*t)}function Sr(t,e=!1){let r=e?t.display_price||0:t.price||0,o=t.selections?.reduce((s,i)=>s+i.selections.reduce((a,l)=>a+l.upcharge,0),0)||0;return(r+o)*t.quantity}function Qo({order:t}){return t.items.filter(e=>e.status!=="removed").reduce((e,r)=>e+Sr(r),0)}function X0(t,e){let r=Qo({order:t}),{discount:o}=eS(t,e),n=r-o,s=tS(n),i=Y0(n,t.method_id,t.is_catering??!1),a=n+s+i;return{subtotal:r,tax:s,service_fee:i,discount:o,total:a}}function bs(t,e,r=0){let o=Q0(t.charges),{subtotal:n,discount:s,tax:i,service_fee:a,total:l}=o.length?Z0(o):X0(t,e);return{lines:t.items.filter(u=>u.status!=="removed").map(u=>({name:u.name,quantity:u.quantity,basePrice:u.price||0,unitPrice:Sr({...u,quantity:1}),lineTotal:Sr(u),perPerson:u.per_person,addOns:(u.selections??[]).flatMap(c=>c.selections.map(d=>({name:d.name,groupName:c.group_name,upcharge:d.upcharge})))})),subtotal:n,discount:s??0,tax:i,serviceFee:a??0,tip:r,total:l+r}}function Q0(t){return(t??[]).filter(e=>e.charge_status===1)}function Z0(t){return(Array.isArray(t)?t:[]).reduce((r,o)=>({subtotal:r.subtotal+o.subtotal,tax:r.tax+o.tax,tip:(r.tip||0)+(o.tip||0),discount:(r.discount||0)+(o.discount||0),service_fee:(r.service_fee||0)+(o.service_fee||0),total:r.total+o.total}),{subtotal:0,tax:0,tip:0,discount:0,service_fee:0,total:0})}function er(t,e,r){if(!e.method_id)throw new Error("Attach method_id to order to calculate promo discount.");if(!e.location_id)throw new Error("Attach location_id to order to calculate promo discount.");if(!t.is_active)return 0;let o=Ph(e.method_id).toLowerCase();if(t.platforms&&t.platforms.length>0&&!t.platforms.includes(o)||t.location_id&&t.location_id!==e.location_id||t.start_date&&We(r,new Date(t.start_date))||t.end_date&&jt(r,new Date(t.end_date)))return 0;if(t.schedule_details_json){let{interval:d,days:f,start_time:m,end_time:h}=t.schedule_details_json;if(d==="weekly"&&f&&!f.includes(Hi(r)+1))return 0;let g=xt(r);if(m){let y=Je(m,"HH:mm",g);if(We(r,y))return 0}if(h){let y=Je(h,"HH:mm",g);if(jt(r,y))return 0}}let n=e.is_catering||e.items.some(d=>d.is_catering);if(t.is_catering_only&&!n)return 0;let s=Qo({order:e});if(t.min_purchase_amount&&s<t.min_purchase_amount)return 0;let i=e.items.reduce((d,f)=>d+f.quantity,0),a=t.is_catering_only&&t.min_purchase_quantity;if(!a&&t.min_purchase_quantity&&i<t.min_purchase_quantity)return 0;let l=e.items,u=s;if(t.discount_target_type&&t.discount_target_ids?.length&&(l=e.items.filter(d=>t.discount_target_type==="category"?t.discount_target_ids.includes(d.category_id):t.discount_target_type==="item"?t.discount_target_ids.includes(d.base_item_id):t.discount_target_type==="item_variant"?t.discount_target_ids.includes(d.item_id):!1),u=l.reduce((d,f)=>d+Sr(f),0)),l.length===0)return 0;let c=0;if(a&&t.promotion_type_id===1){let d=l.reduce((m,h)=>m+h.quantity,0),f=Bu(u,d,t.discount_value/100,t.min_purchase_quantity);c=u-f}else t.promotion_type_id===1?c=u*(t.discount_value/100):t.promotion_type_id===2&&(c=t.discount_value);return Math.min(Math.floor(c),u)}function La(t){return t.is_automatic?t.discount_target_type?"item":"order":"private"}function Ah(t,e,r){if(!e.length)return{discount:0};let o,n=0;for(let u of e){if(La(u)!=="order")continue;let c=er(u,t,r);c>n&&(n=c,o=u)}let s=t.items.filter(u=>u.status!=="removed"),i=e.filter(u=>La(u)==="item"),a=[];i.length>0&&s.forEach((u,c)=>{let d=0,f;for(let m of i){let h={...t,items:[u]},g=er(m,h,r);g>d&&(d=g,f=m.id)}d>0&&f!==void 0&&a.push({itemIndex:c,itemId:u.item_id,promotionId:f,discount:d})});let l=a.reduce((u,c)=>u+c.discount,0);return n===0&&l===0?{discount:0}:n>=l?{discount:n,orderPromo:o}:{discount:l,itemDiscounts:a}}function eS(t,e,r=new Date){if(e)try{let n=er(e,t,r);return{name:e.name,discount:n}}catch{return{name:e.name,discount:0}}let o=t.items.reduce((n,s)=>n+(s.discount_amount??0),0);return o>0?{name:"Item discounts",discount:o}:{discount:0}}function tS(t){return Math.round(t*G0)}import{create as CS}from"zustand";function qu(t,e,r){let o=zi(),n=nS(t,r.timeZone,r.locale??o.locale);return"formatToParts"in n?rS(n,e):oS(n,e)}function rS(t,e){let r=t.formatToParts(e);for(let o=r.length-1;o>=0;--o)if(r[o].type==="timeZoneName")return r[o].value}function oS(t,e){let r=t.format(e).replace(/\u200E/g,""),o=/ [\w-+ ]+$/.exec(r);return o?o[0].substr(1):""}function nS(t,e,r){return new Intl.DateTimeFormat(r?[r.code,"en-US"]:void 0,{timeZone:e,timeZoneName:t})}function Ih(t,e){let r=uS(e);return"formatToParts"in r?iS(r,t):aS(r,t)}var sS={year:0,month:1,day:2,hour:3,minute:4,second:5};function iS(t,e){try{let r=t.formatToParts(e),o=[];for(let n=0;n<r.length;n++){let s=sS[r[n].type];s!==void 0&&(o[s]=parseInt(r[n].value,10))}return o}catch(r){if(r instanceof RangeError)return[NaN];throw r}}function aS(t,e){let r=t.format(e),o=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(r);return[parseInt(o[3],10),parseInt(o[1],10),parseInt(o[2],10),parseInt(o[4],10),parseInt(o[5],10),parseInt(o[6],10)]}var Vu={},Rh=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),lS=Rh==="06/25/2014, 00:00:00"||Rh==="\u200E06\u200E/\u200E25\u200E/\u200E2014\u200E \u200E00\u200E:\u200E00\u200E:\u200E00";function uS(t){return Vu[t]||(Vu[t]=lS?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})),Vu[t]}function _s(t,e,r,o,n,s,i){let a=new Date(0);return a.setUTCFullYear(t,e,r),a.setUTCHours(o,n,s,i),a}var Dh=36e5,cS=6e4,Wu={timezone:/([Z+-].*)$/,timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function tr(t,e,r){if(!t)return 0;let o=Wu.timezoneZ.exec(t);if(o)return 0;let n,s;if(o=Wu.timezoneHH.exec(t),o)return n=parseInt(o[1],10),Lh(n)?-(n*Dh):NaN;if(o=Wu.timezoneHHMM.exec(t),o){n=parseInt(o[2],10);let i=parseInt(o[3],10);return Lh(n,i)?(s=Math.abs(n)*Dh+i*cS,o[1]==="+"?-s:s):NaN}if(mS(t)){e=new Date(e||Date.now());let i=r?e:dS(e),a=Hu(i,t);return-(r?a:fS(e,a,t))}return NaN}function dS(t){return _s(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds())}function Hu(t,e){let r=Ih(t,e),o=_s(r[0],r[1]-1,r[2],r[3]%24,r[4],r[5],0).getTime(),n=t.getTime(),s=n%1e3;return n-=s>=0?s:1e3+s,o-n}function fS(t,e,r){let n=t.getTime()-e,s=Hu(new Date(n),r);if(e===s)return e;n-=s-e;let i=Hu(new Date(n),r);return s===i?s:Math.max(s,i)}function Lh(t,e){return-23<=t&&t<=23&&(e==null||0<=e&&e<=59)}var Nh={};function mS(t){if(Nh[t])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:t}),Nh[t]=!0,!0}catch{return!1}}var hS=60*1e3,Mh={X:function(t,e,r){let o=zu(r.timeZone,t);if(o===0)return"Z";switch(e){case"X":return jh(o);case"XXXX":case"XX":return Zo(o);default:return Zo(o,":")}},x:function(t,e,r){let o=zu(r.timeZone,t);switch(e){case"x":return jh(o);case"xxxx":case"xx":return Zo(o);default:return Zo(o,":")}},O:function(t,e,r){let o=zu(r.timeZone,t);switch(e){case"O":case"OO":case"OOO":return"GMT"+pS(o,":");default:return"GMT"+Zo(o,":")}},z:function(t,e,r){switch(e){case"z":case"zz":case"zzz":return qu("short",t,r);default:return qu("long",t,r)}}};function zu(t,e){let r=t?tr(t,e,!0)/hS:e?.getTimezoneOffset()??0;if(Number.isNaN(r))throw new RangeError("Invalid time zone specified: "+t);return r}function Na(t,e){let r=t<0?"-":"",o=Math.abs(t).toString();for(;o.length<e;)o="0"+o;return r+o}function Zo(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Na(Math.floor(o/60),2),s=Na(Math.floor(o%60),2);return r+n+e+s}function jh(t,e){return t%60===0?(t>0?"-":"+")+Na(Math.abs(t)/60,2):Zo(t,e)}function pS(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Math.floor(o/60),s=o%60;return s===0?r+String(n):r+String(n)+e+Na(s,2)}function Gu(t){let e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),+t-+e}var ja=/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/;var Ku=36e5,Uh=6e4,gS=2,Fe={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,plainTime:/:/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:ja};function dt(t,e={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(t===null)return new Date(NaN);let r=e.additionalDigits==null?gS:Number(e.additionalDigits);if(r!==2&&r!==1&&r!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]")return new Date(t.getTime());if(typeof t=="number"||Object.prototype.toString.call(t)==="[object Number]")return new Date(t);if(Object.prototype.toString.call(t)!=="[object String]")return new Date(NaN);let o=yS(t),{year:n,restDateString:s}=bS(o.date,r),i=_S(s,n);if(i===null||isNaN(i.getTime()))return new Date(NaN);if(i){let a=i.getTime(),l=0,u;if(o.time&&(l=wS(o.time),l===null||isNaN(l)))return new Date(NaN);if(o.timeZone||e.timeZone){if(u=tr(o.timeZone||e.timeZone,new Date(a+l)),isNaN(u))return new Date(NaN)}else u=Gu(new Date(a+l)),u=Gu(new Date(a+l+u));return new Date(a+l+u)}else return new Date(NaN)}function yS(t){let e={},r=Fe.dateTimePattern.exec(t),o;if(r?(e.date=r[1],o=r[3]):(r=Fe.datePattern.exec(t),r?(e.date=r[1],o=r[2]):(e.date=null,o=t)),o){let n=Fe.timeZone.exec(o);n?(e.time=o.replace(n[1],""),e.timeZone=n[1].trim()):e.time=o}return e}function bS(t,e){if(t){let r=Fe.YYY[e],o=Fe.YYYYY[e],n=Fe.YYYY.exec(t)||o.exec(t);if(n){let s=n[1];return{year:parseInt(s,10),restDateString:t.slice(s.length)}}if(n=Fe.YY.exec(t)||r.exec(t),n){let s=n[1];return{year:parseInt(s,10)*100,restDateString:t.slice(s.length)}}}return{year:null}}function _S(t,e){if(e===null)return null;let r,o,n;if(!t||!t.length)return r=new Date(0),r.setUTCFullYear(e),r;let s=Fe.MM.exec(t);if(s)return r=new Date(0),o=parseInt(s[1],10)-1,$h(e,o)?(r.setUTCFullYear(e,o),r):new Date(NaN);if(s=Fe.DDD.exec(t),s){r=new Date(0);let i=parseInt(s[1],10);return xS(e,i)?(r.setUTCFullYear(e,0,i),r):new Date(NaN)}if(s=Fe.MMDD.exec(t),s){r=new Date(0),o=parseInt(s[1],10)-1;let i=parseInt(s[2],10);return $h(e,o,i)?(r.setUTCFullYear(e,o,i),r):new Date(NaN)}if(s=Fe.Www.exec(t),s)return n=parseInt(s[1],10)-1,Bh(n)?Fh(e,n):new Date(NaN);if(s=Fe.WwwD.exec(t),s){n=parseInt(s[1],10)-1;let i=parseInt(s[2],10)-1;return Bh(n,i)?Fh(e,n,i):new Date(NaN)}return null}function wS(t){let e,r,o=Fe.HH.exec(t);if(o)return e=parseFloat(o[1].replace(",",".")),Ju(e)?e%24*Ku:NaN;if(o=Fe.HHMM.exec(t),o)return e=parseInt(o[1],10),r=parseFloat(o[2].replace(",",".")),Ju(e,r)?e%24*Ku+r*Uh:NaN;if(o=Fe.HHMMSS.exec(t),o){e=parseInt(o[1],10),r=parseInt(o[2],10);let n=parseFloat(o[3].replace(",","."));return Ju(e,r,n)?e%24*Ku+r*Uh+n*1e3:NaN}return null}function Fh(t,e,r){e=e||0,r=r||0;let o=new Date(0);o.setUTCFullYear(t,0,4);let n=o.getUTCDay()||7,s=e*7+r+1-n;return o.setUTCDate(o.getUTCDate()+s),o}var vS=[31,28,31,30,31,30,31,31,30,31,30,31],SS=[31,29,31,30,31,30,31,31,30,31,30,31];function qh(t){return t%400===0||t%4===0&&t%100!==0}function $h(t,e,r){if(e<0||e>11)return!1;if(r!=null){if(r<1)return!1;let o=qh(t);if(o&&r>SS[e]||!o&&r>vS[e])return!1}return!0}function xS(t,e){if(e<1)return!1;let r=qh(t);return!(r&&e>366||!r&&e>365)}function Bh(t,e){return!(t<0||t>52||e!=null&&(e<0||e>6))}function Ju(t,e,r){return!(t<0||t>=25||e!=null&&(e<0||e>=60)||r!=null&&(r<0||r>=60))}var kS=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function Yu(t,e,r={}){e=String(e);let o=e.match(kS);if(o){let n=dt(r.originalDate||t,r);e=o.reduce(function(s,i){if(i[0]==="'")return s;let a=s.indexOf(i),l=s[a-1]==="'",u=s.replace(i,"'"+Mh[i[0]](n,i,r)+"'");return l?u.substring(0,a-1)+u.substring(a+1):u},e)}return Ue(t,e,r)}function ws(t,e,r){t=dt(t,r);let o=tr(e,t,!0),n=new Date(t.getTime()-o),s=new Date(0);return s.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),s.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),s}function Ma(t,e,r,o){return o={...o,timeZone:e,originalDate:t},Yu(ws(t,e,{timeZone:o.timeZone}),r,o)}function Xu(t,e,r){if(typeof t=="string"&&!t.match(ja))return dt(t,{...r,timeZone:e});t=dt(t,r);let o=_s(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()).getTime(),n=tr(e,new Date(o));return new Date(o+n)}var Ua="America/New_York",TS=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function Vh(t){return t.replace(/[+-].*$/,"").trim().slice(0,5)}function Wh(t,e,r=0){let o=new Date(`${Ma(t,Ua,"yyyy-MM-dd")}T12:00:00Z`);o.setUTCDate(o.getUTCDate()+r);let n=o.toISOString().slice(0,10),s=TS[o.getUTCDay()],i=e[`${s}_open`],a=e[`${s}_close`];if(!i||!a)return null;let l=dt(`${n}T${Vh(i)}`,{timeZone:Ua}),u=dt(`${n}T${Vh(a)}`,{timeZone:Ua});return u<=l&&(u=new Date(u.getTime()+1440*60*1e3)),{day:s,open:l,close:u}}function Qu(t,e){if(e.force_close)return!0;for(let r of[-1,0]){let o=Wh(t,e,r);if(o&&!We(t,o.open)&&We(t,o.close))return!1}return!0}import{devtools as ES,persist as PS,createJSONStorage as OS,subscribeWithSelector as AS}from"zustand/middleware";async function Hh(t,e){let r=e||M,{data:o,error:n}=await r.from("permissions").select("franchise_id, location_ids, portal_role").eq("user_id",t);if(n)throw n;if(o?.some(f=>f.portal_role==="admin")){let[f,m]=await Promise.all([r.from("franchises").select("*").throwOnError(),r.from("locations").select("*").throwOnError()]);return{franchises:f.data,locations:m.data}}let s=new Set(o?.map(f=>f.franchise_id).filter(f=>f!=null)??[]),i=new Set(o?.filter(f=>!f.location_ids?.length&&f.franchise_id!==null).map(f=>f.franchise_id)),a=o?.flatMap(f=>f.location_ids??[])??[],{data:l,error:u}=await r.from("franchises").select("*").in("franchise_id",Array.from(s));if(u)throw u;let{data:c,error:d}=await r.from("locations").select("*").or(`location_id.in.(${a.join(",")}), franchise_id.in.(${Array.from(i).join(",")})`);if(d)throw d;return{franchises:l,locations:c}}async function zh(t,e){let r=e||M,{data:o,error:n}=await r.from("franchises").select("*").eq("franchise_id",t);if(n)throw n;let{data:s,error:i}=await r.from("locations").select("*").eq("franchise_id",t).or("status.is.null,status.neq.permanently_closed");if(i)throw i;return{franchises:o,locations:s}}async function Gh(t,e,r){let o=r||M,n={...e,...t},{data:s,error:i}=await o.from("locations").update(n).eq("location_id",e.location_id).select().single();if(i)throw i;return s}async function Kh(t,e,r){let o=r||M,{data:n,error:s}=await o.from("locations").update({force_close:e}).eq("location_id",t);if(s)throw s;return n}async function Jh(t,e){let r=e||M,{data:o,error:n}=await r.from("locations").insert(t).select().single();if(n)throw n;return o}async function Yh(t,e){let r=e||M,{data:o,error:n}=await r.from("locations").delete().eq("location_id",t);if(n)throw n;return o}async function Xh(t,e,r){let o=r||M,n={...t,...e},{data:s,error:i}=await o.from("franchises").update(n).eq("franchise_id",t.franchise_id).select().single();if(i)throw i;return s}function Qh(t){try{let e=(t.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")))}catch{return{}}}var vs=CS()(AS(PS(ES((t,e)=>({selectedLocation:null,franchises:[],locations:[],userId:null,navScope:"franchise",initialize:async({userId:r,token:o,locationId:n})=>{if(r&&t({userId:r}),n){let{data:a}=await M.from("locations").select("*").eq("location_id",n).throwOnError().single(),{data:l}=await M.from("franchises").select("*").eq("franchise_id",a.franchise_id).throwOnError().single();t({selectedLocation:a,franchiseId:a.franchise_id,locations:[a],franchises:[l]});return}else if(o){let l=Qh(o).franchise_ids?.[0],{locations:u,franchises:c}=await zh(l),d=e().selectedLocation,f=d?u.find(m=>m.location_id===d.location_id)??null:null;t({locations:u,franchises:c,franchiseId:l,selectedLocation:f});return}else if(r){let{locations:a,franchises:l}=await Hh(r);t({locations:a,franchises:l})}let i=e().locations[0];t({selectedLocation:i,...i&&{franchiseId:i.franchise_id}})},hydrate:({franchises:r,locations:o})=>t({franchises:r??[],locations:o??[]},!1,"hydrate"),getCurrentLocation:()=>e().selectedLocation,getIsCurrentLocationOpen:()=>{let r=e().selectedLocation;return r?!Qu(new Date,r):!1},getAllLocations:()=>e().locations,setForceClose:async(r,o)=>{await Kh(o,r),t(n=>({locations:n.locations.map(s=>s.location_id===o?{...s,force_close:r}:s),selectedLocation:n.selectedLocation?.location_id===o?{...n.selectedLocation,force_close:r}:n.selectedLocation}))},setSelectedLocation:r=>{t({selectedLocation:r}),t({franchiseId:r.franchise_id})},setFranchiseId:r=>{if(t({franchiseId:r}),e().selectedLocation?.franchise_id!==r){let o=e().locations.find(n=>n.franchise_id===r&&n.location_id!==0)??e().locations.find(n=>n.franchise_id===r)??null;t({selectedLocation:o})}},enterFranchise:r=>{let o=e();if(t({franchiseId:r,navScope:"franchise"}),o.selectedLocation?.franchise_id!==r){let n=o.locations.find(s=>s.franchise_id===r&&s.location_id!==0)??o.locations.find(s=>s.franchise_id===r)??null;t({selectedLocation:n})}},enterLocation:r=>{t({selectedLocation:r,franchiseId:r.franchise_id,navScope:"location"})},exitToFranchise:()=>{t({navScope:"franchise"})},exitToAccount:()=>{t({navScope:"account"})},updateLocation:async(r,o)=>{await Gh(r,o),t(n=>({locations:n.locations.map(s=>s.location_id===o.location_id?{...s,...r}:s)}))},createLocation:async r=>{let o=await Jh(r);return t(n=>({locations:[...n.locations,o]})),o},deleteLocation:async r=>{await Yh(r),t(o=>({locations:o.locations.filter(n=>n.location_id!==r)}))},updateFranchise:async(r,o)=>{let n=await Xh(r,o);return t(s=>({franchises:s.franchises.map(i=>i.franchise_id===r.franchise_id?n:i)})),n}})),{name:"location",version:3,migrate:(t,e)=>{let r=t??{};return e<3?{...r,navScope:r.navScope??"franchise",franchiseId:r.franchiseId??r.selectedLocation?.franchise_id}:r},storage:OS(()=>wr()),skipHydration:_r,partialize:t=>({selectedLocation:t.selectedLocation,franchises:t.franchises,locations:t.locations,userId:t.userId,franchiseId:t.franchiseId,navScope:t.navScope})}))),K=vs;import{create as RS}from"zustand";import{immer as IS}from"zustand/middleware/immer";import{devtools as DS}from"zustand/middleware";async function Zh(t){let{data:e,error:r}=await M.from("promotions").select("*").eq("franchise_id",t);if(r)throw r;return e}async function ep(t,e="website",r){let{data:o,error:n}=await M.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",t);if(n)throw n;let s=ys(o,e,r);return{all:o,active:s}}async function tp(t,e){let{data:r,error:o}=await M.from("promotions").select("*").eq("promo_code",t).eq("franchise_id",e).eq("is_active",!0).single();return o||!r?null:r}async function rp(t){let{data:e,error:r}=await M.from("promotions").insert(t).select("*").single();if(r)throw r;return e}async function op(t){let{data:e,error:r}=await M.from("promotions").update(t).eq("id",t.id).select("*").single();if(r)throw r;return e}async function np(t){let{data:e,error:r}=await M.from("promotions").delete().eq("id",t).select("*").single();if(r)throw r;e||console.log("No promotion deleted")}async function sp(t){let{data:e,error:r}=await M.from("franchise_marketing").select("personal_marketer").eq("franchise_id",t).maybeSingle();if(r)throw r;return e?.personal_marketer??!1}async function ip(t,e){let{error:r}=await M.from("franchise_marketing").upsert({franchise_id:t,personal_marketer:e},{onConflict:"franchise_id"});if(r)throw r;let{error:o}=await M.from("agent_skill_config").upsert({franchise_id:t,skill_id:"personal-marketer",enabled:e,updated_at:new Date().toISOString()},{onConflict:"franchise_id,skill_id"});if(o)throw o}async function ap(t,e=10){let{data:r,error:o}=await M.from("personal_marketer_runs").select("*").eq("franchise_id",t).order("created_at",{ascending:!1}).limit(e);if(o)throw o;return r}var LS=RS()(DS(IS((t,e)=>({logLevel:1,promotions:[],allPromotions:[],activePromotions:[],personalMarketerEnabled:!1,recentRuns:[],recentOutboundMessages:[],getPromotions:async r=>{let o=await Zh(r);return t({promotions:o},!1,"getPromotions"),o},getActivePromotions:async(r,o,n="website")=>{let{active:s,all:i}=await ep(r,n,o);return t({allPromotions:i,activePromotions:s},!1,"getActivePromotions"),s},getPromotionByCode:async(r,o)=>await tp(r,o),addPromotion:async r=>{let o=await rp(r);t(n=>{n.promotions.push(o)})},updatePromotion:async r=>{let o=await op(r);t(n=>{n.promotions=n.promotions.map(s=>s.id===o.id?o:s)})},deletePromotion:async r=>{await np(r),t(o=>{o.promotions=o.promotions.filter(n=>n.id!==r)})},getPersonalMarketerSettings:async()=>{let r=vs.getState().franchiseId;if(!r){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}let o=await sp(r);t({personalMarketerEnabled:o},!1,"getPersonalMarketerSettings")},setPersonalMarketerEnabled:async r=>{let o=vs.getState().selectedLocation?.franchise_id;if(!o){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}await ip(o,r),t({personalMarketerEnabled:r},!1,"setPersonalMarketerEnabled")},getRecentRuns:async(r=10)=>{let o=vs.getState().franchiseId;if(!o)return e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found"),[];let n=await ap(o,r);return t({recentRuns:n},!1,"getRecentRuns"),n},createBlastRun:async(r,o)=>{let n=await Ut("/marketing/create-run",{method:"POST",body:JSON.stringify({franchiseId:r,source:"blast",strategyId:"promotionalBlast",promotionId:o,dryRun:!1})});if(!n.ok){let i=await n.json().catch(()=>({}));throw new Error(i?.error??`HTTP ${n.status}`)}let{run:s}=await n.json();return await e().getRecentRuns(),s}})),{name:"PromotionStore"})),we=LS;var cp=yn(up(),1);import{useMemo as $S}from"react";function Fa(t){return t===2?2:1}var dp=!1;function fp(){dp=!0}var $a=NS()(FS(US(jS((t,e)=>({deliveryFeeCents:0,workingOrder:{time_placed:new Date,time_requested:void 0,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},location_id:K.getState().selectedLocation?.location_id||0,order_status:1,method_id:1,order_id:0,type_id:1,items:[],promo_code:void 0,charges:[],table_number:void 0},status:"idle",editingSourceOrder:null,promoOverrideActive:!1,addItem:(r,o)=>{let n=r;if(o){t(a=>{a.promoOverrideActive=!0,a.selectedPromotion=void 0,a.workingOrder.promo_code=void 0});let s=e().workingOrder.location_id,i=er(o,{items:[r],location_id:s,method_id:3},new Date);n={...r,applied_promo_id:o.id,discount_amount:i>0?i:void 0}}t(s=>{s.workingOrder.items.push(n),n.is_catering&&(s.workingOrder.is_catering=!0),s.status!=="editing"&&(s.workingOrder.order_id=0)}),e().checkBestPromo()},setTip:r=>t(o=>{o.selectedTip=r}),removeItem:r=>{t(o=>{o.workingOrder.items.splice(r,1),o.status!=="editing"&&(o.workingOrder.order_id=0)}),e().checkBestPromo()},updateItem:(r,o,n)=>{let s=r;if(n!==void 0)if(t(i=>{i.promoOverrideActive=!0,n&&(i.selectedPromotion=void 0,i.workingOrder.promo_code=void 0)}),n){let i=e().workingOrder.location_id,a=er(n,{items:[r],location_id:i,method_id:3},new Date);s={...r,applied_promo_id:n.id,discount_amount:a>0?a:void 0}}else s={...r,applied_promo_id:void 0,discount_amount:void 0};t(i=>{i.workingOrder.items[o]=s,i.status!=="editing"&&(i.workingOrder.order_id=0)}),e().checkBestPromo()},setCustomer:r=>t(o=>{o.workingOrder.customer=r}),getAnonCustomer:()=>({customer_id:0,first_name:"Customer",last_name:"Customer",phone:"0"}),setCart:r=>t(o=>{o.workingOrder=r}),createCustomer:async()=>{let r=e().workingOrder.customer,{data:o,error:n}=await M.from("customers").insert({first_name:r.first_name,last_name:r.last_name,email:r.email,phone_number:parseInt(r.phone)}).select("*").single();return n?(console.log("Error creating customer:",n),null):(console.log("customer created",o),o)},setLocationId:r=>t(o=>{o.workingOrder.location_id=r}),setOrderType:r=>t(o=>{o.workingOrder.type_id=Fa(r)}),setTableNumber:r=>t(o=>{o.workingOrder.table_number=r}),setTimeRequested:r=>t(o=>{o.workingOrder.time_requested=r}),applyCateringPreflight:r=>t(o=>{if(o.workingOrder.type_id=r.type_id,o.workingOrder.location_id=r.location_id,o.workingOrder.time_requested=r.time_requested,r.type_id===ds.ORDER_TYPE.DELIVERY){let n=r.delivery_address?.trim();o.workingOrder.delivery_address=n&&n.length>0?n:void 0}else o.workingOrder.delivery_address=void 0}),clearCateringSchedule:()=>t(r=>{r.workingOrder.time_requested=void 0}),setDeliveryFee:r=>t(o=>{o.deliveryFeeCents=r}),setPromoCode:r=>t(o=>{o.workingOrder.promo_code=r}),resetOrder:()=>t(r=>({workingOrder:{...r.workingOrder,order_id:0,location_id:K.getState().selectedLocation?.location_id??0,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},items:[],promo_code:void 0,type_id:1,is_catering:!1,time_requested:void 0,delivery_address:void 0,table_number:void 0},selectedTip:void 0,deliveryFeeCents:0})),setOrder:r=>t(o=>{o.workingOrder={...r,type_id:Fa(r.type_id)}}),startEdit:r=>t(o=>{let n={...r,type_id:Fa(r.type_id),charges:r.charges??[]};o.workingOrder=n,o.editingSourceOrder=n,o.status="editing",o.selectedTip=void 0;let s=Number(r.promo_code);o.selectedPromotion=s?we.getState().activePromotions.find(i=>i.id===s):void 0,o.promoOverrideActive=!!o.selectedPromotion}),cancelEdit:(r=!0)=>t(o=>{o.status="idle",o.editingSourceOrder=null,o.selectedTip=void 0,o.selectedPromotion=void 0,o.promoOverrideActive=!1,r&&(o.workingOrder={...o.workingOrder,location_id:K.getState().selectedLocation?.location_id??0,type_id:1,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},order_status:1,order_id:0,items:[],promo_code:void 0,charges:[],revision:void 0,updated_at:void 0,table_number:void 0})}),finishEdit:()=>t(r=>({workingOrder:{...r.workingOrder,location_id:K.getState().selectedLocation?.location_id??0,type_id:1,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},order_status:1,order_id:0,items:[],promo_code:void 0,charges:[],revision:void 0,updated_at:void 0,table_number:void 0},status:"idle",editingSourceOrder:null,selectedTip:void 0,selectedPromotion:void 0,promoOverrideActive:!1})),hasMeaningfulEditChanges:()=>{let{status:r,editingSourceOrder:o,workingOrder:n}=e();return r!=="editing"||!o?!1:!(0,cp.default)(o.items,n.items)},getOrderTotal:()=>Qo({order:e().workingOrder}),setCartFromURL:async(r,o)=>{try{let n={"Content-Type":"application/json",...o?{"X-Zorgo-Api-Key":o}:{}},s=await fetch(`${Ri}/s/${r}`,{headers:n});if(!s.ok)return!1;let{cart_data:i,promotion_id:a}=await s.json();return i?(t(l=>{if(l.workingOrder={...l.workingOrder,...i,type_id:Fa(i.type_id),order_id:0,order_status:1},l.workingOrder.time_requested=void 0,!a||i?.promo_code||i?.items?.some(d=>d.applied_promo_id))return;let c=we.getState().activePromotions.find(d=>d.id===a);if(!c){l.workingOrder.promo_code=String(a);return}if(c.promo_code){l.workingOrder.promo_code=c.promo_code;return}l.workingOrder.items=Eh(l.workingOrder.items,c)}),e().checkBestPromo(),!0):!1}catch(n){return console.error("[CartStore] setCartFromURL failed:",n),!1}},dismissPromo:r=>{t(o=>{o.dismissedPromoIds=[...o.dismissedPromoIds||[],r]})},checkBestPromo:()=>{if(e().promoOverrideActive)return;let{workingOrder:r}=e();if(!r.location_id||!r.method_id)return;let o=we.getState().activePromotions,n=new Date,s=e().selectedPromotion;if(s&&La(s)==="private")return;let i=s?er(s,r,n):0;if(s&&i===0){e().removeOrderPromotion();return}let a=Ah(r,o,n);if(s){a.orderPromo&&a.orderPromo.id!==s.id&&a.discount>i&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo);return}if(a.itemDiscounts?.length?t(u=>{for(let c of u.workingOrder.items)c.display_price=void 0,c.applied_promo_id=void 0,c.discount_amount=void 0;for(let c of a.itemDiscounts){let d=u.workingOrder.items[c.itemIndex];d&&(d.applied_promo_id=c.promotionId,d.discount_amount=c.discount,d.display_price=d.price-Math.round(c.discount/d.quantity))}}):e().wipeItemPromos(),a.discount===0||!a.orderPromo)return;let l=e().workingOrder.items.reduce((u,c)=>u+(c.discount_amount??0),0);l===0?e().applyOrderPromotion(a.orderPromo):a.discount>l&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo)},setOnBestPromoChange:r=>{t(o=>(o.onBestPromoChange=r,o))},wipeItemPromos:()=>{t(r=>{r.workingOrder.items=r.workingOrder.items.map(o=>({...o,display_price:void 0,applied_promo_id:void 0,discount_amount:void 0}))})},applyOrderPromotion:r=>{t(o=>{o.selectedPromotion=r,o.workingOrder.promo_code=String(r.id)}),e().wipeItemPromos()},removeOrderPromotion:()=>{t(r=>{r.selectedPromotion=void 0,r.workingOrder.promo_code=void 0}),e().checkBestPromo()},overrideOrderPromotion:r=>{t(o=>{o.promoOverrideActive=!0}),r?e().applyOrderPromotion(r):(t(o=>{o.selectedPromotion=void 0,o.workingOrder.promo_code=void 0}),e().wipeItemPromos())}}))),{name:"cart",version:1,storage:MS(()=>wr()),skipHydration:_r,partialize:t=>({editingSourceOrder:t.editingSourceOrder,...dp&&{workingOrder:t.workingOrder,selectedTip:t.selectedTip,deliveryFeeCents:t.deliveryFeeCents}})})),Z=$a;function mp(){let t=$a(o=>o.workingOrder),e=$a(o=>o.selectedPromotion),r=$a(o=>o.selectedTip??0);return $S(()=>{let{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}=bs(t,e,r);return{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}},[t,e,r])}import{create as XS}from"zustand";import{z as $}from"zod";function Ft(t){return(t/100).toLocaleString("en-US",{style:"currency",currency:"USD"})}function Ba(t){return`${t.quantity} guests \xD7 ${Ft(t.unitPrice)}/person`}function qa(t,e){return t.upcharge<=0?"included":`+${Ft(t.upcharge)}${e?"/person":""}`}var BS=$.object({email:$.email(),location_id:$.number().int().nullish()}),qS=$.object({notification_emails:$.array(BS).nullish(),minimum_notice_hours:$.number().int().nullish(),minimum_people_required:$.number().int().positive().nullish(),minimum_price:$.number().nonnegative().nullish(),does_cater:$.boolean().nullish(),preferred_time:$.string().regex(/^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/,"expected HH:mm:ss").nullish()}),VS=$.preprocess(t=>{if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(e.notification_email&&e.notification_emails==null){let{notification_email:r,...o}=e;return{...o,notification_emails:[{email:r,location_id:null}]}}}return t},qS),WS=$.object({does_deliver:$.boolean().nullish(),delivery_fee_cents:$.number().int().nullish(),max_delivery_radius_miles:$.number().nullish(),cents_per_mile:$.number().int().nullish()}),HS=$.object({key:$.string().min(1),enabled:$.boolean().default(!0),email:$.email().nullish(),label:$.string().nullish()}),zS=$.object({forms:$.array(HS).nullish()}),GS=$.object({is_active:$.boolean().nullish(),full_discount_at:$.number().int().positive().nullish(),maximum_percent_off:$.number().min(0).max(1).nullish()}),KS=$.object({key:$.string().min(1),label:$.string().min(1),description:$.string().nullish(),price_per_person_cents:$.number().int().nonnegative()}),JS=$.object({base_price_per_person_cents:$.number().int().nonnegative(),default_service_hours:$.number().int().positive(),additional_hour_rate_cents:$.number().int().nonnegative(),service_fee_percent:$.number().min(0).max(100),sales_tax_percent:$.number().min(0).max(100),minimum_booking_fee_cents:$.number().int().nonnegative(),date_hold_deposit_cents:$.number().int().nonnegative(),add_ons:$.array(KS).default([])}).refine(t=>new Set(t.add_ons.map(e=>e.key)).size===t.add_ons.length,{message:"add_on keys must be unique"}),YS={catering:VS,delivery:WS,contact:zS,catering_bulk_discount:GS,food_truck:JS};async function Zu(t,e,r=M){let{data:o}=await r.from("franchise_feature_config").select("config").eq("franchise_id",t).eq("feature",e).maybeSingle();return o?YS[e].parse(o.config):null}import{createJSONStorage as QS,devtools as ZS,persist as ex}from"zustand/middleware";var ft=null,rr=null,or=null,Ss=null;function tx(t){return typeof t=="number"?{franchiseId:t}:t??{}}function hp(){return ec.getState().platform??"website"}var ec=XS()(ex(ZS((t,e)=>({logLevel:3,location_id:void 0,franchiseId:void 0,franchiseCateringConfig:{does_cater:null,minimum_notice_hours:null,minimum_people_required:null,minimum_price:null},franchiseDeliveryConfig:{does_deliver:null,delivery_fee_cents:null,max_delivery_radius_miles:null,cents_per_mile:null},platform:"website",visibilityMode:"editor",lastUpdatedAt:new Date(0),setFranchiseId:r=>t({franchiseId:r}),remoteMenuLastUpdated:async()=>{let{data:r,error:o}=await M.from("items").select("updated_at").order("updated_at",{ascending:!1}).limit(1).single();if(o)throw e().logLevel<=2&&console.warn(o,"error getting menu last updated"),new Error("error getting menu last updated");return!r||!r.updated_at?new Date(0):new Date(r.updated_at)},start:async r=>{let o=tx(r),n=o.franchiseId??e().franchiseId??K.getState().franchiseId;if(e().logLevel<=1&&console.debug("starting menu manager"),!n){e().logLevel<=3&&console.warn("franchise id is not set, cannot start menu manager");return}t({franchiseId:n}),o.platform&&t({platform:o.platform}),e().refreshLocalMenu(),e().menuChangeListener(),e().promotionsChangeListener()},items:[],hydrate:({items:r,categories:o,rules:n,components:s})=>t({items:r??[],categories:o??[],rules:n??[],components:s??[]},!1,"hydrate"),setItems:r=>{t({items:r})},addItem:r=>{t({items:[...e().items,r]})},updateItem:r=>{t({items:e().items.map(o=>o.base_item_id===r.base_item_id?r:o)})},deleteItem:r=>{t({items:e().items.filter(o=>o.base_item_id!==r)})},addVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:[...n.variants,r]}:n)})},updateVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:n.variants.map(s=>s.item_id===r.item_id?r:s)}:n)})},deleteVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:n.variants.filter(s=>s.item_id!==r)}:n)})},categories:[],setCategories:r=>t({categories:r}),addCategory:r=>{t({categories:[...e().categories,r]})},updateCategory:r=>{t({categories:e().categories.map(o=>o.category_id===r.category_id?r:o)})},deleteCategory:r=>{t({categories:e().categories.filter(o=>o.category_id!==r)})},rules:[],setRules:r=>{t({rules:r})},addRule:r=>{t({rules:[...e().rules,r]})},updateRule:r=>{t({rules:e().rules.map(o=>o.rule_id===r.rule_id?r:o)})},deleteRule:r=>{t({rules:e().rules.filter(o=>o.rule_id!==r)})},components:[],setComponents:r=>{t({components:r})},addComponent:r=>{t({components:[...e().components,r]})},updateComponent:r=>{t({components:e().components.map(o=>o.id===r.id?r:o)})},deleteComponent:r=>{t({components:e().components.filter(o=>o.id!==r)})},isLocalMenuFresh:async()=>{let r=await e().remoteMenuLastUpdated(),o=e().lastUpdatedAt;return r>=o},refreshLocalMenu:async()=>{let r=e().franchiseId;if(!r){e().logLevel<=2&&console.warn("franchise id is not set, cannot refresh menu");return}let o=hp(),n=K.getState().selectedLocation?.location_id||0;e().logLevel<=1&&console.log("[MenuStore] refreshing menu:",{franchiseId:r,locationId:n,platform:o});let s=await _h(M,r,n,o),i=ys(we.getState().allPromotions,o,n||void 0,new Date);we.setState({activePromotions:i});let[a,l,u]=await Promise.all([yh(M,r,s),Zu(r,"catering"),Zu(r,"delivery")]),{items:c,categories:d,rules:f,components:m}=bh(a,i);t({items:c,categories:d,rules:f,components:m,franchiseCateringConfig:l??{},franchiseDeliveryConfig:u??{}},!1,"refreshLocalMenu"),Ss||(Ss=setInterval(()=>{let h=we.getState().allPromotions;if(!h.length)return;let g=hp(),y=K.getState().selectedLocation?.location_id??void 0,p=ys(h,g,y,new Date),b=we.getState().activePromotions;(p.length!==b.length||p.some((v,L)=>v.id!==b[L]?.id))&&e().refreshLocalMenu()},6e4)),t({lastUpdatedAt:new Date})},menuChangeListener:async()=>{let r=e().franchiseId;if(!r){e().logLevel<=2&&console.warn("[MenuStore] Cannot subscribe to menu changes without franchiseId");return}if(rr&&(clearTimeout(rr),rr=null),ft){try{ft.unsubscribe?.()}catch{}try{M.removeChannel?.(ft)}catch{}ft=null}let o=M.channel(`menu-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"items",filter:`franchise_id=eq.${r}`},()=>{e().refreshLocalMenu()});ft=o,o.subscribe(n=>{if(n==="SUBSCRIBED"){e().logLevel<=1&&console.log("[MenuStore] Subscribed to menu changes");return}if(n==="CLOSED"){e().logLevel<=1&&console.log(`[MenuStore] Subscription status: ${n}`);return}if(n!=="CHANNEL_ERROR"&&n!=="TIMED_OUT"){e().logLevel<=2&&console.warn(`[MenuStore] Subscription status: ${n}`);return}console.warn(`[MenuStore] Subscription status: ${n}. Reconnecting in 5s...`);try{ft?.unsubscribe?.()}catch{}try{M.removeChannel?.(ft)}catch{}ft=null,rr&&clearTimeout(rr),rr=setTimeout(()=>{e().menuChangeListener()},5e3)})},promotionsChangeListener:()=>{let r=e().franchiseId;if(!r)return;if(or){try{or.unsubscribe?.()}catch{}try{M.removeChannel?.(or)}catch{}or=null}or=M.channel(`promotions-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"promotions",filter:`franchise_id=eq.${r}`},async()=>{let{data:n}=await M.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",r);we.setState({allPromotions:n||[]}),e().refreshLocalMenu()}).subscribe()},cleanup:()=>{if(rr&&(clearTimeout(rr),rr=null),ft){try{ft.unsubscribe?.()}catch{}try{M.removeChannel?.(ft)}catch{}ft=null}if(or){try{or.unsubscribe?.()}catch{}try{M.removeChannel?.(or)}catch{}or=null}Ss&&(clearInterval(Ss),Ss=null)},setLastUpdatedAt:r=>t({lastUpdatedAt:r}),uploadMenuImage:async r=>{let o=K.getState().franchiseId;if(!o)throw e().logLevel<=2&&console.warn("[MenuStore] Cannot upload menu image without franchiseId"),new Error("franchise id is not set");let n=`franchise_id_${o}/menu-${Date.now()}`,{error:s}=await M.storage.from("menu-images").upload(n,r);if(s)throw s;return n}}),{name:"MenuStore"}),{name:"menu",onRehydrateStorage:()=>(t,e)=>{if(e||!t)return;let r=t.items;ec.setState({items:r??[]})},storage:QS(()=>wr()),skipHydration:_r}));var $t=ec;import{z as ve}from"zod";import{z as oo}from"zod";var Tt=t=>({schema:t,actionable:!0}),rx=t=>typeof t=="object"&&t!==null&&t.actionable===!0;function je(t,e){let r={};for(let[o,n]of Object.entries(e)){let s=`${t}.${o}`;r[o]=n instanceof oo.ZodType?{name:s,schema:n,actionable:!1}:rx(n)?{name:s,schema:n.schema,actionable:!0}:je(s,n)}return r}var ox=t=>typeof t=="object"&&t!==null&&"name"in t&&t.schema instanceof oo.ZodType;function Va(t,e=[]){if(ox(t))return e.push(t),e;if(t&&typeof t=="object")for(let r of Object.values(t))Va(r,e);return e}if(process.env.NODE_ENV!=="production"){let t=je("order",{placed:oo.object({orderId:oo.number()}),catering:{placed:Tt(oo.object({orderId:oo.number(),headcount:oo.number()}))}}),e=(r,o)=>{if(!r)throw new Error(`define.ts assert: ${o}`)};e(t.placed.name==="order.placed","leaf name"),e(t.catering.placed.name==="order.catering.placed","nested name"),e(t.placed.schema.safeParse({orderId:1}).success,"leaf schema parses"),e(t.catering.placed.schema.safeParse({orderId:1,headcount:2}).success,"marked schema parses"),e(t.placed.actionable===!1,"bare leaf is not actionable"),e(t.catering.placed.actionable===!0,"marked leaf is actionable"),e(Va(t).length===2,"descriptorsIn walks nested"),console.log("define.ts ok")}import{z as H}from"zod";var no={franchiseId:H.number(),locationId:H.number()},en={placed:H.object({orderId:H.number(),...no,total:H.number(),itemCount:H.number().int()}),requested:H.object({orderId:H.number(),...no}),confirmed:H.object({orderId:H.number(),...no,via:H.enum(["pos","email_link","dashboard"]),userId:H.string().optional(),deviceId:H.number().optional()}),paid:H.object({orderId:H.number(),...no,paymentMethod:H.string()}),completed:H.object({orderId:H.number(),...no}),canceled:H.object({orderId:H.number(),...no,reason:H.string().nullable()})},pp=je("order",{...en,placed:Tt(en.placed),completed:Tt(en.completed),failed:H.object({orderId:H.number().nullable(),total:H.number(),reason:H.string(),phase:H.enum(["create","modify","refund","complete","kitchen_complete"]).optional()}),confirmation_email_sent:H.object({orderId:H.number(),recipient:H.string()}),realtime_disconnected:H.object({status:H.string(),location_id:H.number().nullable()}),catering:{...en,requested:Tt(en.requested),confirmed:Tt(en.confirmed),charge_failed:Tt(H.object({orderId:H.number(),...no,chargeId:H.number()}))}});import{z as nr}from"zod";var tc={franchiseId:nr.number(),locationId:nr.number()},gp=je("inventory",{stock_changed:Tt(nr.object(tc)),ingredient_added:Tt(nr.object({...tc,locationIngredientId:nr.number(),ingredientName:nr.string()})),component_added:Tt(nr.object({...tc,locationComponentId:nr.number(),componentName:nr.string()}))});import{z as Ae}from"zod";var yp=je("payment",{captured:Ae.object({orderId:Ae.number(),amount:Ae.number(),method:Ae.string()}),failed:Ae.object({orderId:Ae.number(),amount:Ae.number(),method:Ae.string(),reason:Ae.string(),phase:Ae.enum(["create_payment_intent","retrieve_payment_intent","collect_payment_method","confirm_payment_intent","unexpected"]).optional(),code:Ae.string().nullable().optional(),decline_code:Ae.string().nullable().optional(),payment_intent_id:Ae.string().nullable().optional()}),refunded:Ae.object({orderId:Ae.number(),amount:Ae.number(),method:Ae.string()})});import{z as B}from"zod";import{z as Re}from"zod";var bp=["healthy","degraded","unhealthy","offline"];function Ye(t,e){return{severity:t,detail:e}}function rc(t){let e=Object.fromEntries(Object.entries(t).map(([r,o])=>[r,Re.object({healthy:Re.boolean(),detail:(o.detail??Re.unknown()).optional()})]));return Re.object(e)}var oc={pos:{authenticated:Ye("critical"),menu_loaded:Ye("critical"),reader_connected:Ye("critical"),printer_connected:Ye("critical"),order_listener:Ye("critical"),battery_healthy:Ye("warning",Re.object({percentage:Re.number()}))},kiosk:{authenticated:Ye("critical"),menu_loaded:Ye("critical"),reader_connected:Ye("critical"),battery_healthy:Ye("warning",Re.object({percentage:Re.number()}))},kitchen_display:{authenticated:Ye("critical"),order_listener:Ye("critical"),battery_healthy:Ye("warning",Re.object({percentage:Re.number()}))}},_F=Re.discriminatedUnion("platform",[Re.object({platform:Re.literal("pos"),checks:rc(oc.pos)}),Re.object({platform:Re.literal("kiosk"),checks:rc(oc.kiosk)}),Re.object({platform:Re.literal("kitchen_display"),checks:rc(oc.kitchen_display)})]);var _p=B.enum(bp),wp=je("device",{status_changed:B.object({from:_p.nullable(),to:_p,reason:B.string().nullable()}),check_failed:B.object({check_key:B.string(),reason:B.string()}),check_recovered:B.object({check_key:B.string()}),auth_failed:B.object({phase:B.enum(["init","verify_403"]),reason:B.string()}),connection_error:B.object({reason:B.string()}),verified:B.object({device_id:B.number()}),printer_disconnected:B.object({printer_id:B.string(),reason:B.string()}),print_failed:B.object({printer_id:B.string().nullable(),job_type:B.string(),reason:B.string(),order_id:B.number().nullable(),timings:Du}),print_succeeded:B.object({printer_id:B.string().nullable(),job_type:B.string(),order_id:B.number().nullable(),timings:Du}),reader_connected:B.object({reader_serial:B.string().nullable()}),reader_disconnected:B.object({reader_serial:B.string().nullable(),reason:B.string()}),reader_connect_failed:B.object({reader_serial:B.string().nullable(),reason:B.string()}),order_received:B.object({orderId:B.number(),method_id:B.number().nullable()}),order_acknowledged:B.object({orderId:B.number(),method_id:B.number().nullable()})});import{z as ce}from"zod";var tn=je("api",{supabase_failed:ce.object({table:ce.string(),op:ce.string(),code:ce.string().nullable(),message:ce.string()}),unhandled:ce.object({message:ce.string(),where:ce.string().nullable()}),rate_limited:ce.object({path:ce.string(),method:ce.string(),retryAfterMs:ce.number().nullable()}),timeout:ce.object({path:ce.string(),method:ce.string(),durationMs:ce.number()}),log_invalid_payload:ce.object({event:ce.string(),issues:ce.string()}),log_enqueue_failed:ce.object({event:ce.string(),message:ce.string()})});import{z as oe}from"zod";var vp=oe.object({source:oe.string().optional(),medium:oe.string().optional(),campaign:oe.string().optional()}),sr=je("website",{session_started:oe.object({landing_page:oe.string(),referrer:oe.string().optional(),utm:vp.optional()}),session_ended:oe.object({duration_ms:oe.number(),pages_visited:oe.number()}),page_viewed:oe.object({path:oe.string(),referrer:oe.string().optional(),utm:vp.optional()}),page_exited:oe.object({path:oe.string(),duration_ms:oe.number()}),short_url_clicked:oe.object({slug:oe.string(),referrer:oe.string().optional(),run_id:oe.string().uuid().optional(),outbound_message_id:oe.string().uuid().optional(),strategy_id:oe.string().optional(),strategy_variant_id:oe.string().optional(),dry_run:oe.boolean().optional()})});import{z as xr}from"zod";var Sp=je("integration",{pushed:xr.object({orderId:xr.number(),provider:xr.string(),externalId:xr.string()}),failed:xr.object({orderId:xr.number(),provider:xr.string(),reason:xr.string()})});var VF=new Set(Va([pp,gp,yp,wp,tn,sr,Sp]).filter(t=>t.actionable).map(t=>t.name));var XF=ve.object({id:ve.number(),created_at:ve.string(),severity:ve.enum(["debug","info","warn","error"]),event_name:ve.string(),source:uh,service:ve.string().nullable(),device_id:ve.number().nullable(),session_id:ve.string().nullable(),request_id:ve.string().nullable(),franchise_id:ve.number().nullable(),location_id:ve.number().nullable(),user_id:ve.string().nullable(),anonymous_id:ve.string().nullable(),customer_id:ve.number().nullable(),order_id:ve.number().nullable(),payload:ve.record(ve.string(),ve.unknown()),stack_trace:ve.string().nullable()}),nx=()=>({}),xp=null,QF=new Proxy({},{get(t,e){return xp?.[e]??(()=>{})}});function kp(t){let{source:e,getContext:r=nx,dev:o=!1}=t,n=(i,a,l,u,c)=>{let d=a.schema.safeParse(l);if(!d.success){console.error(`[log] invalid payload for ${a.name}:`,d.error.issues),a.name!==tn.log_invalid_payload.name&&n("error",tn.log_invalid_payload,{event:a.name,issues:JSON.stringify(d.error.issues)});return}let f=r(),m=i==="error"?(u instanceof Error?u.stack:null)??new Error().stack??null:null;if(o){console.log(`[${i}] ${a.name}`,d.data);return}Ut("/events",{method:"POST",body:JSON.stringify({severity:i,event_name:a.name,source:e,session_id:f.session_id??null,request_id:c?.request_id??f.request_id??null,location_id:f.location_id??null,franchise_id:f.franchise_id??null,anonymous_id:f.anonymous_id??null,customer_id:f.customer_id??null,payload:d.data,stack_trace:m})}).then(h=>{h.ok||h.text().then(g=>console.error(`[log] POST /events ${h.status} for ${a.name}:`,g))}).catch(h=>{console.error(`[log] POST /events failed for ${a.name}:`,h)})},s={info:(i,a,l)=>n("info",i,a,void 0,l),warn:(i,a,l)=>n("warn",i,a,void 0,l),error:(i,a,l,u)=>n("error",i,a,l,u)};return xp=s,s}var so=class{diff(e,r,o={}){let n;typeof o=="function"?(n=o,o={}):"callback"in o&&(n=o.callback);let s=this.castInput(e,o),i=this.castInput(r,o),a=this.removeEmpty(this.tokenize(s,o)),l=this.removeEmpty(this.tokenize(i,o));return this.diffWithOptionsObj(a,l,o,n)}diffWithOptionsObj(e,r,o,n){var s;let i=b=>{if(b=this.postProcess(b,o),n){setTimeout(function(){n(b)},0);return}else return b},a=r.length,l=e.length,u=1,c=a+l;o.maxEditLength!=null&&(c=Math.min(c,o.maxEditLength));let d=(s=o.timeout)!==null&&s!==void 0?s:1/0,f=Date.now()+d,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],r,e,0,o);if(m[0].oldPos+1>=l&&h+1>=a)return i(this.buildValues(m[0].lastComponent,r,e));let g=-1/0,y=1/0,p=()=>{for(let b=Math.max(g,-u);b<=Math.min(y,u);b+=2){let _,v=m[b-1],L=m[b+1];v&&(m[b-1]=void 0);let x=!1;if(L){let X=L.oldPos-b;x=L&&0<=X&&X<a}let P=v&&v.oldPos+1<l;if(!x&&!P){m[b]=void 0;continue}if(!P||x&&v.oldPos<L.oldPos?_=this.addToPath(L,!0,!1,0,o):_=this.addToPath(v,!1,!0,1,o),h=this.extractCommon(_,r,e,b,o),_.oldPos+1>=l&&h+1>=a)return i(this.buildValues(_.lastComponent,r,e))||!0;m[b]=_,_.oldPos+1>=l&&(y=Math.min(y,b-1)),h+1>=a&&(g=Math.max(g,b+1))}u++};if(n)(function b(){setTimeout(function(){if(u>c||Date.now()>f)return n(void 0);p()||b()},0)})();else for(;u<=c&&Date.now()<=f;){let b=p();if(b)return b}}addToPath(e,r,o,n,s){let i=e.lastComponent;return i&&!s.oneChangePerToken&&i.added===r&&i.removed===o?{oldPos:e.oldPos+n,lastComponent:{count:i.count+1,added:r,removed:o,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+n,lastComponent:{count:1,added:r,removed:o,previousComponent:i}}}extractCommon(e,r,o,n,s){let i=r.length,a=o.length,l=e.oldPos,u=l-n,c=0;for(;u+1<i&&l+1<a&&this.equals(o[l+1],r[u+1],s);)u++,l++,c++,s.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return c&&!s.oneChangePerToken&&(e.lastComponent={count:c,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,u}equals(e,r,o){return o.comparator?o.comparator(e,r):e===r||!!o.ignoreCase&&e.toLowerCase()===r.toLowerCase()}removeEmpty(e){let r=[];for(let o=0;o<e.length;o++)e[o]&&r.push(e[o]);return r}castInput(e,r){return e}tokenize(e,r){return Array.from(e)}join(e){return e.join("")}postProcess(e,r){return e}get useLongestToken(){return!1}buildValues(e,r,o){let n=[],s;for(;e;)n.push(e),s=e.previousComponent,delete e.previousComponent,e=s;n.reverse();let i=n.length,a=0,l=0,u=0;for(;a<i;a++){let c=n[a];if(c.removed)c.value=this.join(o.slice(u,u+c.count)),u+=c.count;else{if(!c.added&&this.useLongestToken){let d=r.slice(l,l+c.count);d=d.map(function(f,m){let h=o[u+m];return h.length>f.length?h:f}),c.value=this.join(d)}else c.value=this.join(r.slice(l,l+c.count));l+=c.count,c.added||(u+=c.count)}}return n}};var nc=class extends so{constructor(){super(...arguments),this.tokenize=sc}equals(e,r,o){return o.ignoreWhitespace?((!o.newlineIsToken||!e.includes(`
|
|
154
154
|
`))&&(e=e.trim()),(!o.newlineIsToken||!r.includes(`
|
|
155
155
|
`))&&(r=r.trim())):o.ignoreNewlineAtEof&&!o.newlineIsToken&&(e.endsWith(`
|
|
156
156
|
`)&&(e=e.slice(0,-1)),r.endsWith(`
|
|
157
|
-
`)&&(r=r.slice(0,-1))),super.equals(e,r,o)}},n$=new
|
|
158
|
-
`));let r=[],o=t.split(/(\n|\r\n)/);o[o.length-1]||o.pop();for(let n=0;n<o.length;n++){let s=o[n];n%2&&!e.newlineIsToken?r[r.length-1]+=s:r.push(s)}return r}var nc=class extends so{constructor(){super(...arguments),this.tokenize=oc}get useLongestToken(){return!0}castInput(e,r){let{undefinedReplacement:o,stringifyReplacer:n=(s,i)=>typeof i>"u"?o:i}=r;return typeof e=="string"?e:JSON.stringify(qa(e,null,null,n),null," ")}equals(e,r,o){return super.equals(e.replace(/,([\r\n])/g,"$1"),r.replace(/,([\r\n])/g,"$1"),o)}},xp=new nc;function sc(t,e,r){return xp.diff(t,e,r)}function qa(t,e,r,o,n){e=e||[],r=r||[],o&&(t=o(n===void 0?"":n,t));let s;for(s=0;s<e.length;s+=1)if(e[s]===t)return r[s];let i;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),i=new Array(t.length),r.push(i),s=0;s<t.length;s+=1)i[s]=qa(t[s],e,r,o,String(s));return e.pop(),r.pop(),i}if(t&&t.toJSON&&(t=t.toJSON()),typeof t=="object"&&t!==null){e.push(t),i={},r.push(i);let a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),s=0;s<a.length;s+=1)l=a[s],i[l]=qa(t[l],e,r,o,l);e.pop(),r.pop()}else i=t;return i}import{create as sx}from"zustand";import{devtools as ix}from"zustand/middleware";var kr=sx()(ix((t,e)=>({logLevel:4,stack:[],openModal:r=>t({stack:[...e().stack,r]}),goBack:()=>{let r=e().stack;if(r.length>1){let o=r[r.length-1];if(!o)return;let n=r.slice(0,-1),s=n[n.length-1];o.displayStyle!=="dialog"&&s&&(n[n.length-1]={...s,workingData:null}),t({stack:n})}else t({stack:[]})},close:()=>t({stack:[]}),setWorkingData:(r,o=0)=>{if(e().logLevel<=1&&e().stack.length>1){let a=e().getWorkingData(),l=sc(a,r);console.log("[MODAL STORE] working data diff from old:",l)}let n=e().stack,s=n.length-1-o;if(s<0)return;let i=[...n];i[s]={...i[s],workingData:r},t({stack:i})},getWorkingData:(r=0)=>{let o=e().stack;if(o.length!==0)return o[o.length-1-r]?.workingData}}),{name:"ModalStore"}));var ax="v3",lx=function(e){return e===3?"v3":e},Cp="https://js.stripe.com",ux="".concat(Cp,"/v3"),cx=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,dx=/^https:\/\/js\.stripe\.com\/(v3|[a-z]+)\/stripe\.js(\?.*)?$/,kp="loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used",fx=function(e){return cx.test(e)||dx.test(e)},mx=function(){for(var e=document.querySelectorAll('script[src^="'.concat(Cp,'"]')),r=0;r<e.length;r++){var o=e[r];if(fx(o.src))return o}return null},Tp=function(e){var r=e&&!e.advancedFraudSignals?"?advancedFraudSignals=false":"",o=document.createElement("script");o.src="".concat(ux).concat(r);var n=document.head||document.body;if(!n)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return n.appendChild(o),o},hx=function(e,r){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"5.10.0",startTime:r})},xs=null,Va=null,Wa=null,px=function(e){return function(r){e(new Error("Failed to load Stripe.js",{cause:r}))}},gx=function(e,r){return function(){window.Stripe?e(window.Stripe):r(new Error("Stripe.js not available"))}},yx=function(e){return xs!==null?xs:(xs=new Promise(function(r,o){if(typeof window>"u"||typeof document>"u"){r(null);return}if(window.Stripe&&e&&console.warn(kp),window.Stripe){r(window.Stripe);return}try{var n=mx();if(n&&e)console.warn(kp);else if(!n)n=Tp(e);else if(n&&Wa!==null&&Va!==null){var s;n.removeEventListener("load",Wa),n.removeEventListener("error",Va),(s=n.parentNode)===null||s===void 0||s.removeChild(n),n=Tp(e)}Wa=gx(r,o),Va=px(o),n.addEventListener("load",Wa),n.addEventListener("error",Va)}catch(i){o(i);return}}),xs.catch(function(r){return xs=null,Promise.reject(r)}))},bx=function(e,r,o){if(e===null)return null;var n=r[0],s=n.match(/^pk_test/),i=lx(e.version),a=ax;s&&i!==a&&console.warn("Stripe.js@".concat(i," was loaded on the page, but @stripe/stripe-js@").concat("5.10.0"," expected Stripe.js@").concat(a,". This may result in unexpected behavior. For more information, see https://docs.stripe.com/sdks/stripejs-versioning"));var l=e.apply(void 0,r);return hx(l,o),l},ks,Ep=!1,Pp=function(){return ks||(ks=yx(null).catch(function(e){return ks=null,Promise.reject(e)}),ks)};Promise.resolve().then(function(){return Pp()}).catch(function(t){Ep||console.warn(t)});var Op=function(){for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];Ep=!0;var n=Date.now();return Pp().then(function(s){return bx(s,r,n)})};import{create as Sx}from"zustand";import{devtools as xx}from"zustand/middleware";import ir from"zod";import{create as _x}from"zustand";import{devtools as wx}from"zustand/middleware";var Ha=globalThis;function io(t){if(!Ha.document)return null;let e=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=Ha.document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return r?decodeURIComponent(r[1]):null}function ic(t,e,r=365){Ha.document&&(Ha.document.cookie=`${t}=${encodeURIComponent(e)}; path=/; max-age=${r*86400}; SameSite=Lax`)}var Ap=ir.object({shortUrlPath:ir.string().optional().default("/s"),siteUrl:ir.url().optional(),franchiseId:ir.union([ir.string(),ir.number()]).optional(),locationId:ir.union([ir.string(),ir.number()]).optional()});var vx=_x()(wx((t,e)=>({logLevel:1,config:Ap.parse({}),sessionData:{},sessionId:gs(),consentGiven:io("zorgo_consent")==="1",consentAnswered:io("zorgo_consent")!==null,anonymousId:io("zorgo_anon_id"),getSiteUrl:()=>{let r=e().config.siteUrl,o=typeof process<"u"?process.env.NEXT_PUBLIC_SITE_URL||process.env.NEXT_PUBLIC_BASE_URL:void 0,n=typeof globalThis<"u"&&"location"in globalThis&&globalThis.location?.origin?globalThis.location.origin:void 0,s=r||o||n;if(!s){e().logLevel<=3&&console.error("No site url found.");return}return s},getAnonymousId:()=>e().anonymousId,mergeSessionData:r=>{t(o=>{let n={...o.sessionData};for(let[s,i]of Object.entries(r))i===void 0?delete n[s]:n[s]=i;return{sessionData:n}})},setConsent:r=>{if(ic("zorgo_consent",r?"1":"0"),r&&!e().anonymousId){let o=`anon_${gs()}`;ic("zorgo_anon_id",o),t({consentGiven:!0,consentAnswered:!0,anonymousId:o})}else t({consentGiven:r,consentAnswered:!0})},initialize:({token:r,config:o})=>{let n=Ap.parse(o||{});t({token:r,config:n,consentGiven:io("zorgo_consent")==="1",consentAnswered:io("zorgo_consent")!==null,anonymousId:io("zorgo_anon_id")})}}),{name:"websiteCoreStore"})),Ie=vx;var Rp={logLevel:1,clientSecret:null,intentType:null,isLoading:!1,error:null,orderId:null,finalAmount:null},ac=!1,kx=Sx()(xx((t,e)=>({...Rp,start:async()=>{let r=K.getState().selectedLocation,o=process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY,n=process.env.NEXT_PUBLIC_STRIPE_ACCOUNT_OVERRIDE||r?.stripe_account_id;if(!o||!n)return null;let s=await Op(o,{stripeAccount:n});if(!s){e().logLevel<=3&&console.error("Failed to load Stripe");return}t({stripe:s})},createOrder:async(r,o)=>{if(!r?.items?.length||!o?.location_id)throw new Error("Order, location, and time_requested are required");let n={...r,method_id:2,location_id:o.location_id},{franchiseId:s}=Ie.getState().config,i=await Ut("/create-order",{method:"POST",body:JSON.stringify({order:n,anonymous_id:Ie.getState().getAnonymousId(),franchise_id:s?String(s):void 0})});if(!i.ok){let l=await i.json();throw new Error(l.error||`Server error: ${i.status}`)}return(await i.json()).orderId},createPaymentIntentForOrder:async(r,o,n)=>{let s=await Ut("/create-payment-intent",{method:"POST",body:JSON.stringify({orderId:r,tipAmount:o,deliveryFeeCents:n||0})});if(!s.ok){let u=await s.json();throw new Error(u.error||`Server error: ${s.status}`)}let i=await s.json(),a=i.charges?.total??i.amount??0,l=i.type==="setup_intent"?"setup_intent":"payment_intent";return{clientSecret:i.clientSecret,amount:a,intentType:l}},confirmPayment:async(r,o,n,s,i)=>{let a=r,l={name:`${i.first_name} ${i.last_name}`.trim()||void 0,email:i.email,phone:ch(i.phone)},u=e().intentType,c={return_url:s,payment_method_data:{billing_details:l}},d;return u==="setup_intent"?{error:d}=await a.confirmSetup({elements:o,clientSecret:n,confirmParams:c}):{error:d}=await a.confirmPayment({elements:o,clientSecret:n,confirmParams:c}),d?{success:!1,error:d.message}:u!=="setup_intent"?{success:!0,paymentIntentId:(await a.retrievePaymentIntent(n)).paymentIntent?.id}:{success:!0}},getReturnStatus:r=>{let o=typeof r=="string"?new URL(r):r,n=o.searchParams.get("redirect_status"),s=o.searchParams.get("setup_intent"),i=o.searchParams.get("payment_intent")??s??void 0,a=!!s,l=o.searchParams.get("amount"),u=Number(o.searchParams.get("order")),c=Number.isSafeInteger(u)&&u>0?u:void 0,d=o.searchParams.get("order_token")??void 0;return n?n==="succeeded"?{succeeded:!0,amount:l?parseFloat(l):void 0,paymentIntentId:i,isHold:a,orderId:c,orderToken:c?d:void 0}:{succeeded:!1,error:`Payment ${n}`,paymentIntentId:i,isHold:a}:{succeeded:!1,error:"No payment status found in URL",isHold:a}},mintOrderLinkToken:async(r,o)=>{if(!r||!o)return null;try{let n=await Ut(`/catering/order/${r}/link`,{method:"POST",body:JSON.stringify({email:o}),signal:AbortSignal.timeout(3e3)});if(!n.ok)return null;let s=await n.json();return typeof s?.token=="string"?s.token:null}catch{return null}},beginCheckout:async()=>{if(!(e().isLoading||ac)){ac=!0,t({isLoading:!0,error:null});try{let r=Z.getState().workingOrder,o=K.getState().selectedLocation,n=Z.getState().selectedTip??0,s=Z.getState().deliveryFeeCents??0;if(!o)throw new Error("Cannot start checkout without a selected location");if(!r)throw new Error("Cannot start checkout without a working order");let i=e().orderId;i||(i=await e().createOrder(r,o),t({orderId:i}));let{clientSecret:a,amount:l,intentType:u}=await e().createPaymentIntentForOrder(i,n,s);t({clientSecret:a,intentType:u,orderId:i,finalAmount:l,isLoading:!1,error:null})}catch(r){let o=r instanceof Error?r.message:"Failed to setup payment";throw t({isLoading:!1,error:o}),r}finally{ac=!1}}},reset:()=>t(Rp)}),{name:"PaymentStore"})),Me=kx;import{create as $x}from"zustand";var Qp=yn(Yp(),1);import{z as Ps}from"zod";var mc=t=>(0,Qp.default)(t).isLight()?"#000000":"#FFFFFF",Ya=t=>Ps.string().nullish().transform(e=>e??t),Xp=t=>Ps.number().nullish().transform(e=>e??t),Zp=Ps.object({design_id:Xp(0),franchise_id:Xp(0),primary:Ya("#9943E9"),accent:Ya("#6636BF"),backgroundBase:Ya("#EBEBEB"),fontFamily:Ya("Inter"),created_at:Ps.string().optional(),updated_at:Ps.string().optional()}).transform(t=>({...t,foreground:mc(t.backgroundBase),primaryForeground:mc(t.primary),accentForeground:mc(t.accent)})),eg=Zp.parse({});function tg(t){return Zp.parse(t??{})}import{devtools as Bx,persist as qx,createJSONStorage as Vx}from"zustand/middleware";var Wx="branding-assets",Hx=3600,zx=$x()(qx(Bx((t,e)=>({branding:eg,logoUrl:null,fetchFranchiseLogoUrl:async r=>{let o=[`franchises/${r}/logo.png`,`franchises/${r}/logo.jpg`];for(let n of o){let{data:s,error:i}=await M.storage.from(Wx).createSignedUrl(n,Hx);if(!i&&s?.signedUrl)return t({logoUrl:s.signedUrl}),console.log("logoUrl",s.signedUrl),s.signedUrl;console.log("error",i)}return t({logoUrl:null}),null},initialize:async()=>{let r=K.getState().franchiseId,{data:o,error:n}=await M.from("franchise_branding").select("*").eq("franchise_id",r).single();n||o&&t({branding:tg(o)})}})),{name:"branding",storage:Vx(()=>wr()),skipHydration:_r,partialize:t=>({branding:t.branding})})),hc=zx;import{create as Gx}from"zustand";import{devtools as Kx}from"zustand/middleware";import{immer as Jx}from"zustand/middleware/immer";var Yx=Gx()(Kx(Jx(t=>({recommendations:[],isLoading:!1,error:null,strategy:"top_items",lastFetchedAt:null,fetchRecommendations:async e=>{t(r=>{r.isLoading=!0,r.error=null});try{let r=await Ut("/recommendations",{method:"POST",body:JSON.stringify(e)});if(!r.ok){let n=await r.json().catch(()=>null);throw new Error(n?.error??`Server error: ${r.status}`)}let o=await r.json();t(n=>{n.recommendations=o.recommendations??[],n.strategy=e.strategy??"top_items",n.isLoading=!1,n.lastFetchedAt=new Date})}catch(r){let o=r?.message??"Failed to fetch recommendations";t(n=>{n.error=o,n.isLoading=!1})}},setStrategy:e=>{t(r=>{r.strategy=e})},clear:()=>{t(e=>{e.recommendations=[],e.error=null,e.lastFetchedAt=null})}})),{name:"RecommendationStore"})),Bt=Yx;function rg(){let t=()=>`ses_${crypto.randomUUID()}`;if(typeof sessionStorage>"u")return t();let e="zorgo_session_id",r=sessionStorage.getItem(e);return r||(r=t(),sessionStorage.setItem(e,r)),r}function og(t){if(!t)return;let e=new URLSearchParams(t),r=e.get("utm_source")||void 0,o=e.get("utm_medium")||void 0,n=e.get("utm_campaign")||void 0;if(!(!r&&!o&&!n))return{source:r,medium:o,campaign:n}}var ng=()=>Promise.resolve();function sg(t){ng=t}function qt(){lr(()=>{ng().catch(console.error)},[])}var ig=()=>typeof window>"u"?"/":window.location.pathname;function ag(t){ig=t}function qB(){let t=kr(r=>r.stack);return{current:t[t.length-1]??null,isOpen:t.length>0,depth:t.length,open:(r,o,n)=>kr.getState().openModal({type:r,props:o,displayStyle:n}),close:kr.getState().close,back:kr.getState().goBack,setWorkingData:kr.getState().setWorkingData,getWorkingData:kr.getState().getWorkingData}}function VB(){qt();let t=Z.getState(),e=Z(u=>u.workingOrder),r=Z(u=>u.selectedTip),{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}=dp(),l=Ze(()=>e.items.reduce((u,c)=>u+c.quantity,0),[e.items]);return{items:e.items,itemCount:l,isEmpty:l===0,customer:e.customer,promoCode:e.promo_code,tip:r,subtotal:o,discount:n,tax:s,serviceFee:i,total:a,addItem:t.addItem,removeItem:t.removeItem,updateItem:t.updateItem,resetCart:()=>{t.resetOrder(),t.setOrderType(2)},setCustomer:t.setCustomer,setLocationId:t.setLocationId,setOrderType:t.setOrderType,setTimeRequested:t.setTimeRequested,setTip:t.setTip,getItemTotal:u=>Sr(u),getOrder:()=>Z.getState().workingOrder,resolveShortUrl:u=>t.setCartFromURL(u,Ie.getState().token)}}function WB(t){qt();let e=K(u=>u.locations),r=K(u=>u.franchises),o=K(u=>u.selectedLocation),n=K(u=>u.setSelectedLocation),s=K(u=>u.getIsCurrentLocationOpen),i=Ze(()=>e.filter(u=>r.some(c=>c.franchise_id===u.franchise_id)),[e,r]),a=t?.autoSelectLocationId;lr(()=>{if(a==null||o)return;let u=i.find(c=>c.location_id===a);u&&n(u)},[a,o,i,n]);let l=!!t?.promptLocationSelection&&!o&&i.length>0;return{availableLocations:i,currentLocation:o,setLocation:n,getIsCurrentLocationOpen:s,needsLocationSelection:l}}function Xx(){qt();let t=$t(o=>o.items),e=$t(o=>o.categories);return{items:Ze(()=>t.filter(o=>!e.find(s=>s.category_id===o.category_id)?.is_catering),[t,e]),allItems:t,categories:e}}function Qx(t,e,r,o){let n=t.getState();o(n)&&r(n)(e)}function HB(t){Qx($t,t,e=>e.hydrate,e=>!e.items?.length)}function zB(t,e,r){qt();let o=r!=null,{allItems:n}=Xx(),s=Ze(()=>n.find(S=>S.base_item_id===t),[n,t]),[i,a]=Er(e?.item_id??null),[l,u]=Er(()=>{let S={};for(let q of e?.selections??[])S[q.rule_id]=q.selections.map(N=>Xo(`${N.type}:${N.id}`,N.portion));return S}),[c,d]=Er(()=>{let S={};for(let q of e?.components??[])S[Xo(String(q.id),q.portion)]=q.quantity_servings;return S}),[f,m]=Er(e?.quantity??1),h=Cr(S=>m(q=>Math.max(1,typeof S=="function"?S(q):S)),[]),[g,y]=Er(e?.comments??""),p=s?.variants.find(S=>S.item_id===i)??s?.variants[0],b=p?.portion_scheme??null,_=Cr(S=>{a(S.item_id),u({}),d({})},[]),v=Ze(()=>(p?.rules??s?.rules??[]).filter(S=>S.rule_id!=null),[p,s]),L=Cr((S,q,N,ee=1/0)=>{u(Q=>{let G=Q[S]??[],ge=Xo(q,N),me=G.findIndex(ye=>kt(ye).baseKey===q);return me!==-1?{...Q,[S]:G[me]===ge?G.filter(ye=>ye!==ge):G.map((ye,Ct)=>Ct===me?ge:ye)}:ee===1?{...Q,[S]:[ge]}:Uu(G)+Da(N)>ee?Q:{...Q,[S]:[...G,ge]}})},[]),x=Cr(S=>{u(q=>{let N={};for(let[ee,Q]of Object.entries(q))N[Number(ee)]=Q.flatMap(G=>{let{baseKey:ge,portion:me}=kt(G);if(!me)return[G];let ye=kh(me,S);return ye?[Xo(ge,ye[0])]:[]});return N})},[]),P=Cr((S,q)=>{u(N=>({...N,[S]:(N[S]??[]).filter(ee=>kt(ee).baseKey!==q)}))},[]),X=Ze(()=>v.map(S=>{let q=S.rule_id,N=l[q]??[],ee=_h(S),Q=new Map(ee.map(G=>[G.key,G]));return{rule:S,ruleId:q,keys:N,defs:ee,byKey:Q,charged:xh(N,G=>Q.get(G)?.basePrice??0,S.included_quantity??0)}}),[v,l]),F=Ze(()=>X.map(({rule:S,ruleId:q,keys:N,defs:ee,charged:Q})=>{let G=S.max_selection??1/0,ge=Uu(N),me=ge>=G;return{...S,rule_id:q,max:G,selectedCount:ge,portionable:!!b&&!!S.is_portionable,subtext:Eh(S),satisfied:ge>=S.min_selection&&ge<=G,message:()=>ge<S.min_selection?`Choose at least ${S.min_selection} option${S.min_selection>1?"s":""}`:ge>G?`Choose no more than ${G} option${G>1?"s":""}`:null,options:ee.map(({basePrice:ye,...Ct})=>{let Et=N.find(Sy=>kt(Sy).baseKey===Ct.key),fo=Et?kt(Et).portion:null;return{...Ct,key:Et??Ct.key,portion:fo,coveredSections:fo?[Zt(fo).index]:[],coveredWhole:!!Et&&!fo,upcharge:Et?Q.get(Et):ye,selected:!!Et,disabled:me&&!Et&&G!==1,toggle:()=>L(q,Ct.key,null,G)}})}}),[X,b,L]),tt=Ze(()=>X.map(({rule:S,ruleId:q,keys:N,byKey:ee,charged:Q})=>({rule_id:q,group_name:S.group_name,selections:N.flatMap(G=>{let{baseKey:ge,portion:me}=kt(G),ye=ee.get(ge);return ye?[{id:ye.id,type:ye.type,quantity:1,upcharge:Q.get(G)??0,name:ye.name,portion:me}]:[]})})).filter(S=>S.selections.length>0),[X]),fe=Ze(()=>!s||!p?null:{item_id:p.item_id,base_item_id:s.base_item_id,category_id:s.category_id,name:p.name,quantity:f,price:p.price,components:(p.components??[]).flatMap(S=>Sh(String(S.id),c,S.servings_per_item??1).map(({portion:q,value:N})=>({...S,portion:q,quantity_servings:N}))),selections:tt,comments:g},[s,p,f,c,tt,g]),rt=F.find(S=>!S.satisfied)??null,Wt=!!fe&&!rt,Ht=Cr(()=>!fe||F.some(S=>!S.satisfied)?null:(o?Z.getState().updateItem(fe,r):Z.getState().addItem(fe),fe),[fe,F,o,r]),zt=fe?Sr(fe):0,Ne=!!p?.display_price&&p.display_price<p.price;return{item:s,variant:p,variants:s?.variants??[],setVariant:_,ruleGroups:F,unmetRule:rt,canSubmit:Wt,submit:Ht,portionScheme:b,placeOption:L,clearOption:P,recutSelections:x,quantity:f,setQuantity:h,comments:g,setComments:y,setComponentServings:(S,q,N=null)=>d(ee=>{let Q={...ee};if(!N)for(let G of Object.keys(Q))kt(G).baseKey===String(S)&&delete Q[G];return Q[Xo(String(S),N)]=Math.max(0,q),Q}),price:zt,salePrice:Ne&&fe?Sr({...fe,display_price:p.display_price},!0):void 0,isEditMode:o,draft:fe}}function GB(){qt();let t=K(p=>p.selectedLocation),e=we(p=>p.activePromotions),r=Z(p=>p.workingOrder),o=Z(p=>p.selectedPromotion),n=r.promo_code,[s,i]=Er(null),[a,l]=Er(!1),u=ar(null),c=Ze(()=>r.items.reduce((p,b)=>p+(b.discount_amount??0),0),[r.items]),d=Ze(()=>Qo({order:r}),[r]),f=Ze(()=>{if(!o)return c;try{return er(o,r,new Date)}catch{return 0}},[c,o,r]),m=Ze(()=>{if(o||c<=0)return null;let p=new Map;for(let _ of r.items)!_.applied_promo_id||!_.discount_amount||p.set(_.applied_promo_id,(p.get(_.applied_promo_id)??0)+_.discount_amount);let b=Array.from(p.entries()).sort((_,v)=>v[1]-_[1])[0]?.[0];return e.find(_=>_.id===b)??null},[e,c,o,r.items]),h=o??m;lr(()=>{if(!t?.franchise_id)return;let p=!1;return l(!0),we.getState().getActivePromotions(t.franchise_id,t.location_id).finally(()=>{p||l(!1)}),()=>{p=!0}},[t?.franchise_id,t?.location_id]),lr(()=>{if(!n){i(null);return}if(o&&f>0){i(null);return}if(o?.min_purchase_amount&&d<o.min_purchase_amount){i(`Minimum purchase of $${(o.min_purchase_amount/100).toFixed(2)} required`);return}o&&i("Promotion not applicable")},[d,f,n,o]);let g=Cr(async p=>{let b=p.trim();if(b){if(!t?.franchise_id||!t?.location_id){i("Please select a location first");return}l(!0),i(null);try{let _=await we.getState().getPromotionByCode(b,t.franchise_id);if(!_){Z.getState().removeOrderPromotion(),i("Invalid promotion code");return}Z.getState().applyOrderPromotion(_)}catch{i("Unable to apply promotion")}finally{l(!1)}}},[t?.franchise_id,t?.location_id]);lr(()=>{Z.getState().workingOrder.promo_code||Z.getState().checkBestPromo()},[e]),lr(()=>{if(typeof window>"u")return;let b=new URLSearchParams(window.location.search).get("promo");!b||b===n||u.current===b||(u.current=b,g(b))},[g,n,t?.location_id]);let y=Cr(()=>{if(i(null),u.current=null,Z.getState().overrideOrderPromotion(null),typeof window<"u"){let p=new URL(window.location.href);p.searchParams.has("promo")&&(p.searchParams.delete("promo"),window.history.replaceState({},"",p.toString()))}},[]);return{promoCode:n??"",setPromoCode:p=>{p?g(p):y()},appliedPromo:h,discountAmount:f,error:s,loading:a,applyPromo:g,removePromo:y,activePromotions:e}}function KB(t={}){qt();let e=Me(d=>d.clientSecret),r=Me(d=>d.intentType),o=Me(d=>d.isLoading),n=Me(d=>d.error),s=Me(d=>d.stripe),i=Me(d=>d.finalAmount),a=Me(d=>d.orderId),l=Z(d=>d.workingOrder),u=e?{clientSecret:e,...t.appearance&&{appearance:t.appearance},defaultValues:{billingDetails:{name:(l.customer.first_name??"")+" "+(l.customer.last_name??""),email:l.customer.email,phone:l.customer.phone}}}:null,c=Me.getState().confirmPayment;return{clientSecret:e,intentType:r,stripe:s,elementOptions:u,total:i,orderId:a,isLoading:o,error:n,isReady:!!(e&&s),startCheckout:Me.getState().beginCheckout,resetCheckout:Me.getState().reset,submitPayment:c,paymentElementOptions:{layout:"accordion",fields:{billingDetails:{name:"never",email:"never",phone:"never",address:"auto"}}},getReturnStatus:Me.getState().getReturnStatus,mintOrderLinkToken:Me.getState().mintOrderLinkToken,getReturnUrl:Ie.getState().getSiteUrl}}function JB(){qt();let t=$t(r=>r.franchiseCateringConfig),e=$t(r=>r.franchiseDeliveryConfig);return{minimum_notice_hours:t.minimum_notice_hours,minimum_people_required:t.minimum_people_required,minimum_price:t.minimum_price,does_cater:t.does_cater,does_deliver:e.does_deliver,delivery_fee_cents:e.delivery_fee_cents,max_delivery_radius_miles:e.max_delivery_radius_miles,cents_per_mile:e.cents_per_mile}}function YB(){qt();let t=Bt(s=>s.recommendations),e=Bt(s=>s.isLoading),r=Bt(s=>s.error),o=Bt(s=>s.strategy),n=Bt(s=>s.lastFetchedAt);return{recommendations:t,isLoading:e,error:r,strategy:o,lastFetchedAt:n,refresh:s=>Bt.getState().fetchRecommendations(s),setStrategy:s=>Bt.getState().setStrategy(s),clear:()=>Bt.getState().clear()}}var Xa=null,pc=null,lg={};function gc(){return pc||(pc=Sp({source:"restaurant_site",getContext:()=>lg})),pc}function Zx(){qt();let t=Ie(g=>g.consentGiven),e=Ie(g=>g.anonymousId),r=Ie(g=>g.config),o=K(g=>g.franchiseId),n=ig(),s=ar(null);s.current||(s.current=Symbol("zorgo-tracking"));let[i,a]=Er(!1),l=ar(null),u=ar(Date.now()),c=ar(Date.now()),d=ar(0),f=ar(!1),m=ar(!1),h=ar(typeof window>"u"?void 0:og(window.location.search));lr(()=>(Xa===null&&(Xa=s.current,a(!0)),()=>{Xa===s.current&&(Xa=null)}),[]),lr(()=>{if(!i)return;if(!t){f.current=!1;return}let g=rg(),y=typeof document<"u"&&document.referrer||void 0,p=r.franchiseId??o;lg={session_id:g,anonymous_id:e||null,franchise_id:p!=null?Number(p):null,location_id:r.locationId!=null?Number(r.locationId):null};let b=gc();f.current||(f.current=!0,m.current=!1,b.info(sr.session_started,{landing_page:n,referrer:y,utm:h.current}),d.current=1,c.current=Date.now());let _=()=>{m.current||(m.current=!0,l.current&&b.info(sr.page_exited,{path:l.current,duration_ms:Date.now()-u.current}),b.info(sr.session_ended,{duration_ms:Date.now()-c.current,pages_visited:d.current}))},v=()=>{document.visibilityState==="hidden"&&_()};return window.addEventListener("beforeunload",_),document.addEventListener("visibilitychange",v),()=>{window.removeEventListener("beforeunload",_),document.removeEventListener("visibilitychange",v)}},[i,t,e,o]),lr(()=>{if(!(!i||!t||!f.current)){if(l.current&&l.current!==n&&gc().info(sr.page_exited,{path:l.current,duration_ms:Date.now()-u.current}),l.current!==n){let g=l.current===null;gc().info(sr.page_viewed,{path:n,referrer:typeof document<"u"&&document.referrer||void 0,utm:g?h.current:void 0}),g||(d.current+=1)}l.current=n,u.current=Date.now()}},[n,t,i])}function XB(){qt(),Zx();let t=Z(s=>s.workingOrder.customer),e=Z.getState().setCustomer,r=Ie(s=>s.consentGiven),o=Ie(s=>s.consentAnswered),n=Ie(s=>s.anonymousId);return{customer:t,consentGiven:r,setCustomer:e,consentAnswered:o,setConsent:Ie.getState().setConsent,anonymousId:n}}function ug(t){return typeof window>"u"?Promise.reject(new Error("Google Maps can only load in the browser")):window.google?.maps?.places?Promise.resolve():new Promise((r,o)=>{let n=document.querySelector('script[src^="https://maps.googleapis.com/maps/api/js"]');if(n){n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>o(new Error("Maps script failed")),{once:!0});return}let s=document.createElement("script");s.src=`https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(t)}&libraries=places`,s.async=!0,s.defer=!0,s.onload=()=>r(),s.onerror=()=>o(new Error("Failed to load Google Maps")),document.head.appendChild(s)})}var Qa=null;async function ek(){try{let t=await fetch("/api/zorgo-token");if(!t.ok)return;let{token:e}=await t.json();return e}catch{return}}function cg(){return typeof window>"u"?Promise.resolve():Qa||(Qa=(async()=>{cp();let t,e=new Promise(o=>t=o);wh(async()=>Ie.getState().token??await e),await Promise.all([K,$t,Z,hc].map(o=>o.persist.rehydrate())),Z.setState(o=>({workingOrder:{...o.workingOrder,method_id:2,type_id:2}}));let r=await ek();if(t(r??null),!r)throw new Error("Zorgo: missing token. Ensure app/api/zorgo-token exists and ZORGO_SITE_SECRET is set.");Ie.getState().initialize({token:r}),tk(),await K.getState().initialize({token:r})})(),Qa)}function tk(){let t=n=>{n&&Me.getState().start()},e=async n=>{let s=K.getState().franchiseId;s&&(await we.getState().getActivePromotions(s,n,"website").catch(console.error),Z.getState().checkBestPromo())},r=async n=>{n&&(await e(K.getState().selectedLocation?.location_id),$t.getState().start({franchiseId:n,platform:"website",visibilityMode:"runtime"}))},o={fireImmediately:!0};K.subscribe(n=>n.franchiseId,r,o),K.subscribe(n=>n.selectedLocation?.stripe_account_id,t,o),K.subscribe(n=>n.selectedLocation?.location_id,(n,s)=>{n&&Z.getState().setLocationId(n),n!==s&&e(n)},o)}import{createStore as rk}from"zustand";import{devtools as ok}from"zustand/middleware";import{immer as nk}from"zustand/middleware/immer";import{createContext as sk,useContext as ik}from"react";var yc=sk(null);function mt(){let t=ik(yc);if(!t)throw new Error("Must be used inside DynamicFormShell");return t}function bc({onSubmit:t}){return rk()(ok(nk((e,r)=>({values:{},fieldConfigs:{},fieldErrors:{},status:"idle",registerField:(o,n)=>(e(s=>{s.fieldConfigs[o]=n,o in s.values||(s.values[o]=n.defaultValue??"")}),()=>{e(s=>{delete s.fieldConfigs[o],delete s.fieldErrors[o]})}),setValue:(o,n)=>{e(s=>{s.values[o]=n})},clearError:o=>{e(n=>{delete n.fieldErrors[o],n.status="idle"})},validateField:o=>{let n=r().fieldConfigs[o];if(!n)return null;let s=r().values[o],i=n.required&&!s?"Required.":n.validate(s);return e(a=>{i?a.fieldErrors[o]=i:delete a.fieldErrors[o]}),i??null},setFieldError:(o,n)=>{r().fieldConfigs[o]&&e(i=>{i.fieldErrors[o]=n})},validateAll:()=>{let o={};return Object.keys(r().fieldConfigs).forEach(n=>{let s=r().validateField(n);s&&(o[n]=s)}),o},handleSubmit:async o=>{o.preventDefault();let n=r().validateAll();if(Object.keys(n).length>0){e(s=>{s.fieldErrors=n,s.status="error"});return}e(s=>{s.status="sending"});try{await t(r().values),e(s=>{s.status="sent"})}catch{e(s=>{s.status="error"})}}}))))}import{useMemo as ak,useRef as lk}from"react";import{jsx as dg}from"react/jsx-runtime";function fg({className:t,onSubmit:e,children:r}){let o=lk(e);o.current=e;let n=ak(()=>bc({onSubmit:(...s)=>o.current(...s)}),[]);return dg(yc.Provider,{value:n,children:dg("form",{onSubmit:n.getState().handleSubmit,className:t,children:r})})}import{useRef as mk}from"react";import{z as tl}from"zod";import{useStore as uk}from"zustand";function Za(){let t=mt(),e=uk(t,r=>r.status);return{status:e,isIdle:e==="idle",isSubmitting:e==="sending",isSubmitted:e==="sent",isError:e==="error"}}import{useStore as ck}from"zustand";function dk(t,e){return t.required&&(e==null||e==="")?"Required.":t.validate(e)}function el(){let t=mt();return ck(t,e=>Object.entries(e.fieldConfigs).every(([r,o])=>dk(o,e.values[r])===null))}import{useStore as fk}from"zustand";function He(){let t=mt();return fk(t,e=>e.values)}import{jsx as mg,jsxs as pk}from"react/jsx-runtime";var hk=tl.object({label:tl.string().default("Submit"),loadingLabel:tl.string().default("Submitting..."),className:tl.string().default("")});function hg(t){let{labelFn:e,...r}=t,{label:o,loadingLabel:n,className:s}=hk.parse(r),i=el(),{isSubmitting:a,isSubmitted:l}=Za(),u=He(),c=mt(),d=mk(null),f=!i||a||l,m=e?e(u):o;function h(){c.getState().validateAll(),setTimeout(()=>{d.current?.form?.querySelector("[data-field-error]")?.scrollIntoView({behavior:"smooth",block:"center"})},50)}return pk("div",{style:{position:"relative"},children:[mg("button",{ref:d,type:"submit",disabled:f,className:s,children:a?n:m}),f&&mg("div",{onClick:h,style:{position:"absolute",inset:0,cursor:"pointer"}})]})}import{useStore as pg}from"zustand";function ae(t){let e=mt(),r=pg(e,l=>l.values[t]),o=pg(e,l=>l.fieldErrors[t])??null;return{value:r,error:o,setValue:l=>e.getState().setValue(t,l),clearError:()=>e.getState().clearError(t),validate:()=>e.getState().validateField(t),setError:l=>e.getState().setFieldError(t,l)}}import{jsx as gk}from"react/jsx-runtime";function xe({name:t,className:e}){let{error:r}=ae(t);return r?gk("span",{"data-field-error":t,className:e,children:r}):null}import{jsx as gg,jsxs as yk}from"react/jsx-runtime";function yg({className:t,title:e,titleClassName:r,subtitle:o,subtitleClassName:n}){return yk("div",{className:t,children:[gg("h1",{className:r,children:e}),gg("p",{className:n,children:o})]})}import{useMemo as bg}from"react";import{jsx as ur,jsxs as vc}from"react/jsx-runtime";function bk(t,e){return e.flatMap(r=>{let o=t[`rule_${r.ruleId}`]??[];return r.options.filter(n=>o.includes(n.value)&&n.upcharge>0).map(n=>({id:`rule_${r.ruleId}_${n.value}`,name:n.label,priceCents:n.upcharge}))})}function _c({label:t,value:e,isTotal:r,isDiscount:o}){return r?ur("div",{className:"flex items-center justify-between pt-3 mt-1 border-t-2 border-zestia-red-500",children:ur("span",{className:"font-extrabold text-end text-zestia-red-500 text-xl",children:e})}):o?vc("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[ur("span",{className:"text-xs text-emerald-600 font-medium",children:t}),ur("span",{className:"text-xs font-semibold text-emerald-600",children:e})]}):vc("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[ur("span",{className:"text-xs text-stone-500",children:t}),ur("span",{className:"text-xs font-semibold text-stone-700",children:e})]})}function wc(t){return`$${(t/100).toFixed(2)}`}function _g({items:t,ruleGroups:e=[],guestCountFieldId:r="guestCount",className:o}){let n=He(),{value:s}=ae(r),i=Number(s)||0,a=we(h=>h.allPromotions),l=[...t,...bk(n,e)],u=l.reduce((h,g)=>h+g.priceCents,0),c=bg(()=>{let h=t.find(g=>g.isBase);if(h?.active_promo_id)return a.find(g=>g.id===h.active_promo_id&&g.min_purchase_quantity)},[t,a]),d=bg(()=>!c||i<=0?u:Math.round(Fu(u,i,c.discount_value/100,c.min_purchase_quantity)),[c,i,u]),f=d*i,m=u>0&&d<u?((u-d)/u*100).toFixed(1):null;return vc("div",{className:o,children:[l.map(h=>ur(_c,{label:h.name,value:`${wc(h.priceCents)}/person`},h.id)),m&&ur(_c,{isDiscount:!0,label:`Bulk discount (${m}% off)`,value:`-${wc(u-d)}/person`}),ur(_c,{isTotal:!0,label:"Per-Person Cost",value:`${wc(d)}/person`})]})}import{jsx as _k}from"react/jsx-runtime";function wg({label:t,className:e}){return _k("h2",{className:e,children:t})}import{jsx as wk}from"react/jsx-runtime";function vg({children:t,className:e}){return wk("p",{className:e,children:t})}import{useState as vk,useEffect as Sk}from"react";function rl(t){let e={};for(let[r,o]of Object.entries(t))Array.isArray(o)&&o.every(n=>typeof n=="string")?e[r]=o.length===1?o[0]:o.length===0?void 0:o:e[r]=o;return e}import{Fragment as xk,jsx as kk}from"react/jsx-runtime";function Sg({whenFormVal:t,whenFunction:e,whenMediaQuery:r,children:o}){let n=He(),[s,i]=vk(()=>r&&typeof window<"u"?window.matchMedia(r).matches:!1);return Sk(()=>{if(!r)return;let l=window.matchMedia(r);i(l.matches);let u=c=>i(c.matches);return l.addEventListener("change",u),()=>l.removeEventListener("change",u)},[r]),(t?t(rl(n)):!1)||(e?e():!1)||(r?s:!1)?kk(xk,{children:o}):null}import{z as j}from"zod";var ne=j.object({inputType:j.enum(["text","number","date","time"]).default("text"),fieldId:j.string(),label:j.string().optional(),placeholder:j.string().optional(),autoCompleteType:j.string().optional(),requiredText:j.string().default("Required."),required:j.boolean().default(!0),showLabel:j.boolean().default(!0),showError:j.boolean().default(!0),disabled:j.boolean().default(!1),fieldClassName:j.string().default("flex-1"),containerClassName:j.string().default("flex flex-col"),fieldLabelClassName:j.string().default("flex-1"),fieldErrorClassName:j.string().default("flex-1"),fieldAsteriskClassName:j.string().default("text-red-500"),initialValue:j.unknown().optional()}),i5=ne.extend({min:j.number().optional(),max:j.number().optional(),step:j.number().default(1)}),a5=ne.extend({min:j.string().optional(),max:j.string().default("23:59")}),nn=ne.extend({maxLength:j.number().default(256),validate:j.any(),sanitize:j.any(),min:j.string().optional(),max:j.string().optional(),multiline:j.boolean().default(!1),rows:j.number().default(5)}),xg=ne.extend({minSelections:j.number().default(1),maxSelections:j.union([j.number(),j.literal(1/0)]).default(1),tooFewText:j.string().optional(),tooManyText:j.string().optional(),options:j.array(j.object({label:j.string(),value:j.string(),sublabel:j.string().optional(),description:j.string().optional(),disabled:j.boolean().optional().default(!1)})).min(1),optionClassName:j.string().default("flex items-center gap-3 px-4 py-3 rounded-lg border border-stone-200 cursor-pointer select-none transition-colors duration-150 hover:border-stone-300"),optionActiveClassName:j.string().default("border-blue-500 bg-blue-50"),optionLabelClassName:j.string().default("text-sm font-semibold text-stone-600"),optionActiveLabelClassName:j.string().default("text-sm font-semibold text-blue-500"),optionSublabelClassName:j.string().default("text-sm text-stone-400 shrink-0 ml-auto"),inputClassName:j.string().default("w-4 h-4 shrink-0 accent-blue-500")});import{jsx as Tk,jsxs as Ck}from"react/jsx-runtime";function ht({children:t,required:e,className:r,asteriskClassName:o}){return Ck("label",{className:r,children:[t,e&&Tk("span",{className:o,children:"*"})]})}import{useEffect as kg,useRef as Ek}from"react";function pt({name:t,required:e=!1,validate:r,initialValue:o}){let n=mt(),s=Ek(r);kg(()=>{s.current=r},[r]),kg(()=>n.getState().registerField(t,{required:e,validate:i=>s.current?.(i)??null,defaultValue:o}),[])}import{jsx as ol,jsxs as Rk}from"react/jsx-runtime";var Pk=t=>t?/^[\n\x20-\x7E]*$/:/^[\x20-\x7E]*$/;function Ok(t,e,r=!1){return t.replace(r?/[^\n\x20-\x7E]/g:/[^\x20-\x7E]/g,"").slice(0,e)}function Ak(t,e,r,o,n=!1){return s=>s.trim().length?o?o(s):s.length>e?`Must be ${e} characters or fewer.`:Pk(n).test(s)?null:"Only standard characters are allowed.":t?r:null}function De(t){let{inputRef:e}=t,{fieldId:r,label:o,placeholder:n,initialValue:s,required:i,showLabel:a,showError:l,autoCompleteType:u,fieldClassName:c,containerClassName:d,fieldLabelClassName:f,fieldErrorClassName:m,fieldAsteriskClassName:h,requiredText:g,disabled:y,maxLength:p,validate:b,sanitize:_,inputType:v,min:L,max:x,multiline:P,rows:X}=nn.parse(t),F=_??(Ne=>Ok(Ne,p,P)),tt=Ak(i,p,g,b,P);pt({name:r,required:i,validate:tt,initialValue:s});let{value:fe,setValue:rt,error:Wt,clearError:Ht,validate:zt}=ae(r);return Rk("div",{className:d,children:[a&&ol(ht,{required:i,className:f,asteriskClassName:h,children:o}),P?ol("textarea",{name:r,rows:X,autoComplete:u,placeholder:n,value:fe??"",onChange:Ne=>{rt(F(Ne.target.value)),Ht()},onBlur:zt,"data-error":!!Wt||void 0,className:c,disabled:y,maxLength:p}):ol("input",{type:v,ref:e,name:r,autoComplete:u,placeholder:n,value:fe??"",onChange:Ne=>{rt(F(Ne.target.value)),Ht()},onBlur:zt,"data-error":!!Wt||void 0,className:c,disabled:y,maxLength:p,min:L,max:x}),l&&ol(xe,{name:r,className:m})]})}import{z as Sc}from"zod";import{jsx as Nk}from"react/jsx-runtime";function Ik(t){let e=t.replace(/\D/g,""),r=/^\d{10}$/.test(e),o=/^1\d{10}$/.test(e);return r||o?null:"Please enter a valid 10-digit phone number."}function Dk(t){let e=t.replace(/\D/g,"");if(e.startsWith("1")&&e.length>10){e=e.slice(0,11);let r=e.slice(1);return`+1 (${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6,10)}`}return e=e.slice(0,10),e.length<=3?e:e.length<=6?`(${e.slice(0,3)}) ${e.slice(3)}`:`(${e.slice(0,3)}) ${e.slice(3,6)}-${e.slice(6)}`}var Lk=ne.extend({fieldId:Sc.string().default("phone"),placeholder:Sc.string().default("(586) 313-2480"),label:Sc.string().default("Phone number")});function Tg(t){let e=Lk.parse(t);return Nk(De,{...e,validate:Ik,sanitize:Dk})}import{z as nl}from"zod";import{jsx as Uk}from"react/jsx-runtime";function jk(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())?null:"Please enter a valid email address."}var Mk=ne.extend({fieldId:nl.string().default("email"),placeholder:nl.string().default("Email"),label:nl.string().default("Email"),autoCompleteType:nl.string().default("email")});function Cg(t){let e=Mk.parse(t);return Uk(De,{...e,validate:jk})}import{jsx as ao,jsxs as xc}from"react/jsx-runtime";function Eg(t){let{fieldId:e,label:r,required:o,showLabel:n,showError:s,containerClassName:i,fieldLabelClassName:a,fieldErrorClassName:l,fieldAsteriskClassName:u,requiredText:c,disabled:d,options:f,minSelections:m,maxSelections:h,initialValue:g,tooFewText:y,tooManyText:p,optionClassName:b,optionActiveClassName:_,optionLabelClassName:v,optionActiveLabelClassName:L,optionSublabelClassName:x,inputClassName:P}=xg.parse(t),X=h===1,F=X&&m===0;function tt(N){return o&&N.length===0?c:N.length<m?y??`Please select at least ${m}.`:N.length>h?p??`Please select at most ${h}.`:null}pt({name:e,required:o,initialValue:g??[],validate:tt});let{value:fe,error:rt,setValue:Wt,setError:Ht,validate:zt}=ae(e),Ne=fe??[];function S(N){let ee=X?Ne.includes(N)&&F?[]:[N]:Ne.includes(N)?Ne.filter(Q=>Q!==N):[...Ne,N];if(ee.length>h){Ht(p??`Please select at most ${h}.`);return}Wt(ee),zt()}function q(N){N.currentTarget.contains(N.relatedTarget)||zt()}return xc("div",{className:i,children:[n&&ao(ht,{required:o,className:a,asteriskClassName:u,children:r}),ao("div",{className:"space-y-2",onBlur:q,tabIndex:-1,"data-error":!!rt||void 0,"aria-invalid":!!rt||void 0,children:f.map(N=>{let ee=Ne.includes(N.value),Q=d||N.disabled;return xc("label",{className:`flex items-center gap-3 ${b} ${ee?_:""} ${Q?"opacity-50 cursor-not-allowed":""}`,children:[ao("input",{type:F?"checkbox":X?"radio":"checkbox",name:e,checked:ee,disabled:Q,onChange:()=>S(N.value),className:P}),xc("div",{className:"flex-1 min-w-0",children:[ao("span",{className:ee?L:v,children:N.label}),N.description&&ao("p",{className:"text-xs text-stone-400 mt-0.5 leading-snug",children:N.description})]}),N.sublabel&&ao("span",{className:x,children:N.sublabel})]},N.value)})}),s&&ao(xe,{name:e,className:l})]})}import{useEffect as Fk}from"react";function kc({locationInputRef:t,isApplyingAutocompleteRef:e,setEventLocation:r,onCoordsResolved:o}){Fk(()=>{let n=window;function s(){if(!t.current||!n.google)return;let i=new n.google.maps.places.Autocomplete(t.current,{types:["establishment","geocode"],componentRestrictions:{country:"us"},fields:["formatted_address","name","geometry"]});i.addListener("place_changed",()=>{let a=i.getPlace(),l=a.formatted_address?.trim()??"",u=a.name?.trim()??"",c=u.toLowerCase(),d=l.toLowerCase(),f=u&&l&&!d.startsWith(c)?`${u}, ${l}`:l||u;e.current=!0,t.current&&(t.current.value=f),r(f),a.geometry?.location&&o?.({lat:a.geometry.location.lat(),lng:a.geometry.location.lng()}),requestAnimationFrame(()=>{e.current=!1})})}n.google?s():window.addEventListener("google-maps-loaded",s,{once:!0})},[e,t,r,o])}import{useRef as Pg}from"react";import{useEffect as $k}from"react";function Tc(){return $k(()=>{let t=process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;t&&ug(t).then(()=>window.dispatchEvent(new Event("google-maps-loaded"))).catch(()=>{})},[]),null}import{z as Cc}from"zod";import{Fragment as qk,jsx as Og,jsxs as Vk}from"react/jsx-runtime";var Bk=nn.extend({fieldId:Cc.string().default("eventLocation"),label:Cc.string().default("Event location"),placeholder:Cc.string().default("Search for a venue or enter an address\u2026")});function Ag(t){let e=Pg(null),r=Pg(!1),o=Bk.parse(t),{setValue:n,clearError:s}=ae(o.fieldId);function i(a){return a.replace(/<[^>]*>/g,"").trimStart().slice(0,255)}return kc({locationInputRef:e,isApplyingAutocompleteRef:r,setEventLocation:a=>{n(i(a)),s()}}),Vk(qk,{children:[Og(Tc,{}),Og(De,{...o,inputRef:e})]})}import{useEffect as Wk,useRef as Hk}from"react";import{z as et}from"zod";import{jsx as Jk}from"react/jsx-runtime";var zk="yyyy-MM-dd",Ec="HH:mm",Gk=ne.extend({fieldId:et.string().default("time"),label:et.string().default("Start time"),autoCompleteType:et.string().default("off"),inputType:et.literal("time").default("time"),minTime:et.string().optional(),maxTime:et.string().optional(),closedSpans:et.array(et.object({from:et.string(),to:et.string()})).optional(),minimumNoticeHours:et.number().nullable().optional(),dateFieldId:et.string().default("date"),timezone:et.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone)});function Vt(t){return Je(t,Ec,new Date)}function Rg(t){return Ue(Vt(t),"h:mm a")}function Kk(t){return t.replace(/[^\d:]/g,"").slice(0,5)}function lo(t){let{minTime:e,maxTime:r,closedSpans:o,minimumNoticeHours:n,dateFieldId:s,timezone:i,...a}=Gk.parse(t),u=He()[s],{value:c,validate:d}=ae(a.fieldId),f=Hk(!0);Wk(()=>{if(f.current){f.current=!1;return}c&&d()},[u,n,e,r]);function m(g){if(!/^\d{2}:\d{2}$/.test(g)||!to(Vt(g)))return"Please enter a valid time.";if(e&&We(Vt(g),Vt(e)))return`Please choose a time after ${Rg(e)}.`;if(r&&jt(Vt(g),Vt(r)))return`Please choose a time before ${Rg(r)}.`;if(o?.some(y=>!We(Vt(g),Vt(y.from))&&!jt(Vt(g),Vt(y.to))))return"This time is unavailable.";if(n&&u){let y=Je(`${u} ${g}`,`${zk} ${Ec}`,new Date);if(!to(y))return"Please enter a valid date and time.";let p=Ju(y,i),b=sh(Vo(new Date,n));if(We(p,b)){let _=ws(b,i),v=Ue(_,"MMM d 'at' h:mm a");return`Please select a time at least ${n} hours from now (after ${v}).`}}return null}let h=a.initialValue??(n?Ue(Mm(Vo(new Date,n),5),Ec):void 0);return Jk(De,{...a,initialValue:h,validate:m,sanitize:Kk})}import{z as cr}from"zod";import{jsx as Zk}from"react/jsx-runtime";var Pr="yyyy-MM-dd";function Yk(t,e,r,o){let n=Je(t,Pr,new Date);return!to(n)||Ue(n,Pr)!==t?"Please enter a valid date.":e&&We(n,Je(e,Pr,new Date))?`Please choose ${e} or later.`:r&&jt(n,Je(r,Pr,new Date))?`Please choose ${r} or earlier.`:o?.includes(t)?"This date is unavailable. Please choose another.":null}function Xk(t){return t.replace(/[^\d-]/g,"").slice(0,10)}var Qk=ne.extend({fieldId:cr.string().default("date"),label:cr.string().default("Event date"),autoCompleteType:cr.string().default("off"),inputType:cr.literal("date").default("date"),minimumNoticeHours:cr.number().nullable().optional(),minDate:cr.date().optional(),maxDate:cr.date().optional(),unavailableDates:cr.array(cr.date()).optional()});function sn(t){let{minDate:e,maxDate:r,unavailableDates:o,minimumNoticeHours:n,...s}=Qk.parse(t),i=e??(n?xt(Vo(new Date,n)):xt(new Date)),a=Ue(i,Pr),l=r?Ue(r,Pr):void 0,u=o?.map(f=>Ue(f,Pr));function c(f){return Yk(f,a,l,u)}let d=s.initialValue??(n?Ue(xt(Vo(new Date,n)),Pr):a);return Zk(De,{...s,initialValue:d,min:a,max:l,validate:c,sanitize:Xk})}import{z as Or}from"zod";import{jsx as oT}from"react/jsx-runtime";function eT(t){return t.replace(/[^0-9]/g,"").slice(0,255)}var tT=ne.extend({fieldId:Or.string().default("discreteNumber"),placeholder:Or.string().default("10"),label:Or.string().default("Number of guests"),min:Or.number().default(10),max:Or.number().default(5e3),minErrorText:Or.string().optional(),maxErrorText:Or.string().optional(),step:Or.number().default(1)});function rT(t,e,r,o){return n=>{let s=Number(n);return Number.isNaN(s)?"Please enter a valid number.":s<t?r??`Must be at least ${t}.`:s>e?o??`Must be ${e} or fewer.`:null}}function Ig(t){let e=tT.parse(t),{min:r,max:o,minErrorText:n,maxErrorText:s,...i}=e;return oT(De,{...i,validate:rT(r,o,n,s),sanitize:eT})}import{z as sl}from"zod";import{jsx as Pc,jsxs as sT}from"react/jsx-runtime";var nT=ne.extend({min:sl.number().default(0),max:sl.number().default(100),step:sl.number().default(1),onChange:sl.any().optional()});function Dg(t){let{fieldId:e,label:r,min:o,max:n,step:s,required:i,showLabel:a,showError:l,fieldClassName:u,containerClassName:c,fieldLabelClassName:d,fieldAsteriskClassName:f,fieldErrorClassName:m,initialValue:h,requiredText:g,disabled:y,onChange:p}=nT.parse(t);function b(X){return i&&X==null?g:X<o?`Must be at least ${o}.`:X>n?`Must be ${n} or fewer.`:null}pt({name:e,required:i,validate:b,initialValue:h??o});let{value:_,setValue:v,error:L,clearError:x,validate:P}=ae(e);return sT("div",{className:c,children:[a&&Pc(ht,{required:i,className:d,asteriskClassName:f,children:r}),Pc("input",{type:"range",min:o,max:n,step:s,value:_??o,disabled:y,onChange:X=>{let F=Number(X.target.value);v(F),x(),p?.(F)},onBlur:P,"data-error":!!L||void 0,className:u}),l&&Pc(xe,{name:e,className:m})]})}import{z as Lg}from"zod";import{jsx as Oc,jsxs as Ng}from"react/jsx-runtime";var iT=ne.extend({checkboxClassName:Lg.string().default("mt-0.5 h-5 w-5 shrink-0 rounded"),labelClassName:Lg.string().default("pt-0.5 text-sm leading-snug")});function jg({children:t,...e}){let{fieldId:r,required:o,requiredText:n,showError:s,disabled:i,containerClassName:a,fieldErrorClassName:l,checkboxClassName:u,labelClassName:c,initialValue:d}=iT.parse(e);pt({name:r,required:!1,validate:o?g=>g?null:n:void 0,initialValue:d??!1});let{value:f,setValue:m,validate:h}=ae(r);return Ng("div",{className:a,children:[Ng("div",{className:"flex items-start gap-3 px-1 py-2 min-h-[44px]",children:[Oc("input",{type:"checkbox",id:r,checked:f??!1,onChange:g=>{m(g.target.checked),o&&h()},disabled:i,className:u}),Oc("label",{htmlFor:r,className:c,children:t})]}),s&&Oc(xe,{name:r,className:l})]})}import{jsx as Mg}from"react/jsx-runtime";function Ug({name:t,label:e="Quantity",initalVal:r=0,showLabel:o=!0,showError:n=!0,showIncrement:s=!0,showDecrement:i=!0}){return Mg("div",{children:Mg(ht,{required:!0,children:e})})}import{z as uo}from"zod";import{jsx as il,jsxs as Fg}from"react/jsx-runtime";var aT=nn.extend({fieldId:uo.string().default("nameFields"),outerClassName:uo.string().default("flex flex-col md:flex-row w-full gap-4"),firstNamePlaceholder:uo.string().default("First name"),lastNamePlaceholder:uo.string().default("Last name"),firstNameInitialValue:uo.string().default(""),lastNameInitialValue:uo.string().default(""),childClassName:uo.string().default("flex flex-col w-full md:flex-1 md:min-w-0")});function lT({className:t}){let{error:e}=ae("firstName"),{error:r}=ae("lastName"),o=e??r;return o?il("span",{className:t,children:o}):null}function $g(t){let e=aT.parse({...t}),{outerClassName:r,firstNamePlaceholder:o,lastNamePlaceholder:n,firstNameInitialValue:s,lastNameInitialValue:i,childClassName:a,...l}=e;return Fg("div",{className:"flex flex-col w-full gap-1",children:[Fg("div",{className:r,children:[il(De,{...l,fieldId:"firstName",label:"First name",placeholder:o,initialValue:s,autoCompleteType:"given-name",containerClassName:a,showError:!1}),il(De,{...l,fieldId:"lastName",label:"Last name",placeholder:n,initialValue:i,autoCompleteType:"family-name",containerClassName:a,showError:!1})]}),il(lT,{className:l.fieldErrorClassName})]})}import{z as ke}from"zod";import{jsx as al,jsxs as Bg}from"react/jsx-runtime";var uT=ne.extend({fieldId:ke.string().default("dateTime"),outerClassName:ke.string().default("flex flex-col md:flex-row w-full gap-4"),childClassName:ke.string().default("flex flex-col w-full md:flex-1 md:min-w-0"),dateLabel:ke.string().default("Event date"),dateFieldId:ke.string().default("date"),minDate:ke.date().optional(),maxDate:ke.date().optional(),unavailableDates:ke.array(ke.date()).optional(),minimumNoticeHours:ke.number().nullable().optional(),timeLabel:ke.string().default("Start time"),timeFieldId:ke.string().default("time"),closedSpans:ke.array(ke.object({from:ke.string(),to:ke.string()})).optional(),timezone:ke.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:ke.string().optional(),timeInitialValue:ke.string().optional()});function qg(t){let{minTime:e,maxTime:r,timeBounds:o,...n}=t,{fieldId:s,outerClassName:i,childClassName:a,inputType:l,dateLabel:u,dateFieldId:c,minDate:d,maxDate:f,unavailableDates:m,minimumNoticeHours:h,timeLabel:g,timeFieldId:y,closedSpans:p,timezone:b,dateInitialValue:_,timeInitialValue:v,...L}=uT.parse(n),x=rl(He()),P=o?o(x):void 0,X=P?.min??(typeof e=="function"?e(x):e),F=P?.max??(typeof r=="function"?r(x):r);return Bg("div",{className:"flex flex-col w-full gap-1",children:[Bg("div",{className:i,children:[al(sn,{...L,inputType:"date",fieldId:c,label:u,minDate:d,maxDate:f,unavailableDates:m,minimumNoticeHours:h,containerClassName:a,showError:!1,initialValue:_??L.initialValue}),al(lo,{...L,inputType:"time",fieldId:y,label:g,minTime:X,maxTime:F,closedSpans:p,minimumNoticeHours:h,dateFieldId:c,timezone:b,containerClassName:a,showError:!1,initialValue:v??L.initialValue})]}),al(xe,{name:c,className:L.fieldErrorClassName}),al(xe,{name:y,className:L.fieldErrorClassName})]})}import{z as he}from"zod";import{jsx as an,jsxs as Ac}from"react/jsx-runtime";var cT=ne.extend({fieldId:he.string().default("dateTimeRange"),dateLabel:he.string().default("Event date"),dateFieldId:he.string().default("date"),minDate:he.date().optional(),maxDate:he.date().optional(),unavailableDates:he.array(he.date()).optional(),minimumNoticeHours:he.number().nullable().optional(),startTimeLabel:he.string().default("Start time"),startTimeFieldId:he.string().default("startTime"),endTimeLabel:he.string().default("End time"),endTimeFieldId:he.string().default("endTime"),closedSpans:he.array(he.object({from:he.string(),to:he.string()})).optional(),timezone:he.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:he.string().optional(),startTimeInitialValue:he.string().optional(),endTimeInitialValue:he.string().optional()});function Vg(t){let{fieldId:e,inputType:r,dateLabel:o,dateFieldId:n,minDate:s,maxDate:i,unavailableDates:a,minimumNoticeHours:l,startTimeLabel:u,startTimeFieldId:c,endTimeLabel:d,endTimeFieldId:f,closedSpans:m,timezone:h,dateInitialValue:g,startTimeInitialValue:y,endTimeInitialValue:p,...b}=cT.parse(t),v=He()[c];return Ac("div",{className:"flex flex-col w-full gap-1",children:[Ac("div",{className:"flex flex-col md:flex-row w-full gap-4",children:[an(sn,{...b,inputType:"date",fieldId:n,label:o,minDate:s,maxDate:i,unavailableDates:a,minimumNoticeHours:l,containerClassName:"flex flex-col w-full md:flex-1 md:min-w-0",showError:!1,initialValue:g??b.initialValue}),Ac("div",{className:"flex flex-row gap-4 md:contents",children:[an(lo,{...b,inputType:"time",fieldId:c,label:u,closedSpans:m,minimumNoticeHours:l,dateFieldId:n,timezone:h,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:y??b.initialValue}),an(lo,{...b,inputType:"time",fieldId:f,label:d,minTime:v,closedSpans:m,dateFieldId:n,timezone:h,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:p??b.initialValue})]})]}),an(xe,{name:n,className:b.fieldErrorClassName}),an(xe,{name:c,className:b.fieldErrorClassName}),an(xe,{name:f,className:b.fieldErrorClassName})]})}import{z as dr}from"zod";import{useRef as ll,useEffect as ul}from"react";import{jsx as ln,jsxs as cl}from"react/jsx-runtime";var dT=ne.extend({fieldId:dr.string().default("guestCount"),label:dr.string().default("Number of guests"),placeholder:dr.string().default("10"),min:dr.number().default(10),max:dr.number().default(5e3),step:dr.number().default(1),minErrorText:dr.string().optional(),maxErrorText:dr.string().optional(),sliderClassName:dr.string().default("flex-[3]")});function Wg(t){let{fieldId:e,label:r,placeholder:o,min:n,max:s,step:i,required:a,showLabel:l,showError:u,fieldClassName:c,containerClassName:d,fieldLabelClassName:f,fieldAsteriskClassName:m,fieldErrorClassName:h,initialValue:g,requiredText:y,minErrorText:p,maxErrorText:b,disabled:_,sliderClassName:v}=dT.parse(t);function L(S){if(!S?.trim())return a?y:null;let q=Number(S);return Number.isNaN(q)?"Please enter a valid number.":q<n?p??`Must be at least ${n}.`:q>s?b??`Must be ${s} or fewer.`:null}pt({name:e,required:a,validate:L,initialValue:g??String(n)});let{value:x,setValue:P,error:X,clearError:F,validate:tt}=ae(e),fe=ll(P),rt=ll(F),Wt=ll(tt);ul(()=>{fe.current=P},[P]),ul(()=>{rt.current=F},[F]),ul(()=>{Wt.current=tt},[tt]);let Ht=Number(x)||n,zt=Math.max(0,Math.min(100,(Ht-n)/(s-n)*100)),Ne=ll(null);return ul(()=>{let S=Ne.current;if(!S)return;let q=0,N=0;function ee(me){let{left:ye,width:Ct}=S.getBoundingClientRect(),Et=Math.max(0,Math.min(1,(me-ye)/Ct)),fo=n+(s-n)*Et;return String(Math.max(n,Math.min(s,Math.round(fo/i)*i)))}function Q(me){q=me.changedTouches[0].clientX,N=me.changedTouches[0].clientY,fe.current(ee(q)),rt.current()}function G(me){let ye=Math.abs(me.changedTouches[0].clientX-q),Ct=Math.abs(me.changedTouches[0].clientY-N);ye>Ct&&me.preventDefault(),fe.current(ee(me.changedTouches[0].clientX)),rt.current()}function ge(){Wt.current()}return S.addEventListener("touchstart",Q,{passive:!0}),S.addEventListener("touchmove",G,{passive:!1}),S.addEventListener("touchend",ge,{passive:!0}),()=>{S.removeEventListener("touchstart",Q),S.removeEventListener("touchmove",G),S.removeEventListener("touchend",ge)}},[]),cl("div",{className:d,children:[l&&ln(ht,{required:a,className:f,asteriskClassName:m,children:r}),cl("div",{className:"flex items-center gap-4",children:[cl("div",{className:`flex flex-[6] flex-col ${v}`,children:[ln("input",{ref:Ne,type:"range",min:n,max:s,step:i,value:Ht,disabled:_,onChange:S=>{P(S.target.value),F()},onBlur:tt,className:`w-full ${v}`,style:{"--slider-fill":`${zt}%`}}),cl("div",{className:"flex justify-between text-xs text-stone-400 mt-2 px-0.5",children:[ln("span",{children:n}),ln("span",{children:s})]})]}),ln("input",{type:"text",inputMode:"numeric",placeholder:o,value:x??"",disabled:_,onChange:S=>{P(S.target.value.replace(/[^0-9]/g,"").slice(0,5)),F()},onBlur:tt,"data-error":!!X||void 0,className:`flex-1 text-center ${c}`})]}),u&&ln(xe,{name:e,className:h})]})}import fT from"react";var pe=fT.createContext({});import*as un from"react";import{forwardRef as gT}from"react";var mT=Object.defineProperty,Hg=Object.getOwnPropertySymbols,hT=Object.prototype.hasOwnProperty,pT=Object.prototype.propertyIsEnumerable,zg=(t,e,r)=>e in t?mT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rc=(t,e)=>{for(var r in e||(e={}))hT.call(e,r)&&zg(t,r,e[r]);if(Hg)for(var r of Hg(e))pT.call(e,r)&&zg(t,r,e[r]);return t},yT=(t,e)=>{let r=un.useContext(pe),o=Rc(Rc({},r),t);return un.createElement("svg",Rc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),un.createElement("path",{d:"M10.5213 2.62368C11.3147 1.75255 12.6853 1.75255 13.4787 2.62368L14.4989 3.74391C14.8998 4.18418 15.4761 4.42288 16.071 4.39508L17.5845 4.32435C18.7614 4.26934 19.7307 5.23857 19.6757 6.41554L19.6049 7.92905C19.5771 8.52388 19.8158 9.10016 20.2561 9.50111L21.3763 10.5213C22.2475 11.3147 22.2475 12.6853 21.3763 13.4787L20.2561 14.4989C19.8158 14.8998 19.5771 15.4761 19.6049 16.071L19.6757 17.5845C19.7307 18.7614 18.7614 19.7307 17.5845 19.6757L16.071 19.6049C15.4761 19.5771 14.8998 19.8158 14.4989 20.2561L13.4787 21.3763C12.6853 22.2475 11.3147 22.2475 10.5213 21.3763L9.50111 20.2561C9.10016 19.8158 8.52388 19.5771 7.92905 19.6049L6.41553 19.6757C5.23857 19.7307 4.26934 18.7614 4.32435 17.5845L4.39508 16.071C4.42288 15.4761 4.18418 14.8998 3.74391 14.4989L2.62368 13.4787C1.75255 12.6853 1.75255 11.3147 2.62368 10.5213L3.74391 9.50111C4.18418 9.10016 4.42288 8.52388 4.39508 7.92905L4.32435 6.41553C4.26934 5.23857 5.23857 4.26934 6.41554 4.32435L7.92905 4.39508C8.52388 4.42288 9.10016 4.18418 9.50111 3.74391L10.5213 2.62368Z",stroke:"currentColor"}),un.createElement("path",{d:"M9 12L11 14L15 10",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},bT=gT(yT),Ic=bT;import*as cn from"react";import{forwardRef as ST}from"react";var _T=Object.defineProperty,Gg=Object.getOwnPropertySymbols,wT=Object.prototype.hasOwnProperty,vT=Object.prototype.propertyIsEnumerable,Kg=(t,e,r)=>e in t?_T(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dc=(t,e)=>{for(var r in e||(e={}))wT.call(e,r)&&Kg(t,r,e[r]);if(Gg)for(var r of Gg(e))vT.call(e,r)&&Kg(t,r,e[r]);return t},xT=(t,e)=>{let r=cn.useContext(pe),o=Dc(Dc({},r),t);return cn.createElement("svg",Dc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),cn.createElement("path",{d:"M7 12.5L10 15.5L17 8.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),cn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},kT=ST(xT),dl=kT;import*as dn from"react";import{forwardRef as PT}from"react";var TT=Object.defineProperty,Jg=Object.getOwnPropertySymbols,CT=Object.prototype.hasOwnProperty,ET=Object.prototype.propertyIsEnumerable,Yg=(t,e,r)=>e in t?TT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lc=(t,e)=>{for(var r in e||(e={}))CT.call(e,r)&&Yg(t,r,e[r]);if(Jg)for(var r of Jg(e))ET.call(e,r)&&Yg(t,r,e[r]);return t},OT=(t,e)=>{let r=dn.useContext(pe),o=Lc(Lc({},r),t);return dn.createElement("svg",Lc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),dn.createElement("path",{d:"M12 6L12 12L18 12",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),dn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},AT=PT(OT),fl=AT;import*as Os from"react";import{forwardRef as LT}from"react";var RT=Object.defineProperty,Xg=Object.getOwnPropertySymbols,IT=Object.prototype.hasOwnProperty,DT=Object.prototype.propertyIsEnumerable,Qg=(t,e,r)=>e in t?RT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nc=(t,e)=>{for(var r in e||(e={}))IT.call(e,r)&&Qg(t,r,e[r]);if(Xg)for(var r of Xg(e))DT.call(e,r)&&Qg(t,r,e[r]);return t},NT=(t,e)=>{let r=Os.useContext(pe),o=Nc(Nc({},r),t);return Os.createElement("svg",Nc({width:"1.5em",height:"1.5em",viewBox:"0 0 24 24",strokeWidth:1.5,fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),Os.createElement("path",{d:"M22 9V17C22 18.1046 21.1046 19 20 19H4C2.89543 19 2 18.1046 2 17V7C2 5.89543 2.89543 5 4 5H20C21.1046 5 22 5.89543 22 7V9ZM22 9H6",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},jT=LT(NT),jc=jT;import*as co from"react";import{forwardRef as $T}from"react";var MT=Object.defineProperty,Zg=Object.getOwnPropertySymbols,UT=Object.prototype.hasOwnProperty,FT=Object.prototype.propertyIsEnumerable,ey=(t,e,r)=>e in t?MT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mc=(t,e)=>{for(var r in e||(e={}))UT.call(e,r)&&ey(t,r,e[r]);if(Zg)for(var r of Zg(e))FT.call(e,r)&&ey(t,r,e[r]);return t},BT=(t,e)=>{let r=co.useContext(pe),o=Mc(Mc({},r),t);return co.createElement("svg",Mc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),co.createElement("path",{d:"M1.5 12.5L5.57574 16.5757C5.81005 16.8101 6.18995 16.8101 6.42426 16.5757L9 14",stroke:"currentColor",strokeLinecap:"round"}),co.createElement("path",{d:"M16 7L12 11",stroke:"currentColor",strokeLinecap:"round"}),co.createElement("path",{d:"M7 12L11.5757 16.5757C11.8101 16.8101 12.1899 16.8101 12.4243 16.5757L22 7",stroke:"currentColor",strokeLinecap:"round"}))},qT=$T(BT),Uc=qT;import*as fn from"react";import{forwardRef as zT}from"react";var VT=Object.defineProperty,ty=Object.getOwnPropertySymbols,WT=Object.prototype.hasOwnProperty,HT=Object.prototype.propertyIsEnumerable,ry=(t,e,r)=>e in t?VT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fc=(t,e)=>{for(var r in e||(e={}))WT.call(e,r)&&ry(t,r,e[r]);if(ty)for(var r of ty(e))HT.call(e,r)&&ry(t,r,e[r]);return t},GT=(t,e)=>{let r=fn.useContext(pe),o=Fc(Fc({},r),t);return fn.createElement("svg",Fc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),fn.createElement("path",{d:"M7 9L12 12.5L17 9",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),fn.createElement("path",{d:"M2 17V7C2 5.89543 2.89543 5 4 5H20C21.1046 5 22 5.89543 22 7V17C22 18.1046 21.1046 19 20 19H4C2.89543 19 2 18.1046 2 17Z",stroke:"currentColor"}))},KT=zT(GT),$c=KT;import*as mn from"react";import{forwardRef as QT}from"react";var JT=Object.defineProperty,oy=Object.getOwnPropertySymbols,YT=Object.prototype.hasOwnProperty,XT=Object.prototype.propertyIsEnumerable,ny=(t,e,r)=>e in t?JT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bc=(t,e)=>{for(var r in e||(e={}))YT.call(e,r)&&ny(t,r,e[r]);if(oy)for(var r of oy(e))XT.call(e,r)&&ny(t,r,e[r]);return t},ZT=(t,e)=>{let r=mn.useContext(pe),o=Bc(Bc({},r),t);return mn.createElement("svg",Bc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),mn.createElement("path",{d:"M20 5.99999L20 18C20 19.1046 19.1046 20 18 20H6C4.89543 20 4 19.1046 4 18V6C4 4.89543 4.89543 4 6 4H18C19.1045 4 19.9999 4.89543 20 5.99999Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),mn.createElement("path",{d:"M12 9V4",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},eC=QT(ZT),qc=eC;import*as hn from"react";import{forwardRef as nC}from"react";var tC=Object.defineProperty,sy=Object.getOwnPropertySymbols,rC=Object.prototype.hasOwnProperty,oC=Object.prototype.propertyIsEnumerable,iy=(t,e,r)=>e in t?tC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vc=(t,e)=>{for(var r in e||(e={}))rC.call(e,r)&&iy(t,r,e[r]);if(sy)for(var r of sy(e))oC.call(e,r)&&iy(t,r,e[r]);return t},sC=(t,e)=>{let r=hn.useContext(pe),o=Vc(Vc({},r),t);return hn.createElement("svg",Vc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),hn.createElement("path",{d:"M19.2609 9.69589L20.6455 18.6959C20.8319 19.9074 19.8945 21 18.6688 21H5.33122C4.10545 21 3.16809 19.9074 3.35448 18.6959L4.73909 9.69589C4.8892 8.72022 5.7287 8 6.71584 8H17.2842C18.2713 8 19.1108 8.72022 19.2609 9.69589Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),hn.createElement("path",{d:"M14 5C14 3.89543 13.1046 3 12 3C10.8954 3 10 3.89543 10 5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},iC=nC(sC),Wc=iC;import*as As from"react";import{forwardRef as cC}from"react";var aC=Object.defineProperty,ay=Object.getOwnPropertySymbols,lC=Object.prototype.hasOwnProperty,uC=Object.prototype.propertyIsEnumerable,ly=(t,e,r)=>e in t?aC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hc=(t,e)=>{for(var r in e||(e={}))lC.call(e,r)&&ly(t,r,e[r]);if(ay)for(var r of ay(e))uC.call(e,r)&&ly(t,r,e[r]);return t},dC=(t,e)=>{let r=As.useContext(pe),o=Hc(Hc({},r),t);return As.createElement("svg",Hc({width:"1.5em",height:"1.5em",viewBox:"0 0 24 24",strokeWidth:1.5,fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),As.createElement("path",{d:"M15 4L8 20",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},fC=cC(dC),ml=fC;import*as pn from"react";import{forwardRef as gC}from"react";var mC=Object.defineProperty,uy=Object.getOwnPropertySymbols,hC=Object.prototype.hasOwnProperty,pC=Object.prototype.propertyIsEnumerable,cy=(t,e,r)=>e in t?mC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zc=(t,e)=>{for(var r in e||(e={}))hC.call(e,r)&&cy(t,r,e[r]);if(uy)for(var r of uy(e))pC.call(e,r)&&cy(t,r,e[r]);return t},yC=(t,e)=>{let r=pn.useContext(pe),o=zc(zc({},r),t);return pn.createElement("svg",zc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),pn.createElement("path",{d:"M9.17218 14.8284L12.0006 12M14.829 9.17157L12.0006 12M12.0006 12L9.17218 9.17157M12.0006 12L14.829 14.8284",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),pn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},bC=gC(yC),hl=bC;function dy(t){return{label:(t.split(".").at(-1)??t).replace(/_/g," "),color:"gray"}}import{jsx as $e,jsxs as gn}from"react/jsx-runtime";var _C={"order.placed":{label:"Order placed",color:"blue",icon:Wc},"device.order_received":{label:"Received",color:"blue",icon:qc},"order.requested":{label:"Requested",color:"blue",icon:fl},"order.paid":{label:"Paid",color:"green",icon:jc},"device.order_acknowledged":{label:"Acknowledged",color:"blue",icon:Uc},"order.confirmed":{label:"Confirmed",color:"green",icon:dl},"order.confirmation_email_sent":{label:"Confirmation email sent",color:"green",icon:$c},"order.completed":{label:"Completed",color:"green",icon:Ic},"order.failed":{label:"Failed",color:"red",icon:hl},"order.canceled":{label:"Cancelled",color:"red",icon:ml},"order.cancelled":{label:"Cancelled",color:"red",icon:ml},"order.catering.requested":{label:"Requested",color:"blue",icon:fl},"order.catering.confirmed":{label:"Confirmed",color:"green",icon:dl},"order.catering.charge_failed":{label:"Charge failed",color:"red",icon:hl}};function fy(t){return _C[t]??dy(t)}var wC=new Set(["order.catering.requested","order.catering.confirmed","order.catering.charge_failed","order.canceled","order.cancelled"]);function my(t){let e=t.events.filter(i=>wC.has(i.event_name));if(!e.length)return null;let r=e[e.length-1],o=r.payload,n=r.event_name==="order.catering.confirmed"?"confirmed":r.event_name==="order.catering.requested"?"requested":"rejected",s=typeof o.userId=="string"?t.actorNames?.[o.userId]??o.userId:typeof o.deviceId=="number"?`Device #${o.deviceId}`:null;return{status:n,via:o.via??null,when:r.created_at,actorName:s}}function hy(t){let e=ds.ORDER_STATUS;switch(t.order_status){case e.REQUESTED:return{label:"Awaiting approval",color:"blue"};case e.CONFIRMED:return{label:"Confirmed",color:"green"};case e.CANCELLED:return t.is_catering?{label:"Rejected",color:"red"}:{label:"Cancelled",color:"red"};case e.PAID:case e.PARTIALLY_PAID:return{label:"Paid",color:"green"};case e.PREPARING:return{label:"Preparing",color:"blue"};case e.KITCHEN_DONE:case e.COMPLETED:return{label:"Completed",color:"green"};default:return{label:"Pending",color:"gray"}}}function py(t){let e=ds.ORDER_STATUS;return t.order_status===(t.is_catering?e.REQUESTED:e.STAGING)}function vC(t){return t<1e3?`${t}ms`:t<6e4?`${Math.round(t/1e3)}s`:t<36e5?`${Math.round(t/6e4)}m`:`${Math.round(t/36e5)}h`}var gy={root:"flex flex-col gap-6 min-w-0 text-white",statusPill:"text-sm font-semibold px-3 py-1 rounded-full",approval:"text-white/60 text-sm",approvalEmpty:"text-white/40 text-sm",timeline:"flex items-start overflow-x-auto pb-2",eventIcon:"w-10 h-10 rounded-xl shrink-0 flex items-center justify-center",eventLabel:"text-xs font-medium text-center",eventTime:"text-white/30 text-xs text-center",connectorLine:"h-px w-8 bg-white/20",connectorDelta:"text-white/30 text-xs",confirmButton:"w-full py-4 rounded-lg text-base font-bold text-white bg-green-600 hover:bg-green-500 disabled:opacity-60 transition-colors",confirmError:"text-red-400 text-xs text-center",colors:{blue:{bg:"bg-blue-500/20",text:"text-blue-400",dot:"bg-blue-500/60"},green:{bg:"bg-green-500/20",text:"text-green-400",dot:"bg-green-500/60"},red:{bg:"bg-red-500/20",text:"text-red-400",dot:"bg-red-500/60"},gray:{bg:"bg-white/10",text:"text-white/50",dot:"bg-white/60"}}};function yy(t){let e=gy,{colors:r,...o}=t??{},n=Object.fromEntries(Object.keys(e.colors).map(i=>[i,{...e.colors[i],...r?.[i]}])),s=Object.fromEntries(Object.entries(o).filter(([,i])=>i!==void 0));return{...e,...s,colors:n}}var SC={pos:"at the POS",dashboard:"from the dashboard",email_link:"via an emailed link"};function xC({order:t,can:e,onConfirm:r,confirming:o,confirmError:n,itemClasses:s}){let i=yy(s),a=hy(t),l=my(t),u=t.events,c=!!r&&e("catering.confirm")&&py(t);return gn("div",{className:i.root,children:[$e("div",{className:"flex items-center gap-2",children:$e("span",{className:`${i.statusPill} ${i.colors[a.color].bg} ${i.colors[a.color].text}`,children:a.label})}),$e("div",{className:"flex flex-col gap-1",children:l===null?$e("span",{className:i.approvalEmpty,children:"No approval recorded."}):l.status==="requested"?$e("span",{className:i.approval,children:"Awaiting approval."}):gn("span",{className:i.approval,children:[l.status==="confirmed"?"Confirmed":"Rejected",l.actorName&&` by ${l.actorName}`,l.via&&` ${SC[l.via]}`," on ",Ue(new Date(l.when),"MMM d, h:mm a")]})}),u.length>0&&$e("div",{className:i.timeline,children:u.map((d,f)=>{let m=fy(d.event_name),h=i.colors[m.color],g=f===u.length-1,y=m.icon;return gn("div",{className:"flex items-start shrink-0",children:[gn("div",{className:"flex flex-col items-center gap-2 min-w-20",children:[$e("div",{className:`${i.eventIcon} ${h.bg}`,children:y?$e(y,{width:18,height:18,className:h.text}):$e("div",{className:`w-2 h-2 rounded-full ${h.dot}`})}),$e("span",{className:`${i.eventLabel} ${h.text}`,children:m.label}),$e("span",{className:i.eventTime,children:Ue(new Date(d.created_at),"h:mm a")})]}),!g&&gn("div",{className:"flex flex-col items-center gap-1 mt-4 shrink-0",children:[$e("div",{className:i.connectorLine}),$e("span",{className:i.connectorDelta,children:vC(Fm(new Date(u[f+1].created_at),new Date(d.created_at)))})]})]},d.id)})}),c&&gn("div",{className:"flex flex-col gap-2",children:[$e("button",{onClick:r,disabled:o,className:i.confirmButton,children:o?"Confirming\u2026":"Confirm This Order"}),n&&$e("span",{className:i.confirmError,children:n})]})]})}import{jsx as Le,jsxs as ze}from"react/jsx-runtime";var by={root:"flex flex-col gap-1 min-w-0 text-white",line:"flex flex-col gap-1 py-2 border-b border-white/10 last:border-b-0",lineName:"text-sm font-semibold text-white",lineSublabel:"text-xs text-white/50",linePrice:"text-sm font-semibold text-white tabular-nums",addOn:"flex justify-between items-baseline gap-2 text-xs",addOnName:"text-white/60",addOnPrice:"text-white/40",totalsRow:"flex justify-between text-sm text-white/70",discountRow:"flex justify-between text-sm text-green-400",totalRow:"flex justify-between text-base font-bold text-white mt-2"};function _y(t){let e=Object.fromEntries(Object.entries(t??{}).filter(([,r])=>r!==void 0));return{...by,...e}}function wy(t){return`${t.quantity} guests \xD7 ${Ft(t.unitPrice)}/person`}function vy(t,e){return t.upcharge<=0?"included":`+${Ft(t.upcharge)}${e?"/person":""}`}function kC({order:t,promotion:e,tip:r=0,itemClasses:o}){let n=_y(o),s=bs(t,e,r);return ze("div",{className:n.root,children:[s.lines.map((i,a)=>ze("div",{className:n.line,children:[ze("div",{className:"flex justify-between items-start gap-2",children:[ze("div",{className:"min-w-0",children:[Le("p",{className:n.lineName,children:i.name}),i.perPerson?Le("p",{className:n.lineSublabel,children:wy(i)}):i.quantity>1&&ze("p",{className:n.lineSublabel,children:["\xD7",i.quantity]})]}),Le("span",{className:n.linePrice,children:Ft(i.lineTotal)})]}),i.addOns.length>0&&Le("div",{className:"flex flex-col gap-0.5 mt-1",children:i.addOns.map((l,u)=>ze("div",{className:n.addOn,children:[Le("span",{className:n.addOnName,children:l.name}),Le("span",{className:n.addOnPrice,children:vy(l,i.perPerson)})]},u))})]},a)),ze("div",{className:"flex flex-col gap-1 mt-2",children:[ze("div",{className:n.totalsRow,children:[Le("span",{children:"Subtotal"}),Le("span",{children:Ft(s.subtotal)})]}),s.discount>0&&ze("div",{className:n.discountRow,children:[Le("span",{children:"Discount"}),ze("span",{children:["-",Ft(s.discount)]})]}),ze("div",{className:n.totalsRow,children:[Le("span",{children:"Tax"}),Le("span",{children:Ft(s.tax)})]}),s.serviceFee>0&&ze("div",{className:n.totalsRow,children:[Le("span",{children:"Service fee"}),Le("span",{children:Ft(s.serviceFee)})]}),s.tip>0&&ze("div",{className:n.totalsRow,children:[Le("span",{children:"Tip"}),Le("span",{children:Ft(s.tip)})]}),ze("div",{className:n.totalRow,children:[Le("span",{children:"Total"}),Le("span",{children:Ft(s.total)})]})]})]})}sg(cg);ag(TC);export{jg as CheckboxField,Eg as ClickableField,Sg as ConditionalRenderer,sn as DateField,qg as DateTime,Vg as DateTimeRange,vg as DisclaimerText,Ig as DiscreteNumberField,fg as DynamicFormShell,Cg as EmailField,xe as FieldError,ht as FieldLabel,Wg as GuestCountField,yg as Header,Ug as IncrementField,Ua as LOCATION_ORDERING_TIMEZONE,Ag as LocationField,$g as NameFields,by as ORDER_ITEMIZED_DEFAULT_ITEM_CLASSES,gy as ORDER_STATUS_DEFAULT_ITEM_CLASSES,kC as OrderItemized,xC as OrderStatus,Tg as PhoneField,Iu as Platforms,_g as PricePreview,wg as SectionLabel,Dg as SliderField,hg as SubmitButton,De as TextField,lo as TimeField,my as deriveApproval,hy as deriveOrderStatus,Zj as divisionsFor,vy as formatAddOnPrice,wy as formatCateringLineLabel,tM as groupItemPortions,py as isConfirmable,Yu as isLocationClosedByWeeklySchedule,bs as itemizeOrder,qh as locationWindowOn,_y as mergeOrderItemizedItemClasses,yy as mergeOrderStatusItemClasses,Zt as parsePortion,kt as parsePortionKey,z0 as portionGlyph,Xo as portionKey,eM as portionLabel,Sh as portionRows,Da as portionWeight,rM as radialSectionPath,kh as remapPortion,fy as resolveEventDisplay,V0 as sectionLabel,Uu as selectionWeight,sg as setZorgoBoot,ag as setZorgoPathnameHook,Qj as splitUpcharge,VB as useCart,JB as useCateringConfig,XB as useCustomer,ae as useField,Za as useFormStatus,el as useFormValidity,He as useFormValues,HB as useHydrateMenu,Qx as useHydrateStore,zB as useItemCustomization,WB as useLocation,Xx as useMenu,qB as useModal,KB as usePayment,GB as usePromotions,YB as useRecommendations,pt as useRegisterField,xh as weightedUpcharges};
|
|
157
|
+
`)&&(r=r.slice(0,-1))),super.equals(e,r,o)}},n$=new nc;function sc(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
|
|
158
|
+
`));let r=[],o=t.split(/(\n|\r\n)/);o[o.length-1]||o.pop();for(let n=0;n<o.length;n++){let s=o[n];n%2&&!e.newlineIsToken?r[r.length-1]+=s:r.push(s)}return r}var ic=class extends so{constructor(){super(...arguments),this.tokenize=sc}get useLongestToken(){return!0}castInput(e,r){let{undefinedReplacement:o,stringifyReplacer:n=(s,i)=>typeof i>"u"?o:i}=r;return typeof e=="string"?e:JSON.stringify(Wa(e,null,null,n),null," ")}equals(e,r,o){return super.equals(e.replace(/,([\r\n])/g,"$1"),r.replace(/,([\r\n])/g,"$1"),o)}},Tp=new ic;function ac(t,e,r){return Tp.diff(t,e,r)}function Wa(t,e,r,o,n){e=e||[],r=r||[],o&&(t=o(n===void 0?"":n,t));let s;for(s=0;s<e.length;s+=1)if(e[s]===t)return r[s];let i;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),i=new Array(t.length),r.push(i),s=0;s<t.length;s+=1)i[s]=Wa(t[s],e,r,o,String(s));return e.pop(),r.pop(),i}if(t&&t.toJSON&&(t=t.toJSON()),typeof t=="object"&&t!==null){e.push(t),i={},r.push(i);let a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),s=0;s<a.length;s+=1)l=a[s],i[l]=Wa(t[l],e,r,o,l);e.pop(),r.pop()}else i=t;return i}import{create as sx}from"zustand";import{devtools as ix}from"zustand/middleware";var kr=sx()(ix((t,e)=>({logLevel:4,stack:[],openModal:r=>t({stack:[...e().stack,r]}),goBack:()=>{let r=e().stack;if(r.length>1){let o=r[r.length-1];if(!o)return;let n=r.slice(0,-1),s=n[n.length-1];o.displayStyle!=="dialog"&&s&&(n[n.length-1]={...s,workingData:null}),t({stack:n})}else t({stack:[]})},close:()=>t({stack:[]}),setWorkingData:(r,o=0)=>{if(e().logLevel<=1&&e().stack.length>1){let a=e().getWorkingData(),l=ac(a,r);console.log("[MODAL STORE] working data diff from old:",l)}let n=e().stack,s=n.length-1-o;if(s<0)return;let i=[...n];i[s]={...i[s],workingData:r},t({stack:i})},getWorkingData:(r=0)=>{let o=e().stack;if(o.length!==0)return o[o.length-1-r]?.workingData}}),{name:"ModalStore"}));var ax="v3",lx=function(e){return e===3?"v3":e},Pp="https://js.stripe.com",ux="".concat(Pp,"/v3"),cx=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,dx=/^https:\/\/js\.stripe\.com\/(v3|[a-z]+)\/stripe\.js(\?.*)?$/,Cp="loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used",fx=function(e){return cx.test(e)||dx.test(e)},mx=function(){for(var e=document.querySelectorAll('script[src^="'.concat(Pp,'"]')),r=0;r<e.length;r++){var o=e[r];if(fx(o.src))return o}return null},Ep=function(e){var r=e&&!e.advancedFraudSignals?"?advancedFraudSignals=false":"",o=document.createElement("script");o.src="".concat(ux).concat(r);var n=document.head||document.body;if(!n)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return n.appendChild(o),o},hx=function(e,r){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"5.10.0",startTime:r})},xs=null,Ha=null,za=null,px=function(e){return function(r){e(new Error("Failed to load Stripe.js",{cause:r}))}},gx=function(e,r){return function(){window.Stripe?e(window.Stripe):r(new Error("Stripe.js not available"))}},yx=function(e){return xs!==null?xs:(xs=new Promise(function(r,o){if(typeof window>"u"||typeof document>"u"){r(null);return}if(window.Stripe&&e&&console.warn(Cp),window.Stripe){r(window.Stripe);return}try{var n=mx();if(n&&e)console.warn(Cp);else if(!n)n=Ep(e);else if(n&&za!==null&&Ha!==null){var s;n.removeEventListener("load",za),n.removeEventListener("error",Ha),(s=n.parentNode)===null||s===void 0||s.removeChild(n),n=Ep(e)}za=gx(r,o),Ha=px(o),n.addEventListener("load",za),n.addEventListener("error",Ha)}catch(i){o(i);return}}),xs.catch(function(r){return xs=null,Promise.reject(r)}))},bx=function(e,r,o){if(e===null)return null;var n=r[0],s=n.match(/^pk_test/),i=lx(e.version),a=ax;s&&i!==a&&console.warn("Stripe.js@".concat(i," was loaded on the page, but @stripe/stripe-js@").concat("5.10.0"," expected Stripe.js@").concat(a,". This may result in unexpected behavior. For more information, see https://docs.stripe.com/sdks/stripejs-versioning"));var l=e.apply(void 0,r);return hx(l,o),l},ks,Op=!1,Ap=function(){return ks||(ks=yx(null).catch(function(e){return ks=null,Promise.reject(e)}),ks)};Promise.resolve().then(function(){return Ap()}).catch(function(t){Op||console.warn(t)});var Rp=function(){for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];Op=!0;var n=Date.now();return Ap().then(function(s){return bx(s,r,n)})};import{create as Sx}from"zustand";import{devtools as xx}from"zustand/middleware";import ir from"zod";import{create as _x}from"zustand";import{devtools as wx}from"zustand/middleware";var Ga=globalThis;function io(t){if(!Ga.document)return null;let e=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=Ga.document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return r?decodeURIComponent(r[1]):null}function lc(t,e,r=365){Ga.document&&(Ga.document.cookie=`${t}=${encodeURIComponent(e)}; path=/; max-age=${r*86400}; SameSite=Lax`)}var Ip=ir.object({shortUrlPath:ir.string().optional().default("/s"),siteUrl:ir.url().optional(),franchiseId:ir.union([ir.string(),ir.number()]).optional(),locationId:ir.union([ir.string(),ir.number()]).optional()});var vx=_x()(wx((t,e)=>({logLevel:1,config:Ip.parse({}),sessionData:{},sessionId:gs(),consentGiven:io("zorgo_consent")==="1",consentAnswered:io("zorgo_consent")!==null,anonymousId:io("zorgo_anon_id"),getSiteUrl:()=>{let r=e().config.siteUrl,o=typeof process<"u"?process.env.NEXT_PUBLIC_SITE_URL||process.env.NEXT_PUBLIC_BASE_URL:void 0,n=typeof globalThis<"u"&&"location"in globalThis&&globalThis.location?.origin?globalThis.location.origin:void 0,s=r||o||n;if(!s){e().logLevel<=3&&console.error("No site url found.");return}return s},getAnonymousId:()=>e().anonymousId,mergeSessionData:r=>{t(o=>{let n={...o.sessionData};for(let[s,i]of Object.entries(r))i===void 0?delete n[s]:n[s]=i;return{sessionData:n}})},setConsent:r=>{if(lc("zorgo_consent",r?"1":"0"),r&&!e().anonymousId){let o=`anon_${gs()}`;lc("zorgo_anon_id",o),t({consentGiven:!0,consentAnswered:!0,anonymousId:o})}else t({consentGiven:r,consentAnswered:!0})},initialize:({token:r,config:o})=>{let n=Ip.parse(o||{});t({token:r,config:n,consentGiven:io("zorgo_consent")==="1",consentAnswered:io("zorgo_consent")!==null,anonymousId:io("zorgo_anon_id")})}}),{name:"websiteCoreStore"})),Ie=vx;var Dp={logLevel:1,clientSecret:null,intentType:null,isLoading:!1,error:null,orderId:null,finalAmount:null},uc=!1,kx=Sx()(xx((t,e)=>({...Dp,start:async()=>{let r=K.getState().selectedLocation,o=process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY,n=process.env.NEXT_PUBLIC_STRIPE_ACCOUNT_OVERRIDE||r?.stripe_account_id;if(!o||!n)return null;let s=await Rp(o,{stripeAccount:n});if(!s){e().logLevel<=3&&console.error("Failed to load Stripe");return}t({stripe:s})},createOrder:async(r,o)=>{if(!r?.items?.length||!o?.location_id)throw new Error("Order, location, and time_requested are required");let n={...r,method_id:2,location_id:o.location_id},{franchiseId:s}=Ie.getState().config,i=await Ut("/create-order",{method:"POST",body:JSON.stringify({order:n,anonymous_id:Ie.getState().getAnonymousId(),franchise_id:s?String(s):void 0})});if(!i.ok){let l=await i.json();throw new Error(l.error||`Server error: ${i.status}`)}return(await i.json()).orderId},createPaymentIntentForOrder:async(r,o,n)=>{let s=await Ut("/create-payment-intent",{method:"POST",body:JSON.stringify({orderId:r,tipAmount:o,deliveryFeeCents:n||0})});if(!s.ok){let u=await s.json();throw new Error(u.error||`Server error: ${s.status}`)}let i=await s.json(),a=i.charges?.total??i.amount??0,l=i.type==="setup_intent"?"setup_intent":"payment_intent";return{clientSecret:i.clientSecret,amount:a,intentType:l}},confirmPayment:async(r,o,n,s,i)=>{let a=r,l={name:`${i.first_name} ${i.last_name}`.trim()||void 0,email:i.email,phone:fh(i.phone)},u=e().intentType,c={return_url:s,payment_method_data:{billing_details:l}},d;return u==="setup_intent"?{error:d}=await a.confirmSetup({elements:o,clientSecret:n,confirmParams:c}):{error:d}=await a.confirmPayment({elements:o,clientSecret:n,confirmParams:c}),d?{success:!1,error:d.message}:u!=="setup_intent"?{success:!0,paymentIntentId:(await a.retrievePaymentIntent(n)).paymentIntent?.id}:{success:!0}},getReturnStatus:r=>{let o=typeof r=="string"?new URL(r):r,n=o.searchParams.get("redirect_status"),s=o.searchParams.get("setup_intent"),i=o.searchParams.get("payment_intent")??s??void 0,a=!!s,l=o.searchParams.get("amount"),u=Number(o.searchParams.get("order")),c=Number.isSafeInteger(u)&&u>0?u:void 0,d=o.searchParams.get("order_token")??void 0;return n?n==="succeeded"?{succeeded:!0,amount:l?parseFloat(l):void 0,paymentIntentId:i,isHold:a,orderId:c,orderToken:c?d:void 0}:{succeeded:!1,error:`Payment ${n}`,paymentIntentId:i,isHold:a}:{succeeded:!1,error:"No payment status found in URL",isHold:a}},mintOrderLinkToken:async(r,o)=>{if(!r||!o)return null;try{let n=await Ut(`/catering/order/${r}/link`,{method:"POST",body:JSON.stringify({email:o}),signal:AbortSignal.timeout(3e3)});if(!n.ok)return null;let s=await n.json();return typeof s?.token=="string"?s.token:null}catch{return null}},beginCheckout:async()=>{if(!(e().isLoading||uc)){uc=!0,t({isLoading:!0,error:null});try{let r=Z.getState().workingOrder,o=K.getState().selectedLocation,n=Z.getState().selectedTip??0,s=Z.getState().deliveryFeeCents??0;if(!o)throw new Error("Cannot start checkout without a selected location");if(!r)throw new Error("Cannot start checkout without a working order");let i=e().orderId;i||(i=await e().createOrder(r,o),t({orderId:i}));let{clientSecret:a,amount:l,intentType:u}=await e().createPaymentIntentForOrder(i,n,s);t({clientSecret:a,intentType:u,orderId:i,finalAmount:l,isLoading:!1,error:null})}catch(r){let o=r instanceof Error?r.message:"Failed to setup payment";throw t({isLoading:!1,error:o}),r}finally{uc=!1}}},reset:()=>t(Dp)}),{name:"PaymentStore"})),Me=kx;import{create as $x}from"zustand";var eg=yn(Qp(),1);import{z as Ps}from"zod";var pc=t=>(0,eg.default)(t).isLight()?"#000000":"#FFFFFF",Qa=t=>Ps.string().nullish().transform(e=>e??t),Zp=t=>Ps.number().nullish().transform(e=>e??t),tg=Ps.object({design_id:Zp(0),franchise_id:Zp(0),primary:Qa("#9943E9"),accent:Qa("#6636BF"),backgroundBase:Qa("#EBEBEB"),fontFamily:Qa("Inter"),created_at:Ps.string().optional(),updated_at:Ps.string().optional()}).transform(t=>({...t,foreground:pc(t.backgroundBase),primaryForeground:pc(t.primary),accentForeground:pc(t.accent)})),rg=tg.parse({});function og(t){return tg.parse(t??{})}import{devtools as Bx,persist as qx,createJSONStorage as Vx}from"zustand/middleware";var Wx="branding-assets",Hx=3600,zx=$x()(qx(Bx((t,e)=>({branding:rg,logoUrl:null,fetchFranchiseLogoUrl:async r=>{let o=[`franchises/${r}/logo.png`,`franchises/${r}/logo.jpg`];for(let n of o){let{data:s,error:i}=await M.storage.from(Wx).createSignedUrl(n,Hx);if(!i&&s?.signedUrl)return t({logoUrl:s.signedUrl}),console.log("logoUrl",s.signedUrl),s.signedUrl;console.log("error",i)}return t({logoUrl:null}),null},initialize:async()=>{let r=K.getState().franchiseId,{data:o,error:n}=await M.from("franchise_branding").select("*").eq("franchise_id",r).single();n||o&&t({branding:og(o)})}})),{name:"branding",storage:Vx(()=>wr()),skipHydration:_r,partialize:t=>({branding:t.branding})})),gc=zx;import{create as Gx}from"zustand";import{devtools as Kx}from"zustand/middleware";import{immer as Jx}from"zustand/middleware/immer";var Yx=Gx()(Kx(Jx(t=>({recommendations:[],isLoading:!1,error:null,strategy:"top_items",lastFetchedAt:null,fetchRecommendations:async e=>{t(r=>{r.isLoading=!0,r.error=null});try{let r=await Ut("/recommendations",{method:"POST",body:JSON.stringify(e)});if(!r.ok){let n=await r.json().catch(()=>null);throw new Error(n?.error??`Server error: ${r.status}`)}let o=await r.json();t(n=>{n.recommendations=o.recommendations??[],n.strategy=e.strategy??"top_items",n.isLoading=!1,n.lastFetchedAt=new Date})}catch(r){let o=r?.message??"Failed to fetch recommendations";t(n=>{n.error=o,n.isLoading=!1})}},setStrategy:e=>{t(r=>{r.strategy=e})},clear:()=>{t(e=>{e.recommendations=[],e.error=null,e.lastFetchedAt=null})}})),{name:"RecommendationStore"})),Bt=Yx;function ng(){let t=()=>`ses_${crypto.randomUUID()}`;if(typeof sessionStorage>"u")return t();let e="zorgo_session_id",r=sessionStorage.getItem(e);return r||(r=t(),sessionStorage.setItem(e,r)),r}function sg(t){if(!t)return;let e=new URLSearchParams(t),r=e.get("utm_source")||void 0,o=e.get("utm_medium")||void 0,n=e.get("utm_campaign")||void 0;if(!(!r&&!o&&!n))return{source:r,medium:o,campaign:n}}var ig=()=>Promise.resolve();function ag(t){ig=t}function qt(){lr(()=>{ig().catch(console.error)},[])}var lg=()=>typeof window>"u"?"/":window.location.pathname;function ug(t){lg=t}function qB(){let t=kr(r=>r.stack);return{current:t[t.length-1]??null,isOpen:t.length>0,depth:t.length,open:(r,o,n)=>kr.getState().openModal({type:r,props:o,displayStyle:n}),close:kr.getState().close,back:kr.getState().goBack,setWorkingData:kr.getState().setWorkingData,getWorkingData:kr.getState().getWorkingData}}function VB(){qt();let t=Z.getState(),e=Z(u=>u.workingOrder),r=Z(u=>u.selectedTip),{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}=mp(),l=Ze(()=>e.items.reduce((u,c)=>u+c.quantity,0),[e.items]);return{items:e.items,itemCount:l,isEmpty:l===0,customer:e.customer,promoCode:e.promo_code,tip:r,subtotal:o,discount:n,tax:s,serviceFee:i,total:a,addItem:t.addItem,removeItem:t.removeItem,updateItem:t.updateItem,resetCart:()=>{t.resetOrder(),t.setOrderType(2)},setCustomer:t.setCustomer,setLocationId:t.setLocationId,setOrderType:t.setOrderType,setTimeRequested:t.setTimeRequested,setTip:t.setTip,getItemTotal:u=>Sr(u),getOrder:()=>Z.getState().workingOrder,resolveShortUrl:u=>t.setCartFromURL(u,Ie.getState().token)}}function WB(t){qt();let e=K(u=>u.locations),r=K(u=>u.franchises),o=K(u=>u.selectedLocation),n=K(u=>u.setSelectedLocation),s=K(u=>u.getIsCurrentLocationOpen),i=Ze(()=>e.filter(u=>r.some(c=>c.franchise_id===u.franchise_id)),[e,r]),a=t?.autoSelectLocationId;lr(()=>{if(a==null||o)return;let u=i.find(c=>c.location_id===a);u&&n(u)},[a,o,i,n]);let l=!!t?.promptLocationSelection&&!o&&i.length>0;return{availableLocations:i,currentLocation:o,setLocation:n,getIsCurrentLocationOpen:s,needsLocationSelection:l}}function Xx(){qt();let t=$t(o=>o.items),e=$t(o=>o.categories);return{items:Ze(()=>t.filter(o=>!e.find(s=>s.category_id===o.category_id)?.is_catering),[t,e]),allItems:t,categories:e}}function Qx(t,e,r,o){let n=t.getState();o(n)&&r(n)(e)}function HB(t){Qx($t,t,e=>e.hydrate,e=>!e.items?.length)}function zB(t,e,r){qt();let o=r!=null,{allItems:n}=Xx(),s=Ze(()=>n.find(S=>S.base_item_id===t),[n,t]),[i,a]=Er(e?.item_id??null),[l,u]=Er(()=>{let S={};for(let q of e?.selections??[])S[q.rule_id]=q.selections.map(N=>Xo(`${N.type}:${N.id}`,N.portion));return S}),[c,d]=Er(()=>{let S={};for(let q of e?.components??[])S[Xo(String(q.id),q.portion)]=q.quantity_servings;return S}),[f,m]=Er(e?.quantity??1),h=Cr(S=>m(q=>Math.max(1,typeof S=="function"?S(q):S)),[]),[g,y]=Er(e?.comments??""),p=s?.variants.find(S=>S.item_id===i)??s?.variants[0],b=p?.portion_scheme??null,_=Cr(S=>{a(S.item_id),u({}),d({})},[]),v=Ze(()=>(p?.rules??s?.rules??[]).filter(S=>S.rule_id!=null),[p,s]),L=Cr((S,q,N,ee=1/0)=>{u(Q=>{let G=Q[S]??[],ge=Xo(q,N),me=G.findIndex(ye=>kt(ye).baseKey===q);return me!==-1?{...Q,[S]:G[me]===ge?G.filter(ye=>ye!==ge):G.map((ye,Ct)=>Ct===me?ge:ye)}:ee===1?{...Q,[S]:[ge]}:$u(G)+Da(N)>ee?Q:{...Q,[S]:[...G,ge]}})},[]),x=Cr(S=>{u(q=>{let N={};for(let[ee,Q]of Object.entries(q))N[Number(ee)]=Q.flatMap(G=>{let{baseKey:ge,portion:me}=kt(G);if(!me)return[G];let ye=Ch(me,S);return ye?[Xo(ge,ye[0])]:[]});return N})},[]),P=Cr((S,q)=>{u(N=>({...N,[S]:(N[S]??[]).filter(ee=>kt(ee).baseKey!==q)}))},[]),X=Ze(()=>v.map(S=>{let q=S.rule_id,N=l[q]??[],ee=vh(S),Q=new Map(ee.map(G=>[G.key,G]));return{rule:S,ruleId:q,keys:N,defs:ee,byKey:Q,charged:Th(N,G=>Q.get(G)?.basePrice??0,S.included_quantity??0)}}),[v,l]),F=Ze(()=>X.map(({rule:S,ruleId:q,keys:N,defs:ee,charged:Q})=>{let G=S.max_selection??1/0,ge=$u(N),me=ge>=G;return{...S,rule_id:q,max:G,selectedCount:ge,portionable:!!b&&!!S.is_portionable,subtext:Oh(S),satisfied:ge>=S.min_selection&&ge<=G,message:()=>ge<S.min_selection?`Choose at least ${S.min_selection} option${S.min_selection>1?"s":""}`:ge>G?`Choose no more than ${G} option${G>1?"s":""}`:null,options:ee.map(({basePrice:ye,...Ct})=>{let Et=N.find(Sy=>kt(Sy).baseKey===Ct.key),fo=Et?kt(Et).portion:null;return{...Ct,key:Et??Ct.key,portion:fo,coveredSections:fo?[Zt(fo).index]:[],coveredWhole:!!Et&&!fo,upcharge:Et?Q.get(Et):ye,selected:!!Et,disabled:me&&!Et&&G!==1,toggle:()=>L(q,Ct.key,null,G)}})}}),[X,b,L]),tt=Ze(()=>X.map(({rule:S,ruleId:q,keys:N,byKey:ee,charged:Q})=>({rule_id:q,group_name:S.group_name,selections:N.flatMap(G=>{let{baseKey:ge,portion:me}=kt(G),ye=ee.get(ge);return ye?[{id:ye.id,type:ye.type,quantity:1,upcharge:Q.get(G)??0,name:ye.name,portion:me}]:[]})})).filter(S=>S.selections.length>0),[X]),fe=Ze(()=>!s||!p?null:{item_id:p.item_id,base_item_id:s.base_item_id,category_id:s.category_id,name:p.name,quantity:f,price:p.price,components:(p.components??[]).flatMap(S=>kh(String(S.id),c,S.servings_per_item??1).map(({portion:q,value:N})=>({...S,portion:q,quantity_servings:N}))),selections:tt,comments:g},[s,p,f,c,tt,g]),rt=F.find(S=>!S.satisfied)??null,Wt=!!fe&&!rt,Ht=Cr(()=>!fe||F.some(S=>!S.satisfied)?null:(o?Z.getState().updateItem(fe,r):Z.getState().addItem(fe),fe),[fe,F,o,r]),zt=fe?Sr(fe):0,Ne=!!p?.display_price&&p.display_price<p.price;return{item:s,variant:p,variants:s?.variants??[],setVariant:_,ruleGroups:F,unmetRule:rt,canSubmit:Wt,submit:Ht,portionScheme:b,placeOption:L,clearOption:P,recutSelections:x,quantity:f,setQuantity:h,comments:g,setComments:y,setComponentServings:(S,q,N=null)=>d(ee=>{let Q={...ee};if(!N)for(let G of Object.keys(Q))kt(G).baseKey===String(S)&&delete Q[G];return Q[Xo(String(S),N)]=Math.max(0,q),Q}),price:zt,salePrice:Ne&&fe?Sr({...fe,display_price:p.display_price},!0):void 0,isEditMode:o,draft:fe}}function GB(){qt();let t=K(p=>p.selectedLocation),e=we(p=>p.activePromotions),r=Z(p=>p.workingOrder),o=Z(p=>p.selectedPromotion),n=r.promo_code,[s,i]=Er(null),[a,l]=Er(!1),u=ar(null),c=Ze(()=>r.items.reduce((p,b)=>p+(b.discount_amount??0),0),[r.items]),d=Ze(()=>Qo({order:r}),[r]),f=Ze(()=>{if(!o)return c;try{return er(o,r,new Date)}catch{return 0}},[c,o,r]),m=Ze(()=>{if(o||c<=0)return null;let p=new Map;for(let _ of r.items)!_.applied_promo_id||!_.discount_amount||p.set(_.applied_promo_id,(p.get(_.applied_promo_id)??0)+_.discount_amount);let b=Array.from(p.entries()).sort((_,v)=>v[1]-_[1])[0]?.[0];return e.find(_=>_.id===b)??null},[e,c,o,r.items]),h=o??m;lr(()=>{if(!t?.franchise_id)return;let p=!1;return l(!0),we.getState().getActivePromotions(t.franchise_id,t.location_id).finally(()=>{p||l(!1)}),()=>{p=!0}},[t?.franchise_id,t?.location_id]),lr(()=>{if(!n){i(null);return}if(o&&f>0){i(null);return}if(o?.min_purchase_amount&&d<o.min_purchase_amount){i(`Minimum purchase of $${(o.min_purchase_amount/100).toFixed(2)} required`);return}o&&i("Promotion not applicable")},[d,f,n,o]);let g=Cr(async p=>{let b=p.trim();if(b){if(!t?.franchise_id||!t?.location_id){i("Please select a location first");return}l(!0),i(null);try{let _=await we.getState().getPromotionByCode(b,t.franchise_id);if(!_){Z.getState().removeOrderPromotion(),i("Invalid promotion code");return}Z.getState().applyOrderPromotion(_)}catch{i("Unable to apply promotion")}finally{l(!1)}}},[t?.franchise_id,t?.location_id]);lr(()=>{Z.getState().workingOrder.promo_code||Z.getState().checkBestPromo()},[e]),lr(()=>{if(typeof window>"u")return;let b=new URLSearchParams(window.location.search).get("promo");!b||b===n||u.current===b||(u.current=b,g(b))},[g,n,t?.location_id]);let y=Cr(()=>{if(i(null),u.current=null,Z.getState().overrideOrderPromotion(null),typeof window<"u"){let p=new URL(window.location.href);p.searchParams.has("promo")&&(p.searchParams.delete("promo"),window.history.replaceState({},"",p.toString()))}},[]);return{promoCode:n??"",setPromoCode:p=>{p?g(p):y()},appliedPromo:h,discountAmount:f,error:s,loading:a,applyPromo:g,removePromo:y,activePromotions:e}}function KB(t={}){qt();let e=Me(d=>d.clientSecret),r=Me(d=>d.intentType),o=Me(d=>d.isLoading),n=Me(d=>d.error),s=Me(d=>d.stripe),i=Me(d=>d.finalAmount),a=Me(d=>d.orderId),l=Z(d=>d.workingOrder),u=e?{clientSecret:e,...t.appearance&&{appearance:t.appearance},defaultValues:{billingDetails:{name:(l.customer.first_name??"")+" "+(l.customer.last_name??""),email:l.customer.email,phone:l.customer.phone}}}:null,c=Me.getState().confirmPayment;return{clientSecret:e,intentType:r,stripe:s,elementOptions:u,total:i,orderId:a,isLoading:o,error:n,isReady:!!(e&&s),startCheckout:Me.getState().beginCheckout,resetCheckout:Me.getState().reset,submitPayment:c,paymentElementOptions:{layout:"accordion",fields:{billingDetails:{name:"never",email:"never",phone:"never",address:"auto"}}},getReturnStatus:Me.getState().getReturnStatus,mintOrderLinkToken:Me.getState().mintOrderLinkToken,getReturnUrl:Ie.getState().getSiteUrl}}function JB(){qt();let t=$t(r=>r.franchiseCateringConfig),e=$t(r=>r.franchiseDeliveryConfig);return{minimum_notice_hours:t.minimum_notice_hours,minimum_people_required:t.minimum_people_required,minimum_price:t.minimum_price,does_cater:t.does_cater,does_deliver:e.does_deliver,delivery_fee_cents:e.delivery_fee_cents,max_delivery_radius_miles:e.max_delivery_radius_miles,cents_per_mile:e.cents_per_mile}}function YB(){qt();let t=Bt(s=>s.recommendations),e=Bt(s=>s.isLoading),r=Bt(s=>s.error),o=Bt(s=>s.strategy),n=Bt(s=>s.lastFetchedAt);return{recommendations:t,isLoading:e,error:r,strategy:o,lastFetchedAt:n,refresh:s=>Bt.getState().fetchRecommendations(s),setStrategy:s=>Bt.getState().setStrategy(s),clear:()=>Bt.getState().clear()}}var Za=null,yc=null,cg={};function bc(){return yc||(yc=kp({source:"restaurant_site",getContext:()=>cg})),yc}function Zx(){qt();let t=Ie(g=>g.consentGiven),e=Ie(g=>g.anonymousId),r=Ie(g=>g.config),o=K(g=>g.franchiseId),n=lg(),s=ar(null);s.current||(s.current=Symbol("zorgo-tracking"));let[i,a]=Er(!1),l=ar(null),u=ar(Date.now()),c=ar(Date.now()),d=ar(0),f=ar(!1),m=ar(!1),h=ar(typeof window>"u"?void 0:sg(window.location.search));lr(()=>(Za===null&&(Za=s.current,a(!0)),()=>{Za===s.current&&(Za=null)}),[]),lr(()=>{if(!i)return;if(!t){f.current=!1;return}let g=ng(),y=typeof document<"u"&&document.referrer||void 0,p=r.franchiseId??o;cg={session_id:g,anonymous_id:e||null,franchise_id:p!=null?Number(p):null,location_id:r.locationId!=null?Number(r.locationId):null};let b=bc();f.current||(f.current=!0,m.current=!1,b.info(sr.session_started,{landing_page:n,referrer:y,utm:h.current}),d.current=1,c.current=Date.now());let _=()=>{m.current||(m.current=!0,l.current&&b.info(sr.page_exited,{path:l.current,duration_ms:Date.now()-u.current}),b.info(sr.session_ended,{duration_ms:Date.now()-c.current,pages_visited:d.current}))},v=()=>{document.visibilityState==="hidden"&&_()};return window.addEventListener("beforeunload",_),document.addEventListener("visibilitychange",v),()=>{window.removeEventListener("beforeunload",_),document.removeEventListener("visibilitychange",v)}},[i,t,e,o]),lr(()=>{if(!(!i||!t||!f.current)){if(l.current&&l.current!==n&&bc().info(sr.page_exited,{path:l.current,duration_ms:Date.now()-u.current}),l.current!==n){let g=l.current===null;bc().info(sr.page_viewed,{path:n,referrer:typeof document<"u"&&document.referrer||void 0,utm:g?h.current:void 0}),g||(d.current+=1)}l.current=n,u.current=Date.now()}},[n,t,i])}function XB(){qt(),Zx();let t=Z(s=>s.workingOrder.customer),e=Z.getState().setCustomer,r=Ie(s=>s.consentGiven),o=Ie(s=>s.consentAnswered),n=Ie(s=>s.anonymousId);return{customer:t,consentGiven:r,setCustomer:e,consentAnswered:o,setConsent:Ie.getState().setConsent,anonymousId:n}}function dg(t){return typeof window>"u"?Promise.reject(new Error("Google Maps can only load in the browser")):window.google?.maps?.places?Promise.resolve():new Promise((r,o)=>{let n=document.querySelector('script[src^="https://maps.googleapis.com/maps/api/js"]');if(n){n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>o(new Error("Maps script failed")),{once:!0});return}let s=document.createElement("script");s.src=`https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(t)}&libraries=places`,s.async=!0,s.defer=!0,s.onload=()=>r(),s.onerror=()=>o(new Error("Failed to load Google Maps")),document.head.appendChild(s)})}var el=null;async function ek(){try{let t=await fetch("/api/zorgo-token");if(!t.ok)return;let{token:e}=await t.json();return e}catch{return}}function fg(){return typeof window>"u"?Promise.resolve():el||(el=(async()=>{fp();let t,e=new Promise(o=>t=o);Sh(async()=>Ie.getState().token??await e),await Promise.all([K,$t,Z,gc].map(o=>o.persist.rehydrate())),Z.setState(o=>({workingOrder:{...o.workingOrder,method_id:2,type_id:2}}));let r=await ek();if(t(r??null),!r)throw new Error("Zorgo: missing token. Ensure app/api/zorgo-token exists and ZORGO_SITE_SECRET is set.");Ie.getState().initialize({token:r}),tk(),await K.getState().initialize({token:r})})(),el)}function tk(){let t=n=>{n&&Me.getState().start()},e=async n=>{let s=K.getState().franchiseId;s&&(await we.getState().getActivePromotions(s,n,"website").catch(console.error),Z.getState().checkBestPromo())},r=async n=>{n&&(await e(K.getState().selectedLocation?.location_id),$t.getState().start({franchiseId:n,platform:"website",visibilityMode:"runtime"}))},o={fireImmediately:!0};K.subscribe(n=>n.franchiseId,r,o),K.subscribe(n=>n.selectedLocation?.stripe_account_id,t,o),K.subscribe(n=>n.selectedLocation?.location_id,(n,s)=>{n&&Z.getState().setLocationId(n),n!==s&&e(n)},o)}import{createStore as rk}from"zustand";import{devtools as ok}from"zustand/middleware";import{immer as nk}from"zustand/middleware/immer";import{createContext as sk,useContext as ik}from"react";var _c=sk(null);function mt(){let t=ik(_c);if(!t)throw new Error("Must be used inside DynamicFormShell");return t}function wc({onSubmit:t}){return rk()(ok(nk((e,r)=>({values:{},fieldConfigs:{},fieldErrors:{},status:"idle",registerField:(o,n)=>(e(s=>{s.fieldConfigs[o]=n,o in s.values||(s.values[o]=n.defaultValue??"")}),()=>{e(s=>{delete s.fieldConfigs[o],delete s.fieldErrors[o]})}),setValue:(o,n)=>{e(s=>{s.values[o]=n})},clearError:o=>{e(n=>{delete n.fieldErrors[o],n.status="idle"})},validateField:o=>{let n=r().fieldConfigs[o];if(!n)return null;let s=r().values[o],i=n.required&&!s?"Required.":n.validate(s);return e(a=>{i?a.fieldErrors[o]=i:delete a.fieldErrors[o]}),i??null},setFieldError:(o,n)=>{r().fieldConfigs[o]&&e(i=>{i.fieldErrors[o]=n})},validateAll:()=>{let o={};return Object.keys(r().fieldConfigs).forEach(n=>{let s=r().validateField(n);s&&(o[n]=s)}),o},handleSubmit:async o=>{o.preventDefault();let n=r().validateAll();if(Object.keys(n).length>0){e(s=>{s.fieldErrors=n,s.status="error"});return}e(s=>{s.status="sending"});try{await t(r().values),e(s=>{s.status="sent"})}catch{e(s=>{s.status="error"})}}}))))}import{useMemo as ak,useRef as lk}from"react";import{jsx as mg}from"react/jsx-runtime";function hg({className:t,onSubmit:e,children:r}){let o=lk(e);o.current=e;let n=ak(()=>wc({onSubmit:(...s)=>o.current(...s)}),[]);return mg(_c.Provider,{value:n,children:mg("form",{onSubmit:n.getState().handleSubmit,className:t,children:r})})}import{useRef as mk}from"react";import{z as ol}from"zod";import{useStore as uk}from"zustand";function tl(){let t=mt(),e=uk(t,r=>r.status);return{status:e,isIdle:e==="idle",isSubmitting:e==="sending",isSubmitted:e==="sent",isError:e==="error"}}import{useStore as ck}from"zustand";function dk(t,e){return t.required&&(e==null||e==="")?"Required.":t.validate(e)}function rl(){let t=mt();return ck(t,e=>Object.entries(e.fieldConfigs).every(([r,o])=>dk(o,e.values[r])===null))}import{useStore as fk}from"zustand";function He(){let t=mt();return fk(t,e=>e.values)}import{jsx as pg,jsxs as pk}from"react/jsx-runtime";var hk=ol.object({label:ol.string().default("Submit"),loadingLabel:ol.string().default("Submitting..."),className:ol.string().default("")});function gg(t){let{labelFn:e,...r}=t,{label:o,loadingLabel:n,className:s}=hk.parse(r),i=rl(),{isSubmitting:a,isSubmitted:l}=tl(),u=He(),c=mt(),d=mk(null),f=!i||a||l,m=e?e(u):o;function h(){c.getState().validateAll(),setTimeout(()=>{d.current?.form?.querySelector("[data-field-error]")?.scrollIntoView({behavior:"smooth",block:"center"})},50)}return pk("div",{style:{position:"relative"},children:[pg("button",{ref:d,type:"submit",disabled:f,className:s,children:a?n:m}),f&&pg("div",{onClick:h,style:{position:"absolute",inset:0,cursor:"pointer"}})]})}import{useStore as yg}from"zustand";function ae(t){let e=mt(),r=yg(e,l=>l.values[t]),o=yg(e,l=>l.fieldErrors[t])??null;return{value:r,error:o,setValue:l=>e.getState().setValue(t,l),clearError:()=>e.getState().clearError(t),validate:()=>e.getState().validateField(t),setError:l=>e.getState().setFieldError(t,l)}}import{jsx as gk}from"react/jsx-runtime";function xe({name:t,className:e}){let{error:r}=ae(t);return r?gk("span",{"data-field-error":t,className:e,children:r}):null}import{jsx as bg,jsxs as yk}from"react/jsx-runtime";function _g({className:t,title:e,titleClassName:r,subtitle:o,subtitleClassName:n}){return yk("div",{className:t,children:[bg("h1",{className:r,children:e}),bg("p",{className:n,children:o})]})}import{useMemo as wg}from"react";import{jsx as ur,jsxs as xc}from"react/jsx-runtime";function bk(t,e){return e.flatMap(r=>{let o=t[`rule_${r.ruleId}`]??[];return r.options.filter(n=>o.includes(n.value)&&n.upcharge>0).map(n=>({id:`rule_${r.ruleId}_${n.value}`,name:n.label,priceCents:n.upcharge}))})}function vc({label:t,value:e,isTotal:r,isDiscount:o}){return r?ur("div",{className:"flex items-center justify-between pt-3 mt-1 border-t-2 border-zestia-red-500",children:ur("span",{className:"font-extrabold text-end text-zestia-red-500 text-xl",children:e})}):o?xc("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[ur("span",{className:"text-xs text-emerald-600 font-medium",children:t}),ur("span",{className:"text-xs font-semibold text-emerald-600",children:e})]}):xc("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[ur("span",{className:"text-xs text-stone-500",children:t}),ur("span",{className:"text-xs font-semibold text-stone-700",children:e})]})}function Sc(t){return`$${(t/100).toFixed(2)}`}function vg({items:t,ruleGroups:e=[],guestCountFieldId:r="guestCount",className:o}){let n=He(),{value:s}=ae(r),i=Number(s)||0,a=we(h=>h.allPromotions),l=[...t,...bk(n,e)],u=l.reduce((h,g)=>h+g.priceCents,0),c=wg(()=>{let h=t.find(g=>g.isBase);if(h?.active_promo_id)return a.find(g=>g.id===h.active_promo_id&&g.min_purchase_quantity)},[t,a]),d=wg(()=>!c||i<=0?u:Math.round(Bu(u,i,c.discount_value/100,c.min_purchase_quantity)),[c,i,u]),f=d*i,m=u>0&&d<u?((u-d)/u*100).toFixed(1):null;return xc("div",{className:o,children:[l.map(h=>ur(vc,{label:h.name,value:`${Sc(h.priceCents)}/person`},h.id)),m&&ur(vc,{isDiscount:!0,label:`Bulk discount (${m}% off)`,value:`-${Sc(u-d)}/person`}),ur(vc,{isTotal:!0,label:"Per-Person Cost",value:`${Sc(d)}/person`})]})}import{jsx as _k}from"react/jsx-runtime";function Sg({label:t,className:e}){return _k("h2",{className:e,children:t})}import{jsx as wk}from"react/jsx-runtime";function xg({children:t,className:e}){return wk("p",{className:e,children:t})}import{useState as vk,useEffect as Sk}from"react";function nl(t){let e={};for(let[r,o]of Object.entries(t))Array.isArray(o)&&o.every(n=>typeof n=="string")?e[r]=o.length===1?o[0]:o.length===0?void 0:o:e[r]=o;return e}import{Fragment as xk,jsx as kk}from"react/jsx-runtime";function kg({whenFormVal:t,whenFunction:e,whenMediaQuery:r,children:o}){let n=He(),[s,i]=vk(()=>r&&typeof window<"u"?window.matchMedia(r).matches:!1);return Sk(()=>{if(!r)return;let l=window.matchMedia(r);i(l.matches);let u=c=>i(c.matches);return l.addEventListener("change",u),()=>l.removeEventListener("change",u)},[r]),(t?t(nl(n)):!1)||(e?e():!1)||(r?s:!1)?kk(xk,{children:o}):null}import{z as j}from"zod";var ne=j.object({inputType:j.enum(["text","number","date","time"]).default("text"),fieldId:j.string(),label:j.string().optional(),placeholder:j.string().optional(),autoCompleteType:j.string().optional(),requiredText:j.string().default("Required."),required:j.boolean().default(!0),showLabel:j.boolean().default(!0),showError:j.boolean().default(!0),disabled:j.boolean().default(!1),fieldClassName:j.string().default("flex-1"),containerClassName:j.string().default("flex flex-col"),fieldLabelClassName:j.string().default("flex-1"),fieldErrorClassName:j.string().default("flex-1"),fieldAsteriskClassName:j.string().default("text-red-500"),initialValue:j.unknown().optional()}),i5=ne.extend({min:j.number().optional(),max:j.number().optional(),step:j.number().default(1)}),a5=ne.extend({min:j.string().optional(),max:j.string().default("23:59")}),nn=ne.extend({maxLength:j.number().default(256),validate:j.any(),sanitize:j.any(),min:j.string().optional(),max:j.string().optional(),multiline:j.boolean().default(!1),rows:j.number().default(5)}),Tg=ne.extend({minSelections:j.number().default(1),maxSelections:j.union([j.number(),j.literal(1/0)]).default(1),tooFewText:j.string().optional(),tooManyText:j.string().optional(),options:j.array(j.object({label:j.string(),value:j.string(),sublabel:j.string().optional(),description:j.string().optional(),disabled:j.boolean().optional().default(!1)})).min(1),optionClassName:j.string().default("flex items-center gap-3 px-4 py-3 rounded-lg border border-stone-200 cursor-pointer select-none transition-colors duration-150 hover:border-stone-300"),optionActiveClassName:j.string().default("border-blue-500 bg-blue-50"),optionLabelClassName:j.string().default("text-sm font-semibold text-stone-600"),optionActiveLabelClassName:j.string().default("text-sm font-semibold text-blue-500"),optionSublabelClassName:j.string().default("text-sm text-stone-400 shrink-0 ml-auto"),inputClassName:j.string().default("w-4 h-4 shrink-0 accent-blue-500")});import{jsx as Tk,jsxs as Ck}from"react/jsx-runtime";function ht({children:t,required:e,className:r,asteriskClassName:o}){return Ck("label",{className:r,children:[t,e&&Tk("span",{className:o,children:"*"})]})}import{useEffect as Cg,useRef as Ek}from"react";function pt({name:t,required:e=!1,validate:r,initialValue:o}){let n=mt(),s=Ek(r);Cg(()=>{s.current=r},[r]),Cg(()=>n.getState().registerField(t,{required:e,validate:i=>s.current?.(i)??null,defaultValue:o}),[])}import{jsx as sl,jsxs as Rk}from"react/jsx-runtime";var Pk=t=>t?/^[\n\x20-\x7E]*$/:/^[\x20-\x7E]*$/;function Ok(t,e,r=!1){return t.replace(r?/[^\n\x20-\x7E]/g:/[^\x20-\x7E]/g,"").slice(0,e)}function Ak(t,e,r,o,n=!1){return s=>s.trim().length?o?o(s):s.length>e?`Must be ${e} characters or fewer.`:Pk(n).test(s)?null:"Only standard characters are allowed.":t?r:null}function De(t){let{inputRef:e}=t,{fieldId:r,label:o,placeholder:n,initialValue:s,required:i,showLabel:a,showError:l,autoCompleteType:u,fieldClassName:c,containerClassName:d,fieldLabelClassName:f,fieldErrorClassName:m,fieldAsteriskClassName:h,requiredText:g,disabled:y,maxLength:p,validate:b,sanitize:_,inputType:v,min:L,max:x,multiline:P,rows:X}=nn.parse(t),F=_??(Ne=>Ok(Ne,p,P)),tt=Ak(i,p,g,b,P);pt({name:r,required:i,validate:tt,initialValue:s});let{value:fe,setValue:rt,error:Wt,clearError:Ht,validate:zt}=ae(r);return Rk("div",{className:d,children:[a&&sl(ht,{required:i,className:f,asteriskClassName:h,children:o}),P?sl("textarea",{name:r,rows:X,autoComplete:u,placeholder:n,value:fe??"",onChange:Ne=>{rt(F(Ne.target.value)),Ht()},onBlur:zt,"data-error":!!Wt||void 0,className:c,disabled:y,maxLength:p}):sl("input",{type:v,ref:e,name:r,autoComplete:u,placeholder:n,value:fe??"",onChange:Ne=>{rt(F(Ne.target.value)),Ht()},onBlur:zt,"data-error":!!Wt||void 0,className:c,disabled:y,maxLength:p,min:L,max:x}),l&&sl(xe,{name:r,className:m})]})}import{z as kc}from"zod";import{jsx as Nk}from"react/jsx-runtime";function Ik(t){let e=t.replace(/\D/g,""),r=/^\d{10}$/.test(e),o=/^1\d{10}$/.test(e);return r||o?null:"Please enter a valid 10-digit phone number."}function Dk(t){let e=t.replace(/\D/g,"");if(e.startsWith("1")&&e.length>10){e=e.slice(0,11);let r=e.slice(1);return`+1 (${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6,10)}`}return e=e.slice(0,10),e.length<=3?e:e.length<=6?`(${e.slice(0,3)}) ${e.slice(3)}`:`(${e.slice(0,3)}) ${e.slice(3,6)}-${e.slice(6)}`}var Lk=ne.extend({fieldId:kc.string().default("phone"),placeholder:kc.string().default("(586) 313-2480"),label:kc.string().default("Phone number")});function Eg(t){let e=Lk.parse(t);return Nk(De,{...e,validate:Ik,sanitize:Dk})}import{z as il}from"zod";import{jsx as Uk}from"react/jsx-runtime";function jk(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())?null:"Please enter a valid email address."}var Mk=ne.extend({fieldId:il.string().default("email"),placeholder:il.string().default("Email"),label:il.string().default("Email"),autoCompleteType:il.string().default("email")});function Pg(t){let e=Mk.parse(t);return Uk(De,{...e,validate:jk})}import{jsx as ao,jsxs as Tc}from"react/jsx-runtime";function Og(t){let{fieldId:e,label:r,required:o,showLabel:n,showError:s,containerClassName:i,fieldLabelClassName:a,fieldErrorClassName:l,fieldAsteriskClassName:u,requiredText:c,disabled:d,options:f,minSelections:m,maxSelections:h,initialValue:g,tooFewText:y,tooManyText:p,optionClassName:b,optionActiveClassName:_,optionLabelClassName:v,optionActiveLabelClassName:L,optionSublabelClassName:x,inputClassName:P}=Tg.parse(t),X=h===1,F=X&&m===0;function tt(N){return o&&N.length===0?c:N.length<m?y??`Please select at least ${m}.`:N.length>h?p??`Please select at most ${h}.`:null}pt({name:e,required:o,initialValue:g??[],validate:tt});let{value:fe,error:rt,setValue:Wt,setError:Ht,validate:zt}=ae(e),Ne=fe??[];function S(N){let ee=X?Ne.includes(N)&&F?[]:[N]:Ne.includes(N)?Ne.filter(Q=>Q!==N):[...Ne,N];if(ee.length>h){Ht(p??`Please select at most ${h}.`);return}Wt(ee),zt()}function q(N){N.currentTarget.contains(N.relatedTarget)||zt()}return Tc("div",{className:i,children:[n&&ao(ht,{required:o,className:a,asteriskClassName:u,children:r}),ao("div",{className:"space-y-2",onBlur:q,tabIndex:-1,"data-error":!!rt||void 0,"aria-invalid":!!rt||void 0,children:f.map(N=>{let ee=Ne.includes(N.value),Q=d||N.disabled;return Tc("label",{className:`flex items-center gap-3 ${b} ${ee?_:""} ${Q?"opacity-50 cursor-not-allowed":""}`,children:[ao("input",{type:F?"checkbox":X?"radio":"checkbox",name:e,checked:ee,disabled:Q,onChange:()=>S(N.value),className:P}),Tc("div",{className:"flex-1 min-w-0",children:[ao("span",{className:ee?L:v,children:N.label}),N.description&&ao("p",{className:"text-xs text-stone-400 mt-0.5 leading-snug",children:N.description})]}),N.sublabel&&ao("span",{className:x,children:N.sublabel})]},N.value)})}),s&&ao(xe,{name:e,className:l})]})}import{useEffect as Fk}from"react";function Cc({locationInputRef:t,isApplyingAutocompleteRef:e,setEventLocation:r,onCoordsResolved:o}){Fk(()=>{let n=window;function s(){if(!t.current||!n.google)return;let i=new n.google.maps.places.Autocomplete(t.current,{types:["establishment","geocode"],componentRestrictions:{country:"us"},fields:["formatted_address","name","geometry"]});i.addListener("place_changed",()=>{let a=i.getPlace(),l=a.formatted_address?.trim()??"",u=a.name?.trim()??"",c=u.toLowerCase(),d=l.toLowerCase(),f=u&&l&&!d.startsWith(c)?`${u}, ${l}`:l||u;e.current=!0,t.current&&(t.current.value=f),r(f),a.geometry?.location&&o?.({lat:a.geometry.location.lat(),lng:a.geometry.location.lng()}),requestAnimationFrame(()=>{e.current=!1})})}n.google?s():window.addEventListener("google-maps-loaded",s,{once:!0})},[e,t,r,o])}import{useRef as Ag}from"react";import{useEffect as $k}from"react";function Ec(){return $k(()=>{let t=process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;t&&dg(t).then(()=>window.dispatchEvent(new Event("google-maps-loaded"))).catch(()=>{})},[]),null}import{z as Pc}from"zod";import{Fragment as qk,jsx as Rg,jsxs as Vk}from"react/jsx-runtime";var Bk=nn.extend({fieldId:Pc.string().default("eventLocation"),label:Pc.string().default("Event location"),placeholder:Pc.string().default("Search for a venue or enter an address\u2026")});function Ig(t){let e=Ag(null),r=Ag(!1),o=Bk.parse(t),{setValue:n,clearError:s}=ae(o.fieldId);function i(a){return a.replace(/<[^>]*>/g,"").trimStart().slice(0,255)}return Cc({locationInputRef:e,isApplyingAutocompleteRef:r,setEventLocation:a=>{n(i(a)),s()}}),Vk(qk,{children:[Rg(Ec,{}),Rg(De,{...o,inputRef:e})]})}import{useEffect as Wk,useRef as Hk}from"react";import{z as et}from"zod";import{jsx as Jk}from"react/jsx-runtime";var zk="yyyy-MM-dd",Oc="HH:mm",Gk=ne.extend({fieldId:et.string().default("time"),label:et.string().default("Start time"),autoCompleteType:et.string().default("off"),inputType:et.literal("time").default("time"),minTime:et.string().optional(),maxTime:et.string().optional(),closedSpans:et.array(et.object({from:et.string(),to:et.string()})).optional(),minimumNoticeHours:et.number().nullable().optional(),dateFieldId:et.string().default("date"),timezone:et.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone)});function Vt(t){return Je(t,Oc,new Date)}function Dg(t){return Ue(Vt(t),"h:mm a")}function Kk(t){return t.replace(/[^\d:]/g,"").slice(0,5)}function lo(t){let{minTime:e,maxTime:r,closedSpans:o,minimumNoticeHours:n,dateFieldId:s,timezone:i,...a}=Gk.parse(t),u=He()[s],{value:c,validate:d}=ae(a.fieldId),f=Hk(!0);Wk(()=>{if(f.current){f.current=!1;return}c&&d()},[u,n,e,r]);function m(g){if(!/^\d{2}:\d{2}$/.test(g)||!to(Vt(g)))return"Please enter a valid time.";if(e&&We(Vt(g),Vt(e)))return`Please choose a time after ${Dg(e)}.`;if(r&&jt(Vt(g),Vt(r)))return`Please choose a time before ${Dg(r)}.`;if(o?.some(y=>!We(Vt(g),Vt(y.from))&&!jt(Vt(g),Vt(y.to))))return"This time is unavailable.";if(n&&u){let y=Je(`${u} ${g}`,`${zk} ${Oc}`,new Date);if(!to(y))return"Please enter a valid date and time.";let p=Xu(y,i),b=ah(Vo(new Date,n));if(We(p,b)){let _=ws(b,i),v=Ue(_,"MMM d 'at' h:mm a");return`Please select a time at least ${n} hours from now (after ${v}).`}}return null}let h=a.initialValue??(n?Ue(Fm(Vo(new Date,n),5),Oc):void 0);return Jk(De,{...a,initialValue:h,validate:m,sanitize:Kk})}import{z as cr}from"zod";import{jsx as Zk}from"react/jsx-runtime";var Pr="yyyy-MM-dd";function Yk(t,e,r,o){let n=Je(t,Pr,new Date);return!to(n)||Ue(n,Pr)!==t?"Please enter a valid date.":e&&We(n,Je(e,Pr,new Date))?`Please choose ${e} or later.`:r&&jt(n,Je(r,Pr,new Date))?`Please choose ${r} or earlier.`:o?.includes(t)?"This date is unavailable. Please choose another.":null}function Xk(t){return t.replace(/[^\d-]/g,"").slice(0,10)}var Qk=ne.extend({fieldId:cr.string().default("date"),label:cr.string().default("Event date"),autoCompleteType:cr.string().default("off"),inputType:cr.literal("date").default("date"),minimumNoticeHours:cr.number().nullable().optional(),minDate:cr.date().optional(),maxDate:cr.date().optional(),unavailableDates:cr.array(cr.date()).optional()});function sn(t){let{minDate:e,maxDate:r,unavailableDates:o,minimumNoticeHours:n,...s}=Qk.parse(t),i=e??(n?xt(Vo(new Date,n)):xt(new Date)),a=Ue(i,Pr),l=r?Ue(r,Pr):void 0,u=o?.map(f=>Ue(f,Pr));function c(f){return Yk(f,a,l,u)}let d=s.initialValue??(n?Ue(xt(Vo(new Date,n)),Pr):a);return Zk(De,{...s,initialValue:d,min:a,max:l,validate:c,sanitize:Xk})}import{z as Or}from"zod";import{jsx as oT}from"react/jsx-runtime";function eT(t){return t.replace(/[^0-9]/g,"").slice(0,255)}var tT=ne.extend({fieldId:Or.string().default("discreteNumber"),placeholder:Or.string().default("10"),label:Or.string().default("Number of guests"),min:Or.number().default(10),max:Or.number().default(5e3),minErrorText:Or.string().optional(),maxErrorText:Or.string().optional(),step:Or.number().default(1)});function rT(t,e,r,o){return n=>{let s=Number(n);return Number.isNaN(s)?"Please enter a valid number.":s<t?r??`Must be at least ${t}.`:s>e?o??`Must be ${e} or fewer.`:null}}function Lg(t){let e=tT.parse(t),{min:r,max:o,minErrorText:n,maxErrorText:s,...i}=e;return oT(De,{...i,validate:rT(r,o,n,s),sanitize:eT})}import{z as al}from"zod";import{jsx as Ac,jsxs as sT}from"react/jsx-runtime";var nT=ne.extend({min:al.number().default(0),max:al.number().default(100),step:al.number().default(1),onChange:al.any().optional()});function Ng(t){let{fieldId:e,label:r,min:o,max:n,step:s,required:i,showLabel:a,showError:l,fieldClassName:u,containerClassName:c,fieldLabelClassName:d,fieldAsteriskClassName:f,fieldErrorClassName:m,initialValue:h,requiredText:g,disabled:y,onChange:p}=nT.parse(t);function b(X){return i&&X==null?g:X<o?`Must be at least ${o}.`:X>n?`Must be ${n} or fewer.`:null}pt({name:e,required:i,validate:b,initialValue:h??o});let{value:_,setValue:v,error:L,clearError:x,validate:P}=ae(e);return sT("div",{className:c,children:[a&&Ac(ht,{required:i,className:d,asteriskClassName:f,children:r}),Ac("input",{type:"range",min:o,max:n,step:s,value:_??o,disabled:y,onChange:X=>{let F=Number(X.target.value);v(F),x(),p?.(F)},onBlur:P,"data-error":!!L||void 0,className:u}),l&&Ac(xe,{name:e,className:m})]})}import{z as jg}from"zod";import{jsx as Rc,jsxs as Mg}from"react/jsx-runtime";var iT=ne.extend({checkboxClassName:jg.string().default("mt-0.5 h-5 w-5 shrink-0 rounded"),labelClassName:jg.string().default("pt-0.5 text-sm leading-snug")});function Ug({children:t,...e}){let{fieldId:r,required:o,requiredText:n,showError:s,disabled:i,containerClassName:a,fieldErrorClassName:l,checkboxClassName:u,labelClassName:c,initialValue:d}=iT.parse(e);pt({name:r,required:!1,validate:o?g=>g?null:n:void 0,initialValue:d??!1});let{value:f,setValue:m,validate:h}=ae(r);return Mg("div",{className:a,children:[Mg("div",{className:"flex items-start gap-3 px-1 py-2 min-h-[44px]",children:[Rc("input",{type:"checkbox",id:r,checked:f??!1,onChange:g=>{m(g.target.checked),o&&h()},disabled:i,className:u}),Rc("label",{htmlFor:r,className:c,children:t})]}),s&&Rc(xe,{name:r,className:l})]})}import{jsx as Fg}from"react/jsx-runtime";function $g({name:t,label:e="Quantity",initalVal:r=0,showLabel:o=!0,showError:n=!0,showIncrement:s=!0,showDecrement:i=!0}){return Fg("div",{children:Fg(ht,{required:!0,children:e})})}import{z as uo}from"zod";import{jsx as ll,jsxs as Bg}from"react/jsx-runtime";var aT=nn.extend({fieldId:uo.string().default("nameFields"),outerClassName:uo.string().default("flex flex-col md:flex-row w-full gap-4"),firstNamePlaceholder:uo.string().default("First name"),lastNamePlaceholder:uo.string().default("Last name"),firstNameInitialValue:uo.string().default(""),lastNameInitialValue:uo.string().default(""),childClassName:uo.string().default("flex flex-col w-full md:flex-1 md:min-w-0")});function lT({className:t}){let{error:e}=ae("firstName"),{error:r}=ae("lastName"),o=e??r;return o?ll("span",{className:t,children:o}):null}function qg(t){let e=aT.parse({...t}),{outerClassName:r,firstNamePlaceholder:o,lastNamePlaceholder:n,firstNameInitialValue:s,lastNameInitialValue:i,childClassName:a,...l}=e;return Bg("div",{className:"flex flex-col w-full gap-1",children:[Bg("div",{className:r,children:[ll(De,{...l,fieldId:"firstName",label:"First name",placeholder:o,initialValue:s,autoCompleteType:"given-name",containerClassName:a,showError:!1}),ll(De,{...l,fieldId:"lastName",label:"Last name",placeholder:n,initialValue:i,autoCompleteType:"family-name",containerClassName:a,showError:!1})]}),ll(lT,{className:l.fieldErrorClassName})]})}import{z as ke}from"zod";import{jsx as ul,jsxs as Vg}from"react/jsx-runtime";var uT=ne.extend({fieldId:ke.string().default("dateTime"),outerClassName:ke.string().default("flex flex-col md:flex-row w-full gap-4"),childClassName:ke.string().default("flex flex-col w-full md:flex-1 md:min-w-0"),dateLabel:ke.string().default("Event date"),dateFieldId:ke.string().default("date"),minDate:ke.date().optional(),maxDate:ke.date().optional(),unavailableDates:ke.array(ke.date()).optional(),minimumNoticeHours:ke.number().nullable().optional(),timeLabel:ke.string().default("Start time"),timeFieldId:ke.string().default("time"),closedSpans:ke.array(ke.object({from:ke.string(),to:ke.string()})).optional(),timezone:ke.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:ke.string().optional(),timeInitialValue:ke.string().optional()});function Wg(t){let{minTime:e,maxTime:r,timeBounds:o,...n}=t,{fieldId:s,outerClassName:i,childClassName:a,inputType:l,dateLabel:u,dateFieldId:c,minDate:d,maxDate:f,unavailableDates:m,minimumNoticeHours:h,timeLabel:g,timeFieldId:y,closedSpans:p,timezone:b,dateInitialValue:_,timeInitialValue:v,...L}=uT.parse(n),x=nl(He()),P=o?o(x):void 0,X=P?.min??(typeof e=="function"?e(x):e),F=P?.max??(typeof r=="function"?r(x):r);return Vg("div",{className:"flex flex-col w-full gap-1",children:[Vg("div",{className:i,children:[ul(sn,{...L,inputType:"date",fieldId:c,label:u,minDate:d,maxDate:f,unavailableDates:m,minimumNoticeHours:h,containerClassName:a,showError:!1,initialValue:_??L.initialValue}),ul(lo,{...L,inputType:"time",fieldId:y,label:g,minTime:X,maxTime:F,closedSpans:p,minimumNoticeHours:h,dateFieldId:c,timezone:b,containerClassName:a,showError:!1,initialValue:v??L.initialValue})]}),ul(xe,{name:c,className:L.fieldErrorClassName}),ul(xe,{name:y,className:L.fieldErrorClassName})]})}import{z as he}from"zod";import{jsx as an,jsxs as Ic}from"react/jsx-runtime";var cT=ne.extend({fieldId:he.string().default("dateTimeRange"),dateLabel:he.string().default("Event date"),dateFieldId:he.string().default("date"),minDate:he.date().optional(),maxDate:he.date().optional(),unavailableDates:he.array(he.date()).optional(),minimumNoticeHours:he.number().nullable().optional(),startTimeLabel:he.string().default("Start time"),startTimeFieldId:he.string().default("startTime"),endTimeLabel:he.string().default("End time"),endTimeFieldId:he.string().default("endTime"),closedSpans:he.array(he.object({from:he.string(),to:he.string()})).optional(),timezone:he.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:he.string().optional(),startTimeInitialValue:he.string().optional(),endTimeInitialValue:he.string().optional()});function Hg(t){let{fieldId:e,inputType:r,dateLabel:o,dateFieldId:n,minDate:s,maxDate:i,unavailableDates:a,minimumNoticeHours:l,startTimeLabel:u,startTimeFieldId:c,endTimeLabel:d,endTimeFieldId:f,closedSpans:m,timezone:h,dateInitialValue:g,startTimeInitialValue:y,endTimeInitialValue:p,...b}=cT.parse(t),v=He()[c];return Ic("div",{className:"flex flex-col w-full gap-1",children:[Ic("div",{className:"flex flex-col md:flex-row w-full gap-4",children:[an(sn,{...b,inputType:"date",fieldId:n,label:o,minDate:s,maxDate:i,unavailableDates:a,minimumNoticeHours:l,containerClassName:"flex flex-col w-full md:flex-1 md:min-w-0",showError:!1,initialValue:g??b.initialValue}),Ic("div",{className:"flex flex-row gap-4 md:contents",children:[an(lo,{...b,inputType:"time",fieldId:c,label:u,closedSpans:m,minimumNoticeHours:l,dateFieldId:n,timezone:h,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:y??b.initialValue}),an(lo,{...b,inputType:"time",fieldId:f,label:d,minTime:v,closedSpans:m,dateFieldId:n,timezone:h,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:p??b.initialValue})]})]}),an(xe,{name:n,className:b.fieldErrorClassName}),an(xe,{name:c,className:b.fieldErrorClassName}),an(xe,{name:f,className:b.fieldErrorClassName})]})}import{z as dr}from"zod";import{useRef as cl,useEffect as dl}from"react";import{jsx as ln,jsxs as fl}from"react/jsx-runtime";var dT=ne.extend({fieldId:dr.string().default("guestCount"),label:dr.string().default("Number of guests"),placeholder:dr.string().default("10"),min:dr.number().default(10),max:dr.number().default(5e3),step:dr.number().default(1),minErrorText:dr.string().optional(),maxErrorText:dr.string().optional(),sliderClassName:dr.string().default("flex-[3]")});function zg(t){let{fieldId:e,label:r,placeholder:o,min:n,max:s,step:i,required:a,showLabel:l,showError:u,fieldClassName:c,containerClassName:d,fieldLabelClassName:f,fieldAsteriskClassName:m,fieldErrorClassName:h,initialValue:g,requiredText:y,minErrorText:p,maxErrorText:b,disabled:_,sliderClassName:v}=dT.parse(t);function L(S){if(!S?.trim())return a?y:null;let q=Number(S);return Number.isNaN(q)?"Please enter a valid number.":q<n?p??`Must be at least ${n}.`:q>s?b??`Must be ${s} or fewer.`:null}pt({name:e,required:a,validate:L,initialValue:g??String(n)});let{value:x,setValue:P,error:X,clearError:F,validate:tt}=ae(e),fe=cl(P),rt=cl(F),Wt=cl(tt);dl(()=>{fe.current=P},[P]),dl(()=>{rt.current=F},[F]),dl(()=>{Wt.current=tt},[tt]);let Ht=Number(x)||n,zt=Math.max(0,Math.min(100,(Ht-n)/(s-n)*100)),Ne=cl(null);return dl(()=>{let S=Ne.current;if(!S)return;let q=0,N=0;function ee(me){let{left:ye,width:Ct}=S.getBoundingClientRect(),Et=Math.max(0,Math.min(1,(me-ye)/Ct)),fo=n+(s-n)*Et;return String(Math.max(n,Math.min(s,Math.round(fo/i)*i)))}function Q(me){q=me.changedTouches[0].clientX,N=me.changedTouches[0].clientY,fe.current(ee(q)),rt.current()}function G(me){let ye=Math.abs(me.changedTouches[0].clientX-q),Ct=Math.abs(me.changedTouches[0].clientY-N);ye>Ct&&me.preventDefault(),fe.current(ee(me.changedTouches[0].clientX)),rt.current()}function ge(){Wt.current()}return S.addEventListener("touchstart",Q,{passive:!0}),S.addEventListener("touchmove",G,{passive:!1}),S.addEventListener("touchend",ge,{passive:!0}),()=>{S.removeEventListener("touchstart",Q),S.removeEventListener("touchmove",G),S.removeEventListener("touchend",ge)}},[]),fl("div",{className:d,children:[l&&ln(ht,{required:a,className:f,asteriskClassName:m,children:r}),fl("div",{className:"flex items-center gap-4",children:[fl("div",{className:`flex flex-[6] flex-col ${v}`,children:[ln("input",{ref:Ne,type:"range",min:n,max:s,step:i,value:Ht,disabled:_,onChange:S=>{P(S.target.value),F()},onBlur:tt,className:`w-full ${v}`,style:{"--slider-fill":`${zt}%`}}),fl("div",{className:"flex justify-between text-xs text-stone-400 mt-2 px-0.5",children:[ln("span",{children:n}),ln("span",{children:s})]})]}),ln("input",{type:"text",inputMode:"numeric",placeholder:o,value:x??"",disabled:_,onChange:S=>{P(S.target.value.replace(/[^0-9]/g,"").slice(0,5)),F()},onBlur:tt,"data-error":!!X||void 0,className:`flex-1 text-center ${c}`})]}),u&&ln(xe,{name:e,className:h})]})}import fT from"react";var pe=fT.createContext({});import*as un from"react";import{forwardRef as gT}from"react";var mT=Object.defineProperty,Gg=Object.getOwnPropertySymbols,hT=Object.prototype.hasOwnProperty,pT=Object.prototype.propertyIsEnumerable,Kg=(t,e,r)=>e in t?mT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dc=(t,e)=>{for(var r in e||(e={}))hT.call(e,r)&&Kg(t,r,e[r]);if(Gg)for(var r of Gg(e))pT.call(e,r)&&Kg(t,r,e[r]);return t},yT=(t,e)=>{let r=un.useContext(pe),o=Dc(Dc({},r),t);return un.createElement("svg",Dc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),un.createElement("path",{d:"M10.5213 2.62368C11.3147 1.75255 12.6853 1.75255 13.4787 2.62368L14.4989 3.74391C14.8998 4.18418 15.4761 4.42288 16.071 4.39508L17.5845 4.32435C18.7614 4.26934 19.7307 5.23857 19.6757 6.41554L19.6049 7.92905C19.5771 8.52388 19.8158 9.10016 20.2561 9.50111L21.3763 10.5213C22.2475 11.3147 22.2475 12.6853 21.3763 13.4787L20.2561 14.4989C19.8158 14.8998 19.5771 15.4761 19.6049 16.071L19.6757 17.5845C19.7307 18.7614 18.7614 19.7307 17.5845 19.6757L16.071 19.6049C15.4761 19.5771 14.8998 19.8158 14.4989 20.2561L13.4787 21.3763C12.6853 22.2475 11.3147 22.2475 10.5213 21.3763L9.50111 20.2561C9.10016 19.8158 8.52388 19.5771 7.92905 19.6049L6.41553 19.6757C5.23857 19.7307 4.26934 18.7614 4.32435 17.5845L4.39508 16.071C4.42288 15.4761 4.18418 14.8998 3.74391 14.4989L2.62368 13.4787C1.75255 12.6853 1.75255 11.3147 2.62368 10.5213L3.74391 9.50111C4.18418 9.10016 4.42288 8.52388 4.39508 7.92905L4.32435 6.41553C4.26934 5.23857 5.23857 4.26934 6.41554 4.32435L7.92905 4.39508C8.52388 4.42288 9.10016 4.18418 9.50111 3.74391L10.5213 2.62368Z",stroke:"currentColor"}),un.createElement("path",{d:"M9 12L11 14L15 10",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},bT=gT(yT),Lc=bT;import*as cn from"react";import{forwardRef as ST}from"react";var _T=Object.defineProperty,Jg=Object.getOwnPropertySymbols,wT=Object.prototype.hasOwnProperty,vT=Object.prototype.propertyIsEnumerable,Yg=(t,e,r)=>e in t?_T(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nc=(t,e)=>{for(var r in e||(e={}))wT.call(e,r)&&Yg(t,r,e[r]);if(Jg)for(var r of Jg(e))vT.call(e,r)&&Yg(t,r,e[r]);return t},xT=(t,e)=>{let r=cn.useContext(pe),o=Nc(Nc({},r),t);return cn.createElement("svg",Nc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),cn.createElement("path",{d:"M7 12.5L10 15.5L17 8.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),cn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},kT=ST(xT),ml=kT;import*as dn from"react";import{forwardRef as PT}from"react";var TT=Object.defineProperty,Xg=Object.getOwnPropertySymbols,CT=Object.prototype.hasOwnProperty,ET=Object.prototype.propertyIsEnumerable,Qg=(t,e,r)=>e in t?TT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jc=(t,e)=>{for(var r in e||(e={}))CT.call(e,r)&&Qg(t,r,e[r]);if(Xg)for(var r of Xg(e))ET.call(e,r)&&Qg(t,r,e[r]);return t},OT=(t,e)=>{let r=dn.useContext(pe),o=jc(jc({},r),t);return dn.createElement("svg",jc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),dn.createElement("path",{d:"M12 6L12 12L18 12",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),dn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},AT=PT(OT),hl=AT;import*as Os from"react";import{forwardRef as LT}from"react";var RT=Object.defineProperty,Zg=Object.getOwnPropertySymbols,IT=Object.prototype.hasOwnProperty,DT=Object.prototype.propertyIsEnumerable,ey=(t,e,r)=>e in t?RT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mc=(t,e)=>{for(var r in e||(e={}))IT.call(e,r)&&ey(t,r,e[r]);if(Zg)for(var r of Zg(e))DT.call(e,r)&&ey(t,r,e[r]);return t},NT=(t,e)=>{let r=Os.useContext(pe),o=Mc(Mc({},r),t);return Os.createElement("svg",Mc({width:"1.5em",height:"1.5em",viewBox:"0 0 24 24",strokeWidth:1.5,fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),Os.createElement("path",{d:"M22 9V17C22 18.1046 21.1046 19 20 19H4C2.89543 19 2 18.1046 2 17V7C2 5.89543 2.89543 5 4 5H20C21.1046 5 22 5.89543 22 7V9ZM22 9H6",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},jT=LT(NT),Uc=jT;import*as co from"react";import{forwardRef as $T}from"react";var MT=Object.defineProperty,ty=Object.getOwnPropertySymbols,UT=Object.prototype.hasOwnProperty,FT=Object.prototype.propertyIsEnumerable,ry=(t,e,r)=>e in t?MT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fc=(t,e)=>{for(var r in e||(e={}))UT.call(e,r)&&ry(t,r,e[r]);if(ty)for(var r of ty(e))FT.call(e,r)&&ry(t,r,e[r]);return t},BT=(t,e)=>{let r=co.useContext(pe),o=Fc(Fc({},r),t);return co.createElement("svg",Fc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),co.createElement("path",{d:"M1.5 12.5L5.57574 16.5757C5.81005 16.8101 6.18995 16.8101 6.42426 16.5757L9 14",stroke:"currentColor",strokeLinecap:"round"}),co.createElement("path",{d:"M16 7L12 11",stroke:"currentColor",strokeLinecap:"round"}),co.createElement("path",{d:"M7 12L11.5757 16.5757C11.8101 16.8101 12.1899 16.8101 12.4243 16.5757L22 7",stroke:"currentColor",strokeLinecap:"round"}))},qT=$T(BT),$c=qT;import*as fn from"react";import{forwardRef as zT}from"react";var VT=Object.defineProperty,oy=Object.getOwnPropertySymbols,WT=Object.prototype.hasOwnProperty,HT=Object.prototype.propertyIsEnumerable,ny=(t,e,r)=>e in t?VT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bc=(t,e)=>{for(var r in e||(e={}))WT.call(e,r)&&ny(t,r,e[r]);if(oy)for(var r of oy(e))HT.call(e,r)&&ny(t,r,e[r]);return t},GT=(t,e)=>{let r=fn.useContext(pe),o=Bc(Bc({},r),t);return fn.createElement("svg",Bc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),fn.createElement("path",{d:"M7 9L12 12.5L17 9",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),fn.createElement("path",{d:"M2 17V7C2 5.89543 2.89543 5 4 5H20C21.1046 5 22 5.89543 22 7V17C22 18.1046 21.1046 19 20 19H4C2.89543 19 2 18.1046 2 17Z",stroke:"currentColor"}))},KT=zT(GT),qc=KT;import*as mn from"react";import{forwardRef as QT}from"react";var JT=Object.defineProperty,sy=Object.getOwnPropertySymbols,YT=Object.prototype.hasOwnProperty,XT=Object.prototype.propertyIsEnumerable,iy=(t,e,r)=>e in t?JT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vc=(t,e)=>{for(var r in e||(e={}))YT.call(e,r)&&iy(t,r,e[r]);if(sy)for(var r of sy(e))XT.call(e,r)&&iy(t,r,e[r]);return t},ZT=(t,e)=>{let r=mn.useContext(pe),o=Vc(Vc({},r),t);return mn.createElement("svg",Vc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),mn.createElement("path",{d:"M20 5.99999L20 18C20 19.1046 19.1046 20 18 20H6C4.89543 20 4 19.1046 4 18V6C4 4.89543 4.89543 4 6 4H18C19.1045 4 19.9999 4.89543 20 5.99999Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),mn.createElement("path",{d:"M12 9V4",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},eC=QT(ZT),Wc=eC;import*as hn from"react";import{forwardRef as nC}from"react";var tC=Object.defineProperty,ay=Object.getOwnPropertySymbols,rC=Object.prototype.hasOwnProperty,oC=Object.prototype.propertyIsEnumerable,ly=(t,e,r)=>e in t?tC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hc=(t,e)=>{for(var r in e||(e={}))rC.call(e,r)&&ly(t,r,e[r]);if(ay)for(var r of ay(e))oC.call(e,r)&&ly(t,r,e[r]);return t},sC=(t,e)=>{let r=hn.useContext(pe),o=Hc(Hc({},r),t);return hn.createElement("svg",Hc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),hn.createElement("path",{d:"M19.2609 9.69589L20.6455 18.6959C20.8319 19.9074 19.8945 21 18.6688 21H5.33122C4.10545 21 3.16809 19.9074 3.35448 18.6959L4.73909 9.69589C4.8892 8.72022 5.7287 8 6.71584 8H17.2842C18.2713 8 19.1108 8.72022 19.2609 9.69589Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),hn.createElement("path",{d:"M14 5C14 3.89543 13.1046 3 12 3C10.8954 3 10 3.89543 10 5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},iC=nC(sC),zc=iC;import*as As from"react";import{forwardRef as cC}from"react";var aC=Object.defineProperty,uy=Object.getOwnPropertySymbols,lC=Object.prototype.hasOwnProperty,uC=Object.prototype.propertyIsEnumerable,cy=(t,e,r)=>e in t?aC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gc=(t,e)=>{for(var r in e||(e={}))lC.call(e,r)&&cy(t,r,e[r]);if(uy)for(var r of uy(e))uC.call(e,r)&&cy(t,r,e[r]);return t},dC=(t,e)=>{let r=As.useContext(pe),o=Gc(Gc({},r),t);return As.createElement("svg",Gc({width:"1.5em",height:"1.5em",viewBox:"0 0 24 24",strokeWidth:1.5,fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),As.createElement("path",{d:"M15 4L8 20",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},fC=cC(dC),pl=fC;import*as pn from"react";import{forwardRef as gC}from"react";var mC=Object.defineProperty,dy=Object.getOwnPropertySymbols,hC=Object.prototype.hasOwnProperty,pC=Object.prototype.propertyIsEnumerable,fy=(t,e,r)=>e in t?mC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kc=(t,e)=>{for(var r in e||(e={}))hC.call(e,r)&&fy(t,r,e[r]);if(dy)for(var r of dy(e))pC.call(e,r)&&fy(t,r,e[r]);return t},yC=(t,e)=>{let r=pn.useContext(pe),o=Kc(Kc({},r),t);return pn.createElement("svg",Kc({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),pn.createElement("path",{d:"M9.17218 14.8284L12.0006 12M14.829 9.17157L12.0006 12M12.0006 12L9.17218 9.17157M12.0006 12L14.829 14.8284",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),pn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},bC=gC(yC),gl=bC;function my(t){return{label:(t.split(".").at(-1)??t).replace(/_/g," "),color:"gray"}}import{jsx as $e,jsxs as gn}from"react/jsx-runtime";var _C={"order.placed":{label:"Order placed",color:"blue",icon:zc},"device.order_received":{label:"Received",color:"blue",icon:Wc},"order.requested":{label:"Requested",color:"blue",icon:hl},"order.paid":{label:"Paid",color:"green",icon:Uc},"device.order_acknowledged":{label:"Acknowledged",color:"blue",icon:$c},"order.confirmed":{label:"Confirmed",color:"green",icon:ml},"order.confirmation_email_sent":{label:"Confirmation email sent",color:"green",icon:qc},"order.completed":{label:"Completed",color:"green",icon:Lc},"order.failed":{label:"Failed",color:"red",icon:gl},"order.canceled":{label:"Cancelled",color:"red",icon:pl},"order.cancelled":{label:"Cancelled",color:"red",icon:pl},"order.catering.requested":{label:"Requested",color:"blue",icon:hl},"order.catering.confirmed":{label:"Confirmed",color:"green",icon:ml},"order.catering.charge_failed":{label:"Charge failed",color:"red",icon:gl}};function hy(t){return _C[t]??my(t)}var wC=new Set(["order.catering.requested","order.catering.confirmed","order.catering.charge_failed","order.canceled","order.cancelled"]);function py(t){let e=t.events.filter(i=>wC.has(i.event_name));if(!e.length)return null;let r=e[e.length-1],o=r.payload,n=r.event_name==="order.catering.confirmed"?"confirmed":r.event_name==="order.catering.requested"?"requested":"rejected",s=typeof o.userId=="string"?t.actorNames?.[o.userId]??o.userId:typeof o.deviceId=="number"?`Device #${o.deviceId}`:null;return{status:n,via:o.via??null,when:r.created_at,actorName:s}}function gy(t){let e=ds.ORDER_STATUS;switch(t.order_status){case e.REQUESTED:return{label:"Awaiting approval",color:"blue"};case e.CONFIRMED:return{label:"Confirmed",color:"green"};case e.CANCELLED:return t.is_catering?{label:"Rejected",color:"red"}:{label:"Cancelled",color:"red"};case e.PAID:case e.PARTIALLY_PAID:return{label:"Paid",color:"green"};case e.PREPARING:return{label:"Preparing",color:"blue"};case e.KITCHEN_DONE:case e.COMPLETED:return{label:"Completed",color:"green"};default:return{label:"Pending",color:"gray"}}}function yy(t){let e=ds.ORDER_STATUS;return t.order_status===(t.is_catering?e.REQUESTED:e.STAGING)}function vC(t){return t<1e3?`${t}ms`:t<6e4?`${Math.round(t/1e3)}s`:t<36e5?`${Math.round(t/6e4)}m`:`${Math.round(t/36e5)}h`}var by={root:"flex flex-col gap-6 min-w-0 text-white",statusPill:"text-sm font-semibold px-3 py-1 rounded-full",approval:"text-white/60 text-sm",approvalEmpty:"text-white/40 text-sm",timeline:"flex items-start overflow-x-auto pb-2",eventIcon:"w-10 h-10 rounded-xl shrink-0 flex items-center justify-center",eventLabel:"text-xs font-medium text-center",eventTime:"text-white/30 text-xs text-center",connectorLine:"h-px w-8 bg-white/20",connectorDelta:"text-white/30 text-xs",confirmButton:"w-full py-4 rounded-lg text-base font-bold text-white bg-green-600 hover:bg-green-500 disabled:opacity-60 transition-colors",confirmError:"text-red-400 text-xs text-center",colors:{blue:{bg:"bg-blue-500/20",text:"text-blue-400",dot:"bg-blue-500/60"},green:{bg:"bg-green-500/20",text:"text-green-400",dot:"bg-green-500/60"},red:{bg:"bg-red-500/20",text:"text-red-400",dot:"bg-red-500/60"},gray:{bg:"bg-white/10",text:"text-white/50",dot:"bg-white/60"}}};function _y(t){let e=by,{colors:r,...o}=t??{},n=Object.fromEntries(Object.keys(e.colors).map(i=>[i,{...e.colors[i],...r?.[i]}])),s=Object.fromEntries(Object.entries(o).filter(([,i])=>i!==void 0));return{...e,...s,colors:n}}var SC={pos:"at the POS",dashboard:"from the dashboard",email_link:"via an emailed link"};function xC({order:t,can:e,onConfirm:r,confirming:o,confirmError:n,itemClasses:s}){let i=_y(s),a=gy(t),l=py(t),u=t.events,c=!!r&&e("catering.confirm")&&yy(t);return gn("div",{className:i.root,children:[$e("div",{className:"flex items-center gap-2",children:$e("span",{className:`${i.statusPill} ${i.colors[a.color].bg} ${i.colors[a.color].text}`,children:a.label})}),$e("div",{className:"flex flex-col gap-1",children:l===null?$e("span",{className:i.approvalEmpty,children:"No approval recorded."}):l.status==="requested"?$e("span",{className:i.approval,children:"Awaiting approval."}):gn("span",{className:i.approval,children:[l.status==="confirmed"?"Confirmed":"Rejected",l.actorName&&` by ${l.actorName}`,l.via&&` ${SC[l.via]}`," on ",Ue(new Date(l.when),"MMM d, h:mm a")]})}),u.length>0&&$e("div",{className:i.timeline,children:u.map((d,f)=>{let m=hy(d.event_name),h=i.colors[m.color],g=f===u.length-1,y=m.icon;return gn("div",{className:"flex items-start shrink-0",children:[gn("div",{className:"flex flex-col items-center gap-2 min-w-20",children:[$e("div",{className:`${i.eventIcon} ${h.bg}`,children:y?$e(y,{width:18,height:18,className:h.text}):$e("div",{className:`w-2 h-2 rounded-full ${h.dot}`})}),$e("span",{className:`${i.eventLabel} ${h.text}`,children:m.label}),$e("span",{className:i.eventTime,children:Ue(new Date(d.created_at),"h:mm a")})]}),!g&&gn("div",{className:"flex flex-col items-center gap-1 mt-4 shrink-0",children:[$e("div",{className:i.connectorLine}),$e("span",{className:i.connectorDelta,children:vC(Bm(new Date(u[f+1].created_at),new Date(d.created_at)))})]})]},d.id)})}),c&&gn("div",{className:"flex flex-col gap-2",children:[$e("button",{onClick:r,disabled:o,className:i.confirmButton,children:o?"Confirming\u2026":"Confirm This Order"}),n&&$e("span",{className:i.confirmError,children:n})]})]})}import{jsx as Le,jsxs as ze}from"react/jsx-runtime";var wy={root:"flex flex-col gap-1 min-w-0 text-white",line:"flex flex-col gap-1 py-2 border-b border-white/10 last:border-b-0",lineName:"text-sm font-semibold text-white",lineSublabel:"text-xs text-white/50",linePrice:"text-sm font-semibold text-white tabular-nums",addOn:"flex justify-between items-baseline gap-2 text-xs",addOnName:"text-white/60",addOnPrice:"text-white/40",totalsRow:"flex justify-between text-sm text-white/70",discountRow:"flex justify-between text-sm text-green-400",totalRow:"flex justify-between text-base font-bold text-white mt-2"};function vy(t){let e=Object.fromEntries(Object.entries(t??{}).filter(([,r])=>r!==void 0));return{...wy,...e}}function kC({order:t,promotion:e,tip:r=0,itemClasses:o}){let n=vy(o),s=bs(t,e,r);return ze("div",{className:n.root,children:[s.lines.map((i,a)=>ze("div",{className:n.line,children:[ze("div",{className:"flex justify-between items-start gap-2",children:[ze("div",{className:"min-w-0",children:[Le("p",{className:n.lineName,children:i.name}),i.perPerson?Le("p",{className:n.lineSublabel,children:Ba(i)}):i.quantity>1&&ze("p",{className:n.lineSublabel,children:["\xD7",i.quantity]})]}),Le("span",{className:n.linePrice,children:Ft(i.lineTotal)})]}),(i.perPerson||i.addOns.length>0)&&ze("div",{className:"flex flex-col gap-0.5 mt-1",children:[i.perPerson&&ze("div",{className:n.addOn,children:[Le("span",{className:n.addOnName,children:"Base Price"}),Le("span",{className:n.addOnPrice,children:`${Ft(i.basePrice)}/person`})]}),i.addOns.map((l,u)=>ze("div",{className:n.addOn,children:[Le("span",{className:n.addOnName,children:l.name}),Le("span",{className:n.addOnPrice,children:qa(l,i.perPerson)})]},u))]})]},a)),ze("div",{className:"flex flex-col gap-1 mt-2",children:[s.discount>0&&ze("div",{className:n.discountRow,children:[Le("span",{children:"Discount"}),Le("span",{children:`(${Ft(s.discount)})`})]}),ze("div",{className:n.totalsRow,children:[Le("span",{children:"Tax"}),Le("span",{children:Ft(s.tax)})]}),s.serviceFee>0&&ze("div",{className:n.totalsRow,children:[Le("span",{children:"Service fee"}),Le("span",{children:Ft(s.serviceFee)})]}),s.tip>0&&ze("div",{className:n.totalsRow,children:[Le("span",{children:"Tip"}),Le("span",{children:Ft(s.tip)})]}),ze("div",{className:n.totalRow,children:[Le("span",{children:"Total"}),Le("span",{children:Ft(s.total)})]})]})]})}ag(fg);ug(TC);export{Ug as CheckboxField,Og as ClickableField,kg as ConditionalRenderer,sn as DateField,Wg as DateTime,Hg as DateTimeRange,xg as DisclaimerText,Lg as DiscreteNumberField,hg as DynamicFormShell,Pg as EmailField,xe as FieldError,ht as FieldLabel,zg as GuestCountField,_g as Header,$g as IncrementField,Ua as LOCATION_ORDERING_TIMEZONE,Ig as LocationField,qg as NameFields,wy as ORDER_ITEMIZED_DEFAULT_ITEM_CLASSES,by as ORDER_STATUS_DEFAULT_ITEM_CLASSES,kC as OrderItemized,xC as OrderStatus,Eg as PhoneField,Lu as Platforms,vg as PricePreview,Sg as SectionLabel,Ng as SliderField,gg as SubmitButton,De as TextField,lo as TimeField,py as deriveApproval,gy as deriveOrderStatus,Zj as divisionsFor,qa as formatAddOnPrice,Ba as formatCateringLineLabel,tM as groupItemPortions,yy as isConfirmable,Qu as isLocationClosedByWeeklySchedule,bs as itemizeOrder,Wh as locationWindowOn,vy as mergeOrderItemizedItemClasses,_y as mergeOrderStatusItemClasses,Zt as parsePortion,kt as parsePortionKey,z0 as portionGlyph,Xo as portionKey,eM as portionLabel,kh as portionRows,Da as portionWeight,rM as radialSectionPath,Ch as remapPortion,hy as resolveEventDisplay,V0 as sectionLabel,$u as selectionWeight,ag as setZorgoBoot,ug as setZorgoPathnameHook,Qj as splitUpcharge,VB as useCart,JB as useCateringConfig,XB as useCustomer,ae as useField,tl as useFormStatus,rl as useFormValidity,He as useFormValues,HB as useHydrateMenu,Qx as useHydrateStore,zB as useItemCustomization,WB as useLocation,Xx as useMenu,qB as useModal,KB as usePayment,GB as usePromotions,YB as useRecommendations,pt as useRegisterField,Th as weightedUpcharges};
|
|
159
159
|
/*! Bundled license information:
|
|
160
160
|
|
|
161
161
|
cookie/index.js:
|