@zorgo/next 1.3.0 → 2.0.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.
Files changed (66) hide show
  1. package/dist/cli.d.mts +9 -0
  2. package/dist/cli.d.ts +9 -0
  3. package/dist/cli.js +44 -66
  4. package/dist/cli.js.map +1 -1
  5. package/dist/cli.mjs +43 -65
  6. package/dist/cli.mjs.map +1 -1
  7. package/dist/components.d.mts +735 -5
  8. package/dist/components.d.ts +735 -5
  9. package/dist/components.js +3692 -525
  10. package/dist/components.js.map +1 -1
  11. package/dist/components.mjs +3663 -540
  12. package/dist/components.mjs.map +1 -1
  13. package/dist/images.d.mts +25 -13
  14. package/dist/images.d.ts +25 -13
  15. package/dist/images.js +18 -8
  16. package/dist/images.js.map +1 -1
  17. package/dist/images.mjs +15 -8
  18. package/dist/images.mjs.map +1 -1
  19. package/dist/index.d.mts +315 -9
  20. package/dist/index.d.ts +315 -9
  21. package/dist/index.js +58 -52
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.mjs +58 -52
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/item-page.d.mts +6 -0
  26. package/dist/item-page.d.ts +6 -0
  27. package/dist/item-page.js +4 -2
  28. package/dist/item-page.js.map +1 -1
  29. package/dist/item-page.mjs +4 -2
  30. package/dist/item-page.mjs.map +1 -1
  31. package/dist/legal.d.mts +31 -0
  32. package/dist/legal.d.ts +31 -0
  33. package/dist/legal.js +322 -0
  34. package/dist/legal.js.map +1 -0
  35. package/dist/legal.mjs +293 -0
  36. package/dist/legal.mjs.map +1 -0
  37. package/dist/seo.d.mts +56 -1
  38. package/dist/seo.d.ts +56 -1
  39. package/dist/seo.js +111 -2
  40. package/dist/seo.js.map +1 -1
  41. package/dist/seo.mjs +106 -1
  42. package/dist/seo.mjs.map +1 -1
  43. package/dist/server.d.mts +27 -1
  44. package/dist/server.d.ts +27 -1
  45. package/dist/server.js +322 -102
  46. package/dist/server.js.map +1 -1
  47. package/dist/server.mjs +322 -104
  48. package/dist/server.mjs.map +1 -1
  49. package/dist/slugs.d.mts +2 -1
  50. package/dist/slugs.d.ts +2 -1
  51. package/dist/slugs.js +2 -0
  52. package/dist/slugs.js.map +1 -1
  53. package/dist/slugs.mjs +1 -0
  54. package/dist/tree/README.md +2 -2
  55. package/dist/tree/app/error.tsx +12 -3
  56. package/dist/tree/app/global-error.tsx +21 -4
  57. package/dist/tree/app/globals.css +41 -0
  58. package/dist/tree/app/not-found.tsx +17 -3
  59. package/dist/tree/app/privacy/page.tsx.gen.ts +28 -9
  60. package/dist/tree/app/terms/page.tsx.gen.ts +26 -10
  61. package/dist/tree/gitignore +6 -1
  62. package/dist/tree/next.config.ts +6 -5
  63. package/dist/tree/open-next.config.ts +7 -0
  64. package/dist/tree/package.json.gen.ts +8 -2
  65. package/package.json +7 -2
  66. package/dist/tree/app/globals.css.gen.ts +0 -124
package/dist/index.mjs CHANGED
@@ -1,18 +1,18 @@
1
1
  "use client";
2
- var Lp=Object.create;var Xi=Object.defineProperty;var jp=Object.getOwnPropertyDescriptor;var $p=Object.getOwnPropertyNames;var Mp=Object.getPrototypeOf,Up=Object.prototype.hasOwnProperty;var Zi=(t,e)=>()=>(t&&(e=t(t=0)),e);var qe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fp=(t,e)=>{for(var r in e)Xi(t,r,{get:e[r],enumerable:!0})},Vl=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of $p(e))!Up.call(t,i)&&i!==r&&Xi(t,i,{get:()=>e[i],enumerable:!(n=jp(e,i))||n.enumerable});return t};var qn=(t,e,r)=>(r=t!=null?Lp(Mp(t)):{},Vl(e||!t||!t.__esModule?Xi(r,"default",{value:t,enumerable:!0}):r,t)),Hl=t=>Vl(Xi({},"__esModule",{value:!0}),t);var Pc=qe(Oc=>{"use strict";Oc.parse=db;Oc.serialize=hb;var sb=Object.prototype.toString,ob=Object.prototype.hasOwnProperty,ab=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,cb=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,lb=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,ub=/^[\u0020-\u003A\u003D-\u007E]*$/;function db(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");var r={},n=t.length;if(n<2)return r;var i=e&&e.decode||fb,s=0,o=0,a=0;do{if(o=t.indexOf("=",s),o===-1)break;if(a=t.indexOf(";",s),a===-1)a=n;else if(o>a){s=t.lastIndexOf(";",o-1)+1;continue}var c=nh(t,s,o),l=ih(t,o,c),u=t.slice(c,l);if(!ob.call(r,u)){var d=nh(t,o+1,a),h=ih(t,a,d);t.charCodeAt(d)===34&&t.charCodeAt(h-1)===34&&(d++,h--);var f=t.slice(d,h);r[u]=pb(f,i)}s=a+1}while(s<n);return r}function nh(t,e,r){do{var n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}function ih(t,e,r){for(;e>r;){var n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}function hb(t,e,r){var n=r&&r.encode||encodeURIComponent;if(typeof n!="function")throw new TypeError("option encode is invalid");if(!ab.test(t))throw new TypeError("argument name is invalid");var i=n(e);if(!cb.test(i))throw new TypeError("argument val is invalid");var s=t+"="+i;if(!r)return s;if(r.maxAge!=null){var o=Math.floor(r.maxAge);if(!isFinite(o))throw new TypeError("option maxAge is invalid");s+="; Max-Age="+o}if(r.domain){if(!lb.test(r.domain))throw new TypeError("option domain is invalid");s+="; Domain="+r.domain}if(r.path){if(!ub.test(r.path))throw new TypeError("option path is invalid");s+="; Path="+r.path}if(r.expires){var a=r.expires;if(!mb(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 c=typeof r.priority=="string"?r.priority.toLowerCase():r.priority;switch(c){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 l=typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite;switch(l){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 fb(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}function mb(t){return sb.call(t)==="[object Date]"}function pb(t,e){try{return e(t)}catch{return t}}});var hh=qe((VP,dh)=>{"use strict";dh.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var _h=qe((gh,yh)=>{"use strict";var Zs=hh(),{hasOwnProperty:mh}=Object.prototype,{propertyIsEnumerable:vb}=Object,bn=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),Sb=gh,fh={concatArrays:!1,ignoreUndefined:!1},Qs=t=>{let e=[];for(let r in t)mh.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let n of r)vb.call(t,n)&&e.push(n)}return e};function wn(t){return Array.isArray(t)?xb(t):Zs(t)?kb(t):t}function xb(t){let e=t.slice(0,0);return Qs(t).forEach(r=>{bn(e,r,wn(t[r]))}),e}function kb(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return Qs(t).forEach(r=>{bn(e,r,wn(t[r]))}),e}var ph=(t,e,r,n)=>(r.forEach(i=>{typeof e[i]>"u"&&n.ignoreUndefined||(i in t&&t[i]!==Object.getPrototypeOf(t)?bn(t,i,Mc(t[i],e[i],n)):bn(t,i,wn(e[i])))}),t),Eb=(t,e,r)=>{let n=t.slice(0,0),i=0;return[t,e].forEach(s=>{let o=[];for(let a=0;a<s.length;a++)mh.call(s,a)&&(o.push(String(a)),s===t?bn(n,i++,s[a]):bn(n,i++,wn(s[a])));n=ph(n,s,Qs(s).filter(a=>!o.includes(a)),r)}),n};function Mc(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?Eb(t,e,r):!Zs(e)||!Zs(t)?wn(e):ph(t,e,Qs(e),r)}yh.exports=function(...t){let e=Mc(wn(fh),this!==Sb&&this||{},fh),r={_:{}};for(let n of t)if(n!==void 0){if(!Zs(n))throw new TypeError("`"+n+"` is not an Option Object");r=Mc(r,{_:n},e)}return r._}});var bh,wh,vh=Zi(()=>{"use strict";bh=qn(_h(),1),wh=bh.default});function Ob(t,e){let r=window.localStorage.getItem(t);if(r){let n=JSON.parse(r),i=JSON.parse(e),s=JSON.stringify(Tb(n,i));window.localStorage.setItem(t,s)}else window.localStorage.setItem(t,e)}function vn(t,e){return new Promise((r,n)=>{try{let i=t();e?.(null,i),r(i)}catch(i){e?.(i),n(i)}})}function eo(t,e,r){return Promise.all(t).then(n=>{let i=r?.(n)??null;return e?.(null,i),Promise.resolve(i)},n=>(e?.(n),Promise.reject(n)))}var Tb,Li,Dr,Uc=Zi(()=>{"use strict";vh();Tb=wh.bind({concatArrays:!0,ignoreUndefined:!0});Li={getItem:(t,e)=>vn(()=>window.localStorage.getItem(t),e),setItem:(t,e,r)=>vn(()=>window.localStorage.setItem(t,e),r),removeItem:(t,e)=>vn(()=>window.localStorage.removeItem(t),e),mergeItem:(t,e,r)=>vn(()=>Ob(t,e),r),clear:t=>vn(()=>window.localStorage.clear(),t),getAllKeys:t=>vn(()=>{let e=window.localStorage.length,r=[];for(let n=0;n<e;n+=1){let i=window.localStorage.key(n)||"";r.push(i)}return r},t),flushGetRequests:()=>{},multiGet:(t,e)=>{let r=t.map(i=>Li.getItem(i));return eo(r,e,i=>i.map((s,o)=>[t[o],s]))},multiSet:(t,e)=>{let r=t.map(n=>Li.setItem(n[0],n[1]));return eo(r,e)},multiRemove:(t,e)=>{let r=t.map(n=>Li.removeItem(n));return eo(r,e)},multiMerge:(t,e)=>{let r=t.map(n=>Li.mergeItem(n[0],n[1]));return eo(r,e)}},Dr=Li});function Sh(t){return{getItem:(...e)=>Dr.getItem(t,...e),setItem:(...e)=>Dr.setItem(t,...e),mergeItem:(...e)=>Dr.mergeItem(t,...e),removeItem:(...e)=>Dr.removeItem(t,...e)}}var xh=Zi(()=>{"use strict";Uc()});var Fc={};Fp(Fc,{default:()=>Pb,useAsyncStorage:()=>Sh});var Pb,qc=Zi(()=>{"use strict";Uc();xh();Pb=Dr});var nm=qe((DL,rm)=>{"use strict";rm.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 n,i,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))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),n=s.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var _l=qe((d$,vm)=>{"use strict";vm.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 xm=qe((h$,Sm)=>{"use strict";Sm.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 Tm=qe((f$,Em)=>{"use strict";var h0=xm(),f0=Array.prototype.concat,m0=Array.prototype.slice,km=Em.exports=function(e){for(var r=[],n=0,i=e.length;n<i;n++){var s=e[n];h0(s)?r=f0.call(r,m0.call(s)):r.push(s)}return r};km.wrap=function(t){return function(){return t(km(arguments))}}});var Im=qe((m$,Cm)=>{"use strict";var Ki=_l(),Gi=Tm(),Om=Object.hasOwnProperty,Pm=Object.create(null);for(ha in Ki)Om.call(Ki,ha)&&(Pm[Ki[ha]]=ha);var ha,je=Cm.exports={to:{},get:{}};je.get=function(t){var e=t.substring(0,3).toLowerCase(),r,n;switch(e){case"hsl":r=je.get.hsl(t),n="hsl";break;case"hwb":r=je.get.hwb(t),n="hwb";break;default:r=je.get.rgb(t),n="rgb";break}return r?{model:n,value:r}:null};je.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,n=/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,i=/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,s=/^(\w+)$/,o=[0,0,0,1],a,c,l;if(a=t.match(r)){for(l=a[2],a=a[1],c=0;c<3;c++){var u=c*2;o[c]=parseInt(a.slice(u,u+2),16)}l&&(o[3]=parseInt(l,16)/255)}else if(a=t.match(e)){for(a=a[1],l=a[3],c=0;c<3;c++)o[c]=parseInt(a[c]+a[c],16);l&&(o[3]=parseInt(l+l,16)/255)}else if(a=t.match(n)){for(c=0;c<3;c++)o[c]=parseInt(a[c+1],0);a[4]&&(a[5]?o[3]=parseFloat(a[4])*.01:o[3]=parseFloat(a[4]))}else if(a=t.match(i)){for(c=0;c<3;c++)o[c]=Math.round(parseFloat(a[c+1])*2.55);a[4]&&(a[5]?o[3]=parseFloat(a[4])*.01:o[3]=parseFloat(a[4]))}else return(a=t.match(s))?a[1]==="transparent"?[0,0,0,0]:Om.call(Ki,a[1])?(o=Ki[a[1]],o[3]=1,o):null:null;for(c=0;c<3;c++)o[c]=ir(o[c],0,255);return o[3]=ir(o[3],0,1),o};je.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 n=parseFloat(r[4]),i=(parseFloat(r[1])%360+360)%360,s=ir(parseFloat(r[2]),0,100),o=ir(parseFloat(r[3]),0,100),a=ir(isNaN(n)?1:n,0,1);return[i,s,o,a]}return null};je.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 n=parseFloat(r[4]),i=(parseFloat(r[1])%360+360)%360,s=ir(parseFloat(r[2]),0,100),o=ir(parseFloat(r[3]),0,100),a=ir(isNaN(n)?1:n,0,1);return[i,s,o,a]}return null};je.to.hex=function(){var t=Gi(arguments);return"#"+fa(t[0])+fa(t[1])+fa(t[2])+(t[3]<1?fa(Math.round(t[3]*255)):"")};je.to.rgb=function(){var t=Gi(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]+")"};je.to.rgb.percent=function(){var t=Gi(arguments),e=Math.round(t[0]/255*100),r=Math.round(t[1]/255*100),n=Math.round(t[2]/255*100);return t.length<4||t[3]===1?"rgb("+e+"%, "+r+"%, "+n+"%)":"rgba("+e+"%, "+r+"%, "+n+"%, "+t[3]+")"};je.to.hsl=function(){var t=Gi(arguments);return t.length<4||t[3]===1?"hsl("+t[0]+", "+t[1]+"%, "+t[2]+"%)":"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+t[3]+")"};je.to.hwb=function(){var t=Gi(arguments),e="";return t.length>=4&&t[3]!==1&&(e=", "+t[3]),"hwb("+t[0]+", "+t[1]+"%, "+t[2]+"%"+e+")"};je.to.keyword=function(t){return Pm[t.slice(0,3)]};function ir(t,e,r){return Math.min(Math.max(e,t),r)}function fa(t){var e=Math.round(t).toString(16).toUpperCase();return e.length<2?"0"+e:e}});var bl=qe((p$,Am)=>{"use strict";var Ji=_l(),Rm={};for(let t of Object.keys(Ji))Rm[Ji[t]]=t;var T={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"]}};Am.exports=T;for(let t of Object.keys(T)){if(!("channels"in T[t]))throw new Error("missing channels property: "+t);if(!("labels"in T[t]))throw new Error("missing channel labels property: "+t);if(T[t].labels.length!==T[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:r}=T[t];delete T[t].channels,delete T[t].labels,Object.defineProperty(T[t],"channels",{value:e}),Object.defineProperty(T[t],"labels",{value:r})}T.rgb.hsl=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255,i=Math.min(e,r,n),s=Math.max(e,r,n),o=s-i,a,c;s===i?a=0:e===s?a=(r-n)/o:r===s?a=2+(n-e)/o:n===s&&(a=4+(e-r)/o),a=Math.min(a*60,360),a<0&&(a+=360);let l=(i+s)/2;return s===i?c=0:l<=.5?c=o/(s+i):c=o/(2-s-i),[a,c*100,l*100]};T.rgb.hsv=function(t){let e,r,n,i,s,o=t[0]/255,a=t[1]/255,c=t[2]/255,l=Math.max(o,a,c),u=l-Math.min(o,a,c),d=function(h){return(l-h)/6/u+1/2};return u===0?(i=0,s=0):(s=u/l,e=d(o),r=d(a),n=d(c),o===l?i=n-r:a===l?i=1/3+e-n:c===l&&(i=2/3+r-e),i<0?i+=1:i>1&&(i-=1)),[i*360,s*100,l*100]};T.rgb.hwb=function(t){let e=t[0],r=t[1],n=t[2],i=T.rgb.hsl(t)[0],s=1/255*Math.min(e,Math.min(r,n));return n=1-1/255*Math.max(e,Math.max(r,n)),[i,s*100,n*100]};T.rgb.cmyk=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255,i=Math.min(1-e,1-r,1-n),s=(1-e-i)/(1-i)||0,o=(1-r-i)/(1-i)||0,a=(1-n-i)/(1-i)||0;return[s*100,o*100,a*100,i*100]};function p0(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}T.rgb.keyword=function(t){let e=Rm[t];if(e)return e;let r=1/0,n;for(let i of Object.keys(Ji)){let s=Ji[i],o=p0(t,s);o<r&&(r=o,n=i)}return n};T.keyword.rgb=function(t){return Ji[t]};T.rgb.xyz=function(t){let e=t[0]/255,r=t[1]/255,n=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,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;let i=e*.4124+r*.3576+n*.1805,s=e*.2126+r*.7152+n*.0722,o=e*.0193+r*.1192+n*.9505;return[i*100,s*100,o*100]};T.rgb.lab=function(t){let e=T.rgb.xyz(t),r=e[0],n=e[1],i=e[2];r/=95.047,n/=100,i/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,i=i>.008856?i**(1/3):7.787*i+16/116;let s=116*n-16,o=500*(r-n),a=200*(n-i);return[s,o,a]};T.hsl.rgb=function(t){let e=t[0]/360,r=t[1]/100,n=t[2]/100,i,s,o;if(r===0)return o=n*255,[o,o,o];n<.5?i=n*(1+r):i=n+r-n*r;let a=2*n-i,c=[0,0,0];for(let l=0;l<3;l++)s=e+1/3*-(l-1),s<0&&s++,s>1&&s--,6*s<1?o=a+(i-a)*6*s:2*s<1?o=i:3*s<2?o=a+(i-a)*(2/3-s)*6:o=a,c[l]=o*255;return c};T.hsl.hsv=function(t){let e=t[0],r=t[1]/100,n=t[2]/100,i=r,s=Math.max(n,.01);n*=2,r*=n<=1?n:2-n,i*=s<=1?s:2-s;let o=(n+r)/2,a=n===0?2*i/(s+i):2*r/(n+r);return[e,a*100,o*100]};T.hsv.rgb=function(t){let e=t[0]/60,r=t[1]/100,n=t[2]/100,i=Math.floor(e)%6,s=e-Math.floor(e),o=255*n*(1-r),a=255*n*(1-r*s),c=255*n*(1-r*(1-s));switch(n*=255,i){case 0:return[n,c,o];case 1:return[a,n,o];case 2:return[o,n,c];case 3:return[o,a,n];case 4:return[c,o,n];case 5:return[n,o,a]}};T.hsv.hsl=function(t){let e=t[0],r=t[1]/100,n=t[2]/100,i=Math.max(n,.01),s,o;o=(2-r)*n;let a=(2-r)*i;return s=r*i,s/=a<=1?a:2-a,s=s||0,o/=2,[e,s*100,o*100]};T.hwb.rgb=function(t){let e=t[0]/360,r=t[1]/100,n=t[2]/100,i=r+n,s;i>1&&(r/=i,n/=i);let o=Math.floor(6*e),a=1-n;s=6*e-o,(o&1)!==0&&(s=1-s);let c=r+s*(a-r),l,u,d;switch(o){default:case 6:case 0:l=a,u=c,d=r;break;case 1:l=c,u=a,d=r;break;case 2:l=r,u=a,d=c;break;case 3:l=r,u=c,d=a;break;case 4:l=c,u=r,d=a;break;case 5:l=a,u=r,d=c;break}return[l*255,u*255,d*255]};T.cmyk.rgb=function(t){let e=t[0]/100,r=t[1]/100,n=t[2]/100,i=t[3]/100,s=1-Math.min(1,e*(1-i)+i),o=1-Math.min(1,r*(1-i)+i),a=1-Math.min(1,n*(1-i)+i);return[s*255,o*255,a*255]};T.xyz.rgb=function(t){let e=t[0]/100,r=t[1]/100,n=t[2]/100,i,s,o;return i=e*3.2406+r*-1.5372+n*-.4986,s=e*-.9689+r*1.8758+n*.0415,o=e*.0557+r*-.204+n*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,i=Math.min(Math.max(0,i),1),s=Math.min(Math.max(0,s),1),o=Math.min(Math.max(0,o),1),[i*255,s*255,o*255]};T.xyz.lab=function(t){let e=t[0],r=t[1],n=t[2];e/=95.047,r/=100,n/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let i=116*r-16,s=500*(e-r),o=200*(r-n);return[i,s,o]};T.lab.xyz=function(t){let e=t[0],r=t[1],n=t[2],i,s,o;s=(e+16)/116,i=r/500+s,o=s-n/200;let a=s**3,c=i**3,l=o**3;return s=a>.008856?a:(s-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,o=l>.008856?l:(o-16/116)/7.787,i*=95.047,s*=100,o*=108.883,[i,s,o]};T.lab.lch=function(t){let e=t[0],r=t[1],n=t[2],i;i=Math.atan2(n,r)*360/2/Math.PI,i<0&&(i+=360);let o=Math.sqrt(r*r+n*n);return[e,o,i]};T.lch.lab=function(t){let e=t[0],r=t[1],i=t[2]/360*2*Math.PI,s=r*Math.cos(i),o=r*Math.sin(i);return[e,s,o]};T.rgb.ansi16=function(t,e=null){let[r,n,i]=t,s=e===null?T.rgb.hsv(t)[2]:e;if(s=Math.round(s/50),s===0)return 30;let o=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(r/255));return s===2&&(o+=60),o};T.hsv.ansi16=function(t){return T.rgb.ansi16(T.hsv.rgb(t),t[2])};T.rgb.ansi256=function(t){let e=t[0],r=t[1],n=t[2];return e===r&&r===n?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(n/255*5)};T.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,n=(e&1)*r*255,i=(e>>1&1)*r*255,s=(e>>2&1)*r*255;return[n,i,s]};T.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,n=Math.floor((e=t%36)/6)/5*255,i=e%6/5*255;return[r,n,i]};T.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};T.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 n=parseInt(r,16),i=n>>16&255,s=n>>8&255,o=n&255;return[i,s,o]};T.rgb.hcg=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255,i=Math.max(Math.max(e,r),n),s=Math.min(Math.min(e,r),n),o=i-s,a,c;return o<1?a=s/(1-o):a=0,o<=0?c=0:i===e?c=(r-n)/o%6:i===r?c=2+(n-e)/o:c=4+(e-r)/o,c/=6,c%=1,[c*360,o*100,a*100]};T.hsl.hcg=function(t){let e=t[1]/100,r=t[2]/100,n=r<.5?2*e*r:2*e*(1-r),i=0;return n<1&&(i=(r-.5*n)/(1-n)),[t[0],n*100,i*100]};T.hsv.hcg=function(t){let e=t[1]/100,r=t[2]/100,n=e*r,i=0;return n<1&&(i=(r-n)/(1-n)),[t[0],n*100,i*100]};T.hcg.rgb=function(t){let e=t[0]/360,r=t[1]/100,n=t[2]/100;if(r===0)return[n*255,n*255,n*255];let i=[0,0,0],s=e%1*6,o=s%1,a=1-o,c=0;switch(Math.floor(s)){case 0:i[0]=1,i[1]=o,i[2]=0;break;case 1:i[0]=a,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=o;break;case 3:i[0]=0,i[1]=a,i[2]=1;break;case 4:i[0]=o,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=a}return c=(1-r)*n,[(r*i[0]+c)*255,(r*i[1]+c)*255,(r*i[2]+c)*255]};T.hcg.hsv=function(t){let e=t[1]/100,r=t[2]/100,n=e+r*(1-e),i=0;return n>0&&(i=e/n),[t[0],i*100,n*100]};T.hcg.hsl=function(t){let e=t[1]/100,n=t[2]/100*(1-e)+.5*e,i=0;return n>0&&n<.5?i=e/(2*n):n>=.5&&n<1&&(i=e/(2*(1-n))),[t[0],i*100,n*100]};T.hcg.hwb=function(t){let e=t[1]/100,r=t[2]/100,n=e+r*(1-e);return[t[0],(n-e)*100,(1-n)*100]};T.hwb.hcg=function(t){let e=t[1]/100,n=1-t[2]/100,i=n-e,s=0;return i<1&&(s=(n-i)/(1-i)),[t[0],i*100,s*100]};T.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};T.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};T.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};T.gray.hsl=function(t){return[0,0,t[0]]};T.gray.hsv=T.gray.hsl;T.gray.hwb=function(t){return[0,100,t[0]]};T.gray.cmyk=function(t){return[0,0,0,t[0]]};T.gray.lab=function(t){return[t[0],0,0]};T.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,n=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(n.length)+n};T.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var Nm=qe((g$,Dm)=>{"use strict";var ma=bl();function g0(){let t={},e=Object.keys(ma);for(let r=e.length,n=0;n<r;n++)t[e[n]]={distance:-1,parent:null};return t}function y0(t){let e=g0(),r=[t];for(e[t].distance=0;r.length;){let n=r.pop(),i=Object.keys(ma[n]);for(let s=i.length,o=0;o<s;o++){let a=i[o],c=e[a];c.distance===-1&&(c.distance=e[n].distance+1,c.parent=n,r.unshift(a))}}return e}function _0(t,e){return function(r){return e(t(r))}}function b0(t,e){let r=[e[t].parent,t],n=ma[e[t].parent][t],i=e[t].parent;for(;e[i].parent;)r.unshift(e[i].parent),n=_0(ma[e[i].parent][i],n),i=e[i].parent;return n.conversion=r,n}Dm.exports=function(t){let e=y0(t),r={},n=Object.keys(e);for(let i=n.length,s=0;s<i;s++){let o=n[s];e[o].parent!==null&&(r[o]=b0(o,e))}return r}});var jm=qe((y$,Lm)=>{"use strict";var wl=bl(),w0=Nm(),Ln={},v0=Object.keys(wl);function S0(t){let e=function(...r){let n=r[0];return n==null?n:(n.length>1&&(r=n),t(r))};return"conversion"in t&&(e.conversion=t.conversion),e}function x0(t){let e=function(...r){let n=r[0];if(n==null)return n;n.length>1&&(r=n);let i=t(r);if(typeof i=="object")for(let s=i.length,o=0;o<s;o++)i[o]=Math.round(i[o]);return i};return"conversion"in t&&(e.conversion=t.conversion),e}v0.forEach(t=>{Ln[t]={},Object.defineProperty(Ln[t],"channels",{value:wl[t].channels}),Object.defineProperty(Ln[t],"labels",{value:wl[t].labels});let e=w0(t);Object.keys(e).forEach(n=>{let i=e[n];Ln[t][n]=x0(i),Ln[t][n].raw=S0(i)})});Lm.exports=Ln});var Um=qe((_$,Mm)=>{"use strict";var jn=Im(),$e=jm(),$m=["keyword","gray","hex"],vl={};for(let t of Object.keys($e))vl[[...$e[t].labels].sort().join("")]=t;var pa={};function ve(t,e){if(!(this instanceof ve))return new ve(t,e);if(e&&e in $m&&(e=null),e&&!(e in $e))throw new Error("Unknown model: "+e);let r,n;if(t==null)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(t instanceof ve)this.model=t.model,this.color=[...t.color],this.valpha=t.valpha;else if(typeof t=="string"){let i=jn.get(t);if(i===null)throw new Error("Unable to parse color from string: "+t);this.model=i.model,n=$e[this.model].channels,this.color=i.value.slice(0,n),this.valpha=typeof i.value[n]=="number"?i.value[n]:1}else if(t.length>0){this.model=e||"rgb",n=$e[this.model].channels;let i=Array.prototype.slice.call(t,0,n);this.color=Sl(i,n),this.valpha=typeof t[n]=="number"?t[n]: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 i=Object.keys(t);"alpha"in t&&(i.splice(i.indexOf("alpha"),1),this.valpha=typeof t.alpha=="number"?t.alpha:0);let s=i.sort().join("");if(!(s in vl))throw new Error("Unable to parse color from object: "+JSON.stringify(t));this.model=vl[s];let{labels:o}=$e[this.model],a=[];for(r=0;r<o.length;r++)a.push(t[o[r]]);this.color=Sl(a)}if(pa[this.model])for(n=$e[this.model].channels,r=0;r<n;r++){let i=pa[this.model][r];i&&(this.color[r]=i(this.color[r]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}ve.prototype={toString(){return this.string()},toJSON(){return this[this.model]()},string(t){let e=this.model in jn.to?this:this.rgb();e=e.round(typeof t=="number"?t:1);let r=e.valpha===1?e.color:[...e.color,this.valpha];return jn.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 jn.to.rgb.percent(r)},array(){return this.valpha===1?[...this.color]:[...this.color,this.valpha]},object(){let t={},{channels:e}=$e[this.model],{labels:r}=$e[this.model];for(let n=0;n<e;n++)t[r[n]]=this.color[n];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 ve([...this.color.map(E0(t)),this.valpha],this.model)},alpha(t){return t!==void 0?new ve([...this.color,Math.max(0,Math.min(1,t))],this.model):this.valpha},red:oe("rgb",0,ge(255)),green:oe("rgb",1,ge(255)),blue:oe("rgb",2,ge(255)),hue:oe(["hsl","hsv","hsl","hwb","hcg"],0,t=>(t%360+360)%360),saturationl:oe("hsl",1,ge(100)),lightness:oe("hsl",2,ge(100)),saturationv:oe("hsv",1,ge(100)),value:oe("hsv",2,ge(100)),chroma:oe("hcg",1,ge(100)),gray:oe("hcg",2,ge(100)),white:oe("hwb",1,ge(100)),wblack:oe("hwb",2,ge(100)),cyan:oe("cmyk",0,ge(100)),magenta:oe("cmyk",1,ge(100)),yellow:oe("cmyk",2,ge(100)),black:oe("cmyk",3,ge(100)),x:oe("xyz",0,ge(95.047)),y:oe("xyz",1,ge(100)),z:oe("xyz",2,ge(108.833)),l:oe("lab",0,ge(100)),a:oe("lab",1),b:oe("lab",2),keyword(t){return t!==void 0?new ve(t):$e[this.model].keyword(this.color)},hex(t){return t!==void 0?new ve(t):jn.to.hex(this.rgb().round().color)},hexa(t){if(t!==void 0)return new ve(t);let e=this.rgb().round().color,r=Math.round(this.valpha*255).toString(16).toUpperCase();return r.length===1&&(r="0"+r),jn.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,n]of t.entries()){let i=n/255;e[r]=i<=.04045?i/12.92:((i+.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 ve.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(),n=this.rgb(),i=e===void 0?.5:e,s=2*i-1,o=r.alpha()-n.alpha(),a=((s*o===-1?s:(s+o)/(1+s*o))+1)/2,c=1-a;return ve.rgb(a*r.red()+c*n.red(),a*r.green()+c*n.green(),a*r.blue()+c*n.blue(),r.alpha()*i+n.alpha()*(1-i))}};for(let t of Object.keys($e)){if($m.includes(t))continue;let{channels:e}=$e[t];ve.prototype[t]=function(...r){return this.model===t?new ve(this):r.length>0?new ve(r,t):new ve([...T0($e[this.model][t].raw(this.color)),this.valpha],t)},ve[t]=function(...r){let n=r[0];return typeof n=="number"&&(n=Sl(r,e)),new ve(n,t)}}function k0(t,e){return Number(t.toFixed(e))}function E0(t){return function(e){return k0(e,t)}}function oe(t,e,r){t=Array.isArray(t)?t:[t];for(let n of t)(pa[n]||(pa[n]=[]))[e]=r;return t=t[0],function(n){let i;return n!==void 0?(r&&(n=r(n)),i=this[t](),i.color[e]=n,i):(i=this[t]().color[e],r&&(i=r(i)),i)}}function ge(t){return function(e){return Math.max(0,Math.min(t,e))}}function T0(t){return Array.isArray(t)?t:[t]}function Sl(t,e){for(let r=0;r<e;r++)typeof t[r]!="number"&&(t[r]=0);return t}Mm.exports=ve});import{usePathname as QS}from"next/navigation";import{useCallback as sr,useEffect as ar,useMemo as Me,useRef as Vt,useState as or}from"react";import{create as Rv}from"zustand";function Oe(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Qi(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(d){o(d)}}function c(u){try{l(n.throw(u))}catch(d){o(d)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(t,e||[])).next())})}var Wl=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var Wr=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}},Bn=class extends Wr{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},zr=class extends Wr{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Kr=class extends Wr{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 Hn=class{constructor(e,{headers:r={},customFetch:n,region:i=Vn.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=Wl(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Qi(this,arguments,void 0,function*(r,n={}){var i;let s,o;try{let{headers:a,method:c,body:l,signal:u,timeout:d}=n,h={},{region:f}=n;f||(f=this.region);let m=new URL(`${this.url}/${r}`);f&&f!=="any"&&(h["x-region"]=f,m.searchParams.set("forceFunctionRegion",f));let g;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",g=l):typeof l=="string"?(h["Content-Type"]="text/plain",g=l):typeof FormData<"u"&&l instanceof FormData?g=l:(h["Content-Type"]="application/json",g=JSON.stringify(l)):l&&typeof l!="string"&&!(typeof Blob<"u"&&l instanceof Blob)&&!(l instanceof ArrayBuffer)&&!(typeof FormData<"u"&&l instanceof FormData)?g=JSON.stringify(l):g=l;let y=u;d&&(o=new AbortController,s=setTimeout(()=>o.abort(),d),u?(y=o.signal,u.addEventListener("abort",()=>o.abort())):y=o.signal);let p=yield this.fetch(m.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),a),body:g,signal:y}).catch(D=>{throw new Bn(D)}),_=p.headers.get("x-relay-error");if(_&&_==="true")throw new zr(p);if(!p.ok)throw new Kr(p);let b=((i=p.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),w;return b==="application/json"?w=yield p.json():b==="application/octet-stream"||b==="application/pdf"?w=yield p.blob():b==="text/event-stream"?w=p:b==="multipart/form-data"?w=yield p.formData():w=yield p.text(),{data:w,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof Kr||a instanceof zr?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var Gl=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},qp=class{constructor(t){var e,r,n;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let n=this.fetch,i=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let o=null,a=null,c=null,l=s.status,u=s.statusText;if(s.ok){var d,h;if(r.method!=="HEAD"){var f;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let m=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(h=s.headers.get("content-range"))===null||h===void 0?void 0:h.split("/");m&&g&&g.length>1&&(c=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,c=null,l=406,u="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let m=await s.text();try{o=JSON.parse(m),Array.isArray(o)&&s.status===404&&(a=[],o=null,l=200,u="OK")}catch{s.status===404&&m===""?(l=204,u="No Content"):o={message:m}}if(o&&r.shouldThrowOnError)throw new Gl(o)}return{error:o,data:a,count:c,status:l,statusText:u}});return this.shouldThrowOnError||(i=i.catch(s=>{var o;let a="",c="",l="",u=s?.cause;if(u){var d,h,f,m;let p=(d=u?.message)!==null&&d!==void 0?d:"",_=(h=u?.code)!==null&&h!==void 0?h:"";a=`${(f=s?.name)!==null&&f!==void 0?f:"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})},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+=`
3
3
 
4
- Caused by: ${(m=u?.name)!==null&&m!==void 0?m:"Error"}: ${p}`,_&&(a+=` (${_})`),u?.stack&&(a+=`
5
- ${u.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"?(l="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. 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.`)):(u?.name==="HeadersOverflowError"||u?.code==="UND_ERR_HEADERS_OVERFLOW")&&(l="",c="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(c+=`. 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:`${(o=s?.name)!==null&&o!==void 0?o:"FetchError"}: ${s?.message}`,details:a,hint:c,code:l},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}returns(){return this}overrideTypes(){return this}},Bp=class extends qp{select(t){let e=!1,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:i=n}={}){let s=i?`${i}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let i=typeof n>"u"?"offset":`${n}.offset`,s=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${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:n=!1,wal:i=!1,format:s="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${c}"; 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}},zl=new RegExp("[,()]"),Gr=class extends Bp{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&zl.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&zl.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}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 n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Vp=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:i=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:n}=e??{},i=r?"HEAD":"GET",s=!1,o=(t??"*").split("").map(l=>/\s/.test(l)&&!s?"":(l==='"'&&(s=!s),l)).join(""),{url:a,headers:c}=this.cloneRequestState();return a.searchParams.set("select",o),n&&c.append("Prefer",`count=${n}`),new Gr({method:i,url:a,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;let i="POST",{url:s,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((c,l)=>c.concat(Object.keys(l)),[]);if(a.length>0){let c=[...new Set(a)].map(l=>`"${l}"`);s.searchParams.set("columns",c.join(","))}}return new Gr({method:i,url:s,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){var s;let o="POST",{url:a,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&c.append("Prefer",`count=${n}`),i||c.append("Prefer","missing=default"),Array.isArray(t)){let l=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(l.length>0){let u=[...new Set(l)].map(d=>`"${d}"`);a.searchParams.set("columns",u.join(","))}}return new Gr({method:o,url:a,headers:c,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 n="PATCH",{url:i,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Gr({method:n,url:i,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:n,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new Gr({method:r,url:n,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Wn(t){"@babel/helpers - typeof";return Wn=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},Wn(t)}function Hp(t,e){if(Wn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Wn(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Wp(t){var e=Hp(t,"string");return Wn(e)=="symbol"?e:e+""}function zp(t,e,r){return(e=Wp(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Kl(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function es(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Kl(Object(r),!0).forEach(function(n){zp(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Kl(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var Jl=class Yl{constructor(e,{headers:r={},schema:n,fetch:i,timeout:s,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let a=i??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,l)=>{let u=new AbortController,d=setTimeout(()=>u.abort(),s),h=l?.signal;if(h){if(h.aborted)return clearTimeout(d),a(c,l);let f=()=>{clearTimeout(d),u.abort()};return h.addEventListener("abort",f,{once:!0}),a(c,es(es({},l),{},{signal:u.signal})).finally(()=>{clearTimeout(d),h.removeEventListener("abort",f)})}return a(c,es(es({},l),{},{signal:u.signal})).finally(()=>clearTimeout(d))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Vp(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Yl(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:n=!1,get:i=!1,count:s}={}){var o;let a,c=new URL(`${this.url}/rpc/${e}`),l,u=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(u)),d=n&&Object.values(r).some(u);d?(a="POST",l=r):n||i?(a=n?"HEAD":"GET",Object.entries(r).filter(([f,m])=>m!==void 0).map(([f,m])=>[f,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([f,m])=>{c.searchParams.append(f,m)})):(a="POST",l=r);let h=new Headers(this.headers);return d?h.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&h.set("Prefer",`count=${s}`),new Gr({method:a,url:c,headers:h,schema:this.schemaName,body:l,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var Ia=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let n=r.versions;if(n&&n.node){let i=n.node,s=parseInt(i.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:
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:
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}}},Ra=Ia;var Xl="2.100.1";var Zl=`realtime-js/${Xl}`,Ql="1.0.0",Aa="2.0.0",eu=Aa;var tu=1e4;var ru=100;var gt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ts={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 Kn=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var i,s;let o=e.topic,a=(i=e.ref)!==null&&i!==void 0?i:"",c=(s=e.join_ref)!==null&&s!==void 0?s:"",l=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(u).length===0?"":JSON.stringify(u);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let h=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+a.length+o.length+l.length+d.length,f=new ArrayBuffer(this.HEADER_LENGTH+h),m=new DataView(f),g=0;m.setUint8(g++,this.KINDS.userBroadcastPush),m.setUint8(g++,c.length),m.setUint8(g++,a.length),m.setUint8(g++,o.length),m.setUint8(g++,l.length),m.setUint8(g++,d.length),m.setUint8(g++,r),Array.from(c,p=>m.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>m.setUint8(g++,p.charCodeAt(0))),Array.from(o,p=>m.setUint8(g++,p.charCodeAt(0))),Array.from(l,p=>m.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>m.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(f.byteLength+n.byteLength);return y.set(new Uint8Array(f),0),y.set(new Uint8Array(n),f.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[i,s,o,a,c]=n;return r({join_ref:i,ref:s,topic:o,event:a,payload:c})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),i=new TextDecoder;if(n===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,i)}_decodeUserBroadcast(e,r,n){let i=r.getUint8(1),s=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),c=this.HEADER_LENGTH+4,l=n.decode(e.slice(c,c+i));c=c+i;let u=n.decode(e.slice(c,c+s));c=c+s;let d=n.decode(e.slice(c,c+o));c=c+o;let h=e.slice(c,e.byteLength),f=a===this.JSON_ENCODING?JSON.parse(n.decode(h)):h,m={type:this.BROADCAST_EVENT,event:u,payload:f};return o>0&&(m.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:m}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};var X;(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"})(X||(X={}));var Na=(t,e,r={})=>{var n;let i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((s,o)=>(s[o]=Kp(o,t,e,i),s),{}):{}},Kp=(t,e,r,n)=>{let i=e.find(a=>a.name===t),s=i?.type,o=r[t];return s&&!n.includes(s)?nu(s,o):Da(o)},nu=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Xp(e,r)}switch(t){case X.bool:return Gp(e);case X.float4:case X.float8:case X.int2:case X.int4:case X.int8:case X.numeric:case X.oid:return Jp(e);case X.json:case X.jsonb:return Yp(e);case X.timestamp:return Zp(e);case X.abstime:case X.date:case X.daterange:case X.int4range:case X.int8range:case X.money:case X.reltime:case X.text:case X.time:case X.timestamptz:case X.timetz:case X.tsrange:case X.tstzrange:return Da(e);default:return Da(e)}},Da=t=>t,Gp=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Jp=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Yp=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Xp=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let s,o=t.slice(1,r);try{s=JSON.parse("["+o+"]")}catch{s=o?o.split(","):[]}return s.map(a=>nu(e,a))}return t},Zp=t=>typeof t=="string"?t.replace(" ","T"):t,rs=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 Jn=t=>typeof t=="function"?t:function(){return t},eg=typeof self<"u"?self:null,Yr=typeof window<"u"?window:null,yt=eg||Yr||globalThis,tg="2.0.0",rg=1e4,ng=1e3,_t={connecting:0,open:1,closing:2,closed:3},Pe={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},It={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},La={longpoll:"longpoll",websocket:"websocket"},ig={complete:4},ja="base64url.bearer.phx.",ns=class{constructor(t,e,r,n){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=n,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(n=>n.status===t).forEach(n=>n.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})}},iu=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))}},sg=class{constructor(t,e,r){this.state=Pe.closed,this.topic=t,this.params=Jn(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new ns(this,It.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new iu(()=>{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=Pe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",n=>{this.state=Pe.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Pe.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Pe.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 ns(this,It.leave,Jn({}),this.timeout).send(),this.state=Pe.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(It.reply,(n,i)=>{this.trigger(this.replyEventName(i),n)})}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=Pe.closed,this.bindings=[]}onClose(t){this.on(It.close,t)}onError(t){return this.on(It.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 n=new ns(this,t,function(){return e},r);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Pe.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(It.close,"leave")},r=new ns(this,It.leave,Jn({}),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,n){return this.topic!==t?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Pe.joining,this.joinPush.resend(t))}trigger(t,e,r,n){let i=this.onMessage(t,e,r,n);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;o<s.length;o++)s[o].callback(i,r,n||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===Pe.closed}isErrored(){return this.state===Pe.errored}isJoined(){return this.state===Pe.joined}isJoining(){return this.state===Pe.joining}isLeaving(){return this.state===Pe.leaving}},ss=class{static request(t,e,r,n,i,s,o){if(yt.XDomainRequest){let a=new yt.XDomainRequest;return this.xdomainRequest(a,t,e,n,i,s,o)}else if(yt.XMLHttpRequest){let a=new yt.XMLHttpRequest;return this.xhrRequest(a,t,e,r,n,i,s,o)}else{if(yt.fetch&&yt.AbortController)return this.fetchRequest(t,e,r,n,i,s,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,n,i,s,o){let a={method:t,headers:r,body:n},c=null;if(i){c=new AbortController;let l=setTimeout(()=>c.abort(),i);a.signal=c.signal}return yt.fetch(e,a).then(l=>l.text()).then(l=>this.parseJSON(l)).then(l=>o&&o(l)).catch(l=>{l.name==="AbortError"&&s?s():o&&o(null)}),c}static xdomainRequest(t,e,r,n,i,s,o){return t.timeout=i,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a)},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,r,n,i,s,o,a){t.open(e,r,!0),t.timeout=s;for(let[c,l]of Object.entries(n))t.setRequestHeader(c,l);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===ig.complete&&a){let c=this.parseJSON(t.responseText);a(c)}},o&&(t.ontimeout=o),t.send(i),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 n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=e?`${e}[${n}]`:n,s=t[n];typeof s=="object"?r.push(this.serialize(s,i)):r.push(encodeURIComponent(i)+"="+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)}`}},og=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let i=0;i<n;i++)e+=String.fromCharCode(r[i]);return btoa(e)},Jr=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(ja)&&(this.authToken=atob(e[1].slice(ja.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=_t.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+La.websocket),"$1/"+La.longpoll)}endpointURL(){return ss.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=_t.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===_t.open||this.readyState===_t.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:n,messages:i}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=n}else r=0;switch(r){case 200:i.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=_t.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=og(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 i of this.reqs)i.abort();this.readyState=_t.closed;let n=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",n)):this.onclose(n)}ajax(t,e,r,n,i){let s,o=()=>{this.reqs.delete(s),n()};s=ss.request(t,this.endpointURL(),e,r,this.timeout,o,a=>{this.reqs.delete(s),this.isActive()&&i(a)}),this.reqs.add(s)}},os=class Gn{constructor(e,r={}){let n=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(n.state,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Gn.syncState(this.state,i,s,o),this.pendingDiffs.forEach(c=>{this.state=Gn.syncDiff(this.state,c,s,o)}),this.pendingDiffs=[],a()}),this.channel.on(n.diff,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Gn.syncDiff(this.state,i,s,o),a())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return Gn.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,n,i){let s=this.clone(e),o={},a={};return this.map(s,(c,l)=>{r[c]||(a[c]=l)}),this.map(r,(c,l)=>{let u=s[c];if(u){let d=l.metas.map(g=>g.phx_ref),h=u.metas.map(g=>g.phx_ref),f=l.metas.filter(g=>h.indexOf(g.phx_ref)<0),m=u.metas.filter(g=>d.indexOf(g.phx_ref)<0);f.length>0&&(o[c]=l,o[c].metas=f),m.length>0&&(a[c]=this.clone(u),a[c].metas=m)}else o[c]=l}),this.syncDiff(s,{joins:o,leaves:a},n,i)}static syncDiff(e,r,n,i){let{joins:s,leaves:o}=this.clone(r);return n||(n=function(){}),i||(i=function(){}),this.map(s,(a,c)=>{let l=e[a];if(e[a]=this.clone(c),l){let u=e[a].metas.map(h=>h.phx_ref),d=l.metas.filter(h=>u.indexOf(h.phx_ref)<0);e[a].metas.unshift(...d)}n(a,l,c)}),this.map(o,(a,c)=>{let l=e[a];if(!l)return;let u=c.metas.map(d=>d.phx_ref);l.metas=l.metas.filter(d=>u.indexOf(d.phx_ref)<0),i(a,l,c),l.metas.length===0&&delete e[a]}),e}static list(e,r){return r||(r=function(n,i){return i}),this.map(e,(n,i)=>r(n,i))}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static clone(e){return JSON.parse(JSON.stringify(e))}},is={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,n,i,s,o]=JSON.parse(t);return e({join_ref:r,ref:n,topic:i,event:s,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:n,topic:i,payload:s}=t,o=this.META_LENGTH+e.length+r.length+i.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),c=new DataView(a),l=0;c.setUint8(l++,this.KINDS.push),c.setUint8(l++,e.length),c.setUint8(l++,r.length),c.setUint8(l++,i.length),c.setUint8(l++,n.length),Array.from(e,d=>c.setUint8(l++,d.charCodeAt(0))),Array.from(r,d=>c.setUint8(l++,d.charCodeAt(0))),Array.from(i,d=>c.setUint8(l++,d.charCodeAt(0))),Array.from(n,d=>c.setUint8(l++,d.charCodeAt(0)));var u=new Uint8Array(a.byteLength+s.byteLength);return u.set(new Uint8Array(a),0),u.set(new Uint8Array(s),a.byteLength),u.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(o,o+n));o=o+n;let c=r.decode(t.slice(o,o+i));o=o+i;let l=r.decode(t.slice(o,o+s));o=o+s;let u=t.slice(o,t.byteLength);return{join_ref:a,ref:null,topic:c,event:l,payload:u}},decodeReply(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,c=r.decode(t.slice(a,a+n));a=a+n;let l=r.decode(t.slice(a,a+i));a=a+i;let u=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+o));a=a+o;let h=t.slice(a,t.byteLength),f={status:d,response:h};return{join_ref:c,ref:l,topic:u,event:It.reply,payload:f}},decodeBroadcast(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=this.HEADER_LENGTH+2,o=r.decode(t.slice(s,s+n));s=s+n;let a=r.decode(t.slice(s,s+i));s=s+i;let c=t.slice(s,t.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:c}}},as=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||rg,this.transport=e.transport||yt.WebSocket||Jr,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||yt&&yt.sessionStorage,this.establishedConnections=0,this.defaultEncoder=is.encode.bind(is),this.defaultDecoder=is.decode.bind(is),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!==Jr?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;Yr&&Yr.addEventListener&&(Yr.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),r=this.connectClock)}),Yr.addEventListener("pageshow",n=>{r===this.connectClock&&(r=null,this.connect())}),Yr.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=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,s)=>{console.log(`${n}: ${i}`,s)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Jn(e.params||{}),this.endPoint=`${t}/${La.websocket}`,this.vsn=e.vsn||tg,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new iu(()=>{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 Jr}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=ss.appendParams(ss.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=Jn(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Jr?this.connectWithFallback(Jr,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 n=this.onMessage(i=>{i.ref===e&&(this.off([n]),t(Date.now()-r))});return!0}transportName(t){return t===Jr?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${ja}${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,n=!0,i,s,o=this.transportName(t),a=c=>{this.log("transport",`falling back to ${o}...`,c),this.off([i,s]),n=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(c=>{this.log("transport","error",c),n&&!r&&(clearTimeout(this.fallbackTimer),a(c))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!n){let c=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${c}`,"true"),this.log("transport",`established ${c} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(c=>{this.log("transport","connected to primary after",c),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(),ng,"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 n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,r||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(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===_t.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(It.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case _t.connecting:return"connecting";case _t.open:return"open";case _t.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 sg(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:n,ref:i,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${i})`,n)}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:n,payload:i,ref:s,join_ref:o}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",a)}catch(c){this.log("error","error in heartbeat callback",c)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${n} ${s&&"("+s+")"||""}`.trim(),i);for(let a=0;a<this.channels.length;a++){let c=this.channels[a];c.isMember(r,n,i,o)&&c.trigger(n,i,s,o)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,n])=>{try{n(...e)}catch(i){this.log("error",`error in ${t} callback`,i)}})}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 Yn=class t{constructor(e,r){let n=cg(r);this.presence=new os(e.getChannel(),n),this.presence.onJoin((i,s,o)=>{let a=t.onJoinPayload(i,s,o);e.getChannel().trigger("presence",a)}),this.presence.onLeave((i,s,o)=>{let a=t.onLeavePayload(i,s,o);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=ag(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let i=e[n];return r[n]=cs(i),r},{})}static onJoinPayload(e,r,n){let i=su(r),s=cs(n);return{event:"join",key:e,currentPresences:i,newPresences:s}}static onLeavePayload(e,r,n){let i=su(r),s=cs(n);return{event:"leave",key:e,currentPresences:i,leftPresences:s}}};function cs(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function ag(t){return JSON.parse(JSON.stringify(t))}function cg(t){return t?.events&&{events:t.events}}function su(t){return t?.metas?cs(t):[]}var $a;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})($a||($a={}));var Xr=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Yn(this.channel.channelAdapter,r)}};var Xn=class{constructor(e,r,n){let i=lg(n);this.channel=e.getSocket().channel(r,i),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,n){let i;try{i=this.channel.push(e,r,n)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>ru){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return i}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===gt.joined}isJoined(){return this.state===gt.joined}isJoining(){return this.state===gt.joining}isClosed(){return this.state===gt.closed}isLeaving(){return this.state===gt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function lg(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Ma;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Ma||(Ma={}));var Zr;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Zr||(Zr={}));var bt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(bt||(bt={}));var Qr=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:{}},n){var i,s;if(this.topic=e,this.params=r,this.socket=n,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 Xn(this.socket.socketAdapter,e,this.params),this.presence=new Xr(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=rs(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(i=this.params.config)===null||i===void 0?void 0:i.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 n,i,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:o,presence:a,private:c}}=this.params,l=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(f=>f.filter))!==null&&i!==void 0?i:[],u=!!this.bindings[Zr.PRESENCE]&&this.bindings[Zr.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},h={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:l,private:c};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(f=>{e?.(bt.CHANNEL_ERROR,f)}),this._onClose(()=>e?.(bt.CLOSED)),this.updateJoinPayload(Object.assign({config:h},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:f})=>{if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e?.(bt.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",f=>{this.state=gt.errored,e?.(bt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e?.(bt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var n;let i=this.bindings.postgres_changes,s=(n=i?.length)!==null&&n!==void 0?n:0,o=[];for(let a=0;a<s;a++){let c=i[a],{filter:{event:l,schema:u,table:d,filter:h}}=c,f=e&&e[a];if(f&&f.event===l&&t.isFilterValueEqual(f.schema,u)&&t.isFilterValueEqual(f.table,d)&&t.isFilterValueEqual(f.filter,h))o.push(Object.assign(Object.assign({},c),{id:f.id}));else{this.unsubscribe(),this.state=gt.errored,r?.(bt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=gt.errored&&r&&r(bt.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,n){if(this.channelAdapter.isJoined()&&e===Zr.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,n)}async httpSend(e,r,n={}){var i;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 o={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(i=n.timeout)!==null&&i!==void 0?i:this.timeout);if(a.status===202)return{success:!0};let c=a.statusText;try{let l=await a.json();c=l.error||l.message||c}catch{}return Promise.reject(new Error(c))}async send(e,r={}){var n,i;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:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let c={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o,private:this.private}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,a,c;let l=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&s("ok"),l.receive("ok",()=>s("ok")),l.receive("error",()=>s("error")),l.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,n){let i=new AbortController,s=setTimeout(()=>i.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(s),o}_on(e,r,n){let i=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,n),o={type:i,filter:r,callback:n,ref:s};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var i,s,o,a,c,l,u;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,n))return!1;let h=(i=this.bindings[d])===null||i===void 0?void 0:i.find(f=>f.ref===e.ref);if(!h)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in h){let f=h.id,m=(s=h.filter)===null||s===void 0?void 0:s.event;return f&&((o=r.ids)===null||o===void 0?void 0:o.includes(f))&&(m==="*"||m?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let f=(l=(c=h?.filter)===null||c===void 0?void 0:c.event)===null||l===void 0?void 0:l.toLocaleLowerCase();return f==="*"||f===((u=r?.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return h.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:n,error:i,leave:s,join:o}=ts;return r&&[n,i,s,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){let i=r.data,{schema:s,table:o,commit_timestamp:a,type:c,errors:l}=i;return Object.assign(Object.assign({},{schema:s,table:o,commit_timestamp:a,eventType:c,new:{},old:{},errors:l}),this._getPayloadRecords(i))}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=Na(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Na(e.columns,e.old_record)),r}};var Zn=class{constructor(e,r){this.socket=new as(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,n,i=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),i),this.socket.disconnect(()=>{e(),s("ok")},r,n)})}push(e){this.socket.push(e)}log(e,r,n){this.socket.log(e,r,n)}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 ug={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},dg=[1e3,2e3,5e3,1e4],hg=1e4,fg=`
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=`
11
11
  addEventListener("message", (e) => {
12
12
  if (e.data.event === "start") {
13
13
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
14
14
  }
15
- });`,en=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var n;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new Kn,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...o)=>s(...o):(...o)=>fetch(...o),!(!((n=r?.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let i=this._initializeOptions(r);this.socketAdapter=new Zn(e,i),this.httpEndpoint=rs(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let r=e.message;throw r.includes("Node.js")?new Error(`${r}
15
+ });`,So=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var o;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new xn,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((o=r?.params)===null||o===void 0)&&o.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let n=this._initializeOptions(r);this.socketAdapter=new Pn(e,n),this.httpEndpoint=js(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let r=e.message;throw r.includes("Node.js")?new Error(`${r}
16
16
 
17
17
  To use Realtime in Node.js, you need to provide a WebSocket implementation:
18
18
 
@@ -25,36 +25,36 @@ 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 n=>{let i=await n.unsubscribe();return n.teardown(),i}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,n){this.socketAdapter.log(e,r,n)}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 n=`realtime:${e}`,i=this.getChannels().find(s=>s.topic===n);if(i)return i;{let s=new Qr(`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,n=!1;if(e)r=e,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue}else r=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{let s={access_token:r,version:Zl};r&&i.updateJoinPayload(s),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(ts.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,n)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,n)}}_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 n=new Blob([fg],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_initializeOptions(e){var r,n,i,s,o,a,c,l,u;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(n=e?.accessToken)!==null&&n!==void 0?n:null;let d={};d.timeout=(i=e?.timeout)!==null&&i!==void 0?i:tu,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:ug.HEARTBEAT_INTERVAL,d.transport=(o=e?.transport)!==null&&o!==void 0?o:Ra.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=>dg[g-1]||hg);let h,f,m=(c=e?.vsn)!==null&&c!==void 0?c:eu;switch(m){case Ql:h=(g,y)=>y(JSON.stringify(g)),f=(g,y)=>y(JSON.parse(g));break;case Aa:h=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=m,d.encode=(l=e?.encode)!==null&&l!==void 0?l:h,d.decode=(u=e?.decode)!==null&&u!==void 0?u:f,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 Qn=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 mg(t,e,r){let n=new URL(e,t);if(r)for(let[i,s]of Object.entries(r))s!==void 0&&n.searchParams.set(i,s);return n.toString()}async function pg(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 gg(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:i,body:s,headers:o}){let a=mg(t.baseUrl,n,i),c=await pg(t.auth),l=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...c,...o},body:s?JSON.stringify(s):void 0}),u=await l.text(),d=(l.headers.get("content-type")||"").includes("application/json"),h=d&&u?JSON.parse(u):u;if(!l.ok){let f=d?h:void 0,m=f?.error;throw new Qn(m?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:m?.type,icebergCode:m?.code,details:f})}return{status:l.status,headers:l.headers,data:h}}}}function ls(t){return t.join("")}var yg=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:ls(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ls(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ls(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ls(t.namespace)}`}),!0}catch(e){if(e instanceof Qn&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Qn&&r.status===409)return;throw r}}};function tn(t){return t.join("")}var _g=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/${tn(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/${tn(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/${tn(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/${tn(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/${tn(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/${tn(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Qn&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Qn&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},us=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=gg({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new yg(this.client,e),this.tableOps=new _g(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 ds=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}};function hs(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Ua=class extends ds{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},lu=class extends ds{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var bg=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),wg=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)},Fa=t=>{if(Array.isArray(t))return t.map(r=>Fa(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let i=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[i]=Fa(n)}),e},vg=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function ti(t){"@babel/helpers - typeof";return ti=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},ti(t)}function Sg(t,e){if(ti(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(ti(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function xg(t){var e=Sg(t,"string");return ti(e)=="symbol"?e:e+""}function kg(t,e,r){return(e=xg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ou(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function I(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?ou(Object(r),!0).forEach(function(n){kg(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):ou(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var au=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)},Eg=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let i=t,s=parseInt(i.status,10);Number.isFinite(s)||(s=500),i.json().then(o=>{let a=o?.statusCode||o?.code||s+"";e(new Ua(au(o),s,a,n))}).catch(()=>{let o=s+"";e(new Ua(i.statusText||`HTTP ${s} error`,s,o,n))})}else e(new lu(au(t),t,n))},Tg=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!n?I(I({},i),r):(wg(n)?(i.headers=I({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(n)):i.body=n,e?.duplex&&(i.duplex=e.duplex),I(I({},i),r))};async function ei(t,e,r,n,i,s,o){return new Promise((a,c)=>{t(r,Tg(e,n,i,s)).then(l=>{if(!l.ok)throw l;if(n?.noResolveJson)return l;if(o==="vectors"){let u=l.headers.get("content-type");if(l.headers.get("content-length")==="0"||l.status===204)return{};if(!u||!u.includes("application/json"))return{}}return l.json()}).then(l=>a(l)).catch(l=>Eg(l,c,n,o))})}function uu(t="storage"){return{get:async(e,r,n,i)=>ei(e,"GET",r,n,i,void 0,t),post:async(e,r,n,i,s)=>ei(e,"POST",r,i,s,n,t),put:async(e,r,n,i,s)=>ei(e,"PUT",r,i,s,n,t),head:async(e,r,n,i)=>ei(e,"HEAD",r,I(I({},n),{},{noResolveJson:!0}),i,void 0,t),remove:async(e,r,n,i,s)=>ei(e,"DELETE",r,i,s,n,t)}}var Og=uu("storage"),{get:ri,post:rt,put:qa,head:Pg,remove:Ba}=Og,De=uu("vectors"),rn=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=bg(r),this.namespace=n}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(hs(r))return{data:null,error:r};throw r}}},Cg=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(hs(e))return{data:null,error:e};throw e}}},du;du=Symbol.toStringTag;var Ig=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[du]="BlobDownloadBuilder",this.promise=null}asStream(){return new Cg(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(hs(e))return{data:null,error:e};throw e}}},Rg={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},cu={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Ag=class extends rn{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var i=this;return i.handleOperation(async()=>{let s,o=I(I({},cu),n),a=I(I({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),c=o.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),c&&s.append("metadata",i.encodeMetadata(c)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",o.cacheControl),c&&!s.has("metadata")&&s.append("metadata",i.encodeMetadata(c))):(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,c&&(a["x-metadata"]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=I(I({},a),n.headers));let l=i._removeEmptyFolders(e),u=i._getFinalPath(l),d=await(t=="PUT"?qa:rt)(i.fetch,`${i.url}/object/${u}`,s,I({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:l,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var i=this;let s=i._removeEmptyFolders(t),o=i._getFinalPath(s),a=new URL(i.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),i.handleOperation(async()=>{let c,l=I(I({},cu),n),u=I(I({},i.headers),{"x-upsert":String(l.upsert)});return typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",l.cacheControl)):(c=r,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType),{path:s,fullPath:(await qa(i.fetch,a.toString(),c,{headers:u})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),i=I({},r.headers);e?.upsert&&(i["x-upsert"]="true");let s=await rt(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:i}),o=new URL(r.url+s.url),a=o.searchParams.get("token");if(!a)throw new ds("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await rt(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await rt(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await rt(n.fetch,`${n.url}/object/sign/${i}`,I({expiresIn:e},s?{transform:r.transform}:{}),{headers:n.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",c=s&&o.signedURL.includes("/object/sign/")?o.signedURL.replace("/object/sign/","/render/image/sign/"):o.signedURL;return{signedUrl:encodeURI(`${n.url}${c}${a}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let i=await rt(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return i.map(o=>I(I({},o),{},{signedUrl:o.signedURL?encodeURI(`${n.url}${o.signedURL}${s}`):null}))})}download(t,e,r){let n=typeof e?.transform<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString(e?.transform||{}),s=i?`?${i}`:"",o=this._getFinalPath(t),a=()=>ri(this.fetch,`${this.url}/${n}/${o}${s}`,{headers:this.headers,noResolveJson:!0},r);return new Ig(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>Fa(await ri(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await Pg(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(hs(i)){var n;let s=i instanceof Ua?i.status:i instanceof lu?(n=i.originalError)===null||n===void 0?void 0:n.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:i}}throw i}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=[],i=e?.download?`download=${e.download===!0?"":e.download}`:"";i!==""&&n.push(i);let s=typeof e?.transform<"u"?"render/image":"object",o=this.transformOptsToQueryString(e?.transform||{});o!==""&&n.push(o);let a=n.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await Ba(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let i=I(I(I({},Rg),e),{},{prefix:t||""});return await rt(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=I({},t);return await rt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},Dg="2.100.1",ni={"X-Client-Info":`storage-js/${Dg}`},Ng=class extends rn{constructor(t,e={},r,n){let i=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));let s=i.href.replace(/\/$/,""),o=I(I({},ni),e);super(s,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await ri(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await ri(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await rt(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 qa(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 rt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ba(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():""}},Lg=class extends rn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=I(I({},ni),e);super(n,i,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await rt(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),i=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await ri(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ba(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!vg(t))throw new ds("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 us({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,s){let o=i[s];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(i,a),error:null}}catch(c){if(n)throw c;return{data:null,error:c}}}}})}},jg=class extends rn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=I(I({},ni),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await De.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await De.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},$g=class extends rn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=I(I({},ni),{},{"Content-Type":"application/json"},e);super(n,i,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 De.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await De.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 De.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await De.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 De.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Mg=class extends rn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=I(I({},ni),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await De.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Ug=class extends Mg{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Fg(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)}},Fg=class extends jg{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,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 qg(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},qg=class extends $g{constructor(t,e,r,n,i){super(t,e,i),this.vectorBucketName=r,this.indexName=n}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}))}},hu=class extends Ng{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new Ag(this.url,this.headers,t,this.fetch)}get vectors(){return new Ug(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Lg(this.url+"/iceberg",this.headers,this.fetch)}};var fs="2.100.1";var ur=30*1e3,ms=3,ps=ms*ur,fu="http://localhost:9999",mu="supabase.auth.token";var pu={"X-Client-Info":`gotrue-js/${fs}`};var ii="X-Supabase-Api-Version",Va={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},gu=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,yu=600*1e3;var Gt=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}};function x(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var gs=class extends Gt{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}};function _u(t){return x(t)&&t.name==="AuthApiError"}var Be=class extends Gt{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},nt=class extends Gt{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}},Se=class extends nt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function _s(t){return x(t)&&t.name==="AuthSessionMissingError"}var Rt=class extends nt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},dr=class extends nt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},hr=class extends nt{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 bu(t){return x(t)&&t.name==="AuthImplicitGrantRedirectError"}var si=class extends nt{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}}},ys=class extends nt{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 nn=class extends nt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function bs(t){return x(t)&&t.name==="AuthRetryableFetchError"}var oi=class extends nt{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}};var fr=class extends nt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var ws="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),wu=`
29
- \r=`.split(""),Bg=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<wu.length;e+=1)t[wu[e].charCodeAt(0)]=-2;for(let e=0;e<ws.length;e+=1)t[ws[e].charCodeAt(0)]=e;return t})();function vu(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(ws[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(ws[n]),e.queuedBits-=6}}function Su(t,e,r){let n=Bg[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Ha(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=o=>{Wg(o,n,r)};for(let o=0;o<t.length;o+=1)Su(t.charCodeAt(o),i,s);return e.join("")}function Vg(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 Hg(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}Vg(n,e)}}function Wg(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function Jt(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;i<t.length;i+=1)Su(t.charCodeAt(i),r,n);return new Uint8Array(e)}function xu(t){let e=[];return Hg(t,r=>e.push(r)),new Uint8Array(e)}function At(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};return t.forEach(i=>vu(i,r,n)),vu(null,r,n),e.join("")}function ku(t){return Math.round(Date.now()/1e3)+t}function Eu(){return Symbol("auth-callback")}var he=()=>typeof window<"u"&&typeof document<"u",mr={tested:!1,writable:!1},vs=()=>{if(!he())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(mr.tested)return mr.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),mr.tested=!0,mr.writable=!0}catch{mr.tested=!0,mr.writable=!1}return mr.writable};function Tu(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,s)=>{e[s]=i})}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n}),e}var Ss=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ou=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",pr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},Yt=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},be=async(t,e)=>{await t.removeItem(e)},ai=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};ai.promiseConstructor=Promise;function ci(t){let e=t.split(".");if(e.length!==3)throw new fr("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!gu.test(e[n]))throw new fr("JWT not in base64url format");return{header:JSON.parse(Ha(e[0])),payload:JSON.parse(Ha(e[1])),signature:Jt(e[2]),raw:{header:e[0],payload:e[1]}}}async function Pu(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Cu(t,e){return new Promise((n,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{let o=await t(s);if(!e(s,null,o)){n(o);return}}catch(o){if(!e(s,o)){i(o);return}}})()})}function zg(t){return("0"+t.toString(16)).substr(-2)}function Kg(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,i="";for(let s=0;s<56;s++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,zg).join("")}async function Gg(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}async function Jg(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 Gg(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function gr(t,e,r=!1){let n=Kg(),i=n;r&&(i+="/PASSWORD_RECOVERY"),await pr(t,`${e}-code-verifier`,i);let s=await Jg(n);return[s,n===s?"plain":"s256"]}var Yg=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Iu(t){let e=t.headers.get(ii);if(!e||!e.match(Yg))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Ru(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 Au(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 Xg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function yr(t){if(!Xg.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function xs(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Du(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){let s=n.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,n,i)}return!e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,n,i)}})}function Wa(t){return JSON.parse(JSON.stringify(t))}var _r=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Zg=[502,503,504];async function Nu(t){var e;if(!Ou(t))throw new nn(_r(t),0);if(Zg.includes(t.status))throw new nn(_r(t),t.status);let r;try{r=await t.json()}catch(s){throw new Be(_r(s),s)}let n,i=Iu(t);if(i&&i.getTime()>=Va["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new oi(_r(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Se}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,o)=>s&&typeof o=="string",!0))throw new oi(_r(r),t.status,r.weak_password.reasons);throw new gs(_r(r),t.status||500,n)}var Qg=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};async function O(t,e,r,n){var i;let s=Object.assign({},n?.headers);s[ii]||(s[ii]=Va["2024-01-01"].name),n?.jwt&&(s.Authorization=`Bearer ${n.jwt}`);let o=(i=n?.query)!==null&&i!==void 0?i:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await ey(t,e,r+a,{headers:s,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(c):{data:Object.assign({},c),error:null}}async function ey(t,e,r,n,i,s){let o=Qg(e,n,i,s),a;try{a=await t(r,Object.assign({},o))}catch(c){throw console.error(c),new nn(_r(c),0)}if(a.ok||await Nu(a),n?.noResolveJson)return a;try{return await a.json()}catch(c){await Nu(c)}}function Ve(t){var e;let r=null;ty(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=ku(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function za(t){let e=Ve(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function wt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Lu(t){return{data:t,error:null}}function ju(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s}=t,o=Oe(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Ka(t){return t}function ty(t){return t.access_token&&t.refresh_token&&t.expires_in}var ks=["global","local","others"];var br=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=Ss(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},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=ks[0]){if(ks.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ks.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(n){if(x(n))return{data:null,error:n};throw n}}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:wt})}catch(n){if(x(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=Oe(e,["options"]),i=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(i.new_email=n?.newEmail,delete i.newEmail),await O(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ju,redirectTo:r?.redirectTo})}catch(r){if(x(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:wt})}catch(r){if(x(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,s,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await O(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Ka});if(u.error)throw u.error;let d=await u.json(),h=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(m=>{let g=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(m.split(";")[1].split("=")[1]);l[`${y}Page`]=g}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(x(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){yr(e);try{return await O(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:wt})}catch(r){if(x(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){yr(e);try{return await O(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:wt})}catch(n){if(x(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){yr(e);try{return await O(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:wt})}catch(n){if(x(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){yr(e.userId);try{let{data:r,error:n}=await O(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:r,error:n}}catch(r){if(x(r))return{data:null,error:r};throw r}}async _deleteFactor(e){yr(e.userId),yr(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(x(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,i,s,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await O(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Ka});if(u.error)throw u.error;let d=await u.json(),h=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(m=>{let g=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(m.split(";")[1].split("=")[1]);l[`${y}Page`]=g}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(x(l))return{data:{clients:[]},error:l};throw l}}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(x(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(x(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:n=>({data:n,error:null})})}catch(n){if(x(n))return{data:null,error:n};throw n}}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(x(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(x(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:n=>{var i;return{data:{providers:(i=n?.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(x(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(x(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(x(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:n=>({data:n,error:null})})}catch(n){if(x(n))return{data:null,error:n};throw n}}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(x(r))return{data:null,error:r};throw r}}};function Ga(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var it={debug:!!(globalThis&&vs()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},sn=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},li=class extends sn{},Ja=class extends sn{};async function Ya(t,e,r){it.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController,i;e>0&&(i=setTimeout(()=>{n.abort(),it.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){clearTimeout(i),it.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{it.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw it.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new li(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(it.debug)try{let o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "))}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o)}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(i),await r()}})}catch(s){if(e>0&&clearTimeout(i),s?.name==="AbortError"&&e>0){if(n.signal.aborted)return it.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 o=>{if(o){it.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,o.name);try{return await r()}finally{it.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,o.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw it.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new li(`Lock "${t}" was released because another request stole it`)}throw s}}var $u={};async function Xa(t,e,r){var n;let i=(n=$u[t])!==null&&n!==void 0?n:Promise.resolve(),s=(async()=>{try{return await i,null}catch{return null}})(),o=(async()=>{let a=null;try{let c=e>=0?new Promise((l,u)=>{a=setTimeout(()=>{console.warn(`@supabase/gotrue-js: Lock "${t}" acquisition timed out after ${e}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),u(new Ja(`Acquiring process lock with name "${t}" timed out`))},e)}):null;await Promise.race([s,c].filter(l=>l)),a!==null&&clearTimeout(a)}catch(c){if(a!==null&&clearTimeout(a),c&&c.isAcquireTimeout)throw c}return await r()})();return $u[t]=(async()=>{try{return await o}catch(a){if(a&&a.isAcquireTimeout){try{await i}catch{}return null}throw a}})(),await o}function Mu(){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 Za(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Uu(t){return parseInt(t,16)}function Fu(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function qu(t){var e;let{chainId:r,domain:n,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:c,resources:l,scheme:u,uri:d,version:h}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(h!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);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 f=Za(t.address),m=u?`${u}://${n}`:n,g=t.statement?`${t.statement}
31
- `:"",y=`${m} wants you to sign in with your Ethereum account:
32
- ${f}
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=Ml(t.address),h=c?`${c}://${o}`:o,g=t.statement?`${t.statement}
31
+ `:"",y=`${h} wants you to sign in with your Ethereum account:
32
+ ${m}
33
33
 
34
34
  ${g}`,p=`URI: ${d}
35
- Version: ${h}
36
- Chain ID: ${r}${o?`
37
- Nonce: ${o}`:""}
38
- Issued At: ${s.toISOString()}`;if(i&&(p+=`
39
- Expiration Time: ${i.toISOString()}`),a&&(p+=`
40
- Not Before: ${a.toISOString()}`),c&&(p+=`
41
- Request ID: ${c}`),l){let _=`
42
- Resources:`;for(let b of l){if(!b||typeof b!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);_+=`
43
- - ${b}`}p+=_}return`${y}
44
- ${p}`}var te=class extends Error{constructor({message:e,code:r,cause:n,name:i}){var s;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(s=i??(n instanceof Error?n.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},wr=class extends te{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function Bu({error:t,options:e}){var r,n,i;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 te({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 te({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new te({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=s.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new te({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new te({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new te({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new te({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Qa(o)){if(s.rp.id!==o)return new te({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new te({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Vu({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new te({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if(Qa(n)){if(r.rpId!==n)return new te({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var ec=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}}},ry=new ec;function Wu(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:n}=t,i=Oe(t,["challenge","user","excludeCredentials"]),s=Jt(e).buffer,o=Object.assign(Object.assign({},r),{id:Jt(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:s,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let c=0;c<n.length;c++){let l=n[c];a.excludeCredentials[c]=Object.assign(Object.assign({},l),{id:Jt(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return a}function zu(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,n=Oe(t,["challenge","allowCredentials"]),i=Jt(e).buffer,s=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];s.allowCredentials[o]=Object.assign(Object.assign({},a),{id:Jt(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function Ku(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:At(new Uint8Array(t.response.attestationObject)),clientDataJSON:At(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Gu(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,n=t.getClientExtensionResults(),i=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:At(new Uint8Array(i.authenticatorData)),clientDataJSON:At(new Uint8Array(i.clientDataJSON)),signature:At(new Uint8Array(i.signature)),userHandle:i.userHandle?At(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Qa(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Hu(){var t,e;return!!(he()&&"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 ny(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new wr("Browser returned unexpected credential type",e)}:{data:null,error:new wr("Empty credential response",e)}}catch(e){return{data:null,error:Bu({error:e,options:t})}}}async function iy(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new wr("Browser returned unexpected credential type",e)}:{data:null,error:new wr("Empty credential response",e)}}catch(e){return{data:null,error:Vu({error:e,options:t})}}}var sy={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},oy={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Es(...t){let e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(let i of t)if(i)for(let s in i){let o=i[s];if(o!==void 0)if(Array.isArray(o))n[s]=o;else if(r(o))n[s]=o;else if(e(o)){let a=n[s];e(a)?n[s]=Es(a,o):n[s]=Es(o)}else n[s]=o}return n}function ay(t,e){return Es(sy,t,e||{})}function cy(t,e){return Es(oy,t,e||{})}var Ts=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:i},s){var o;try{let{data:a,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:c};let l=i??ry.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let d=n;if(d)u.name=`${u.id}:${d}`;else{let f=(await this.client.getUser()).data.user,m=((o=f?.user_metadata)===null||o===void 0?void 0:o.name)||f?.email||f?.id||"User";u.name=`${u.id}:${m}`}}u.displayName||(u.displayName=u.name)}switch(a.webauthn.type){case"create":{let u=ay(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:h}=await ny({publicKey:u,signal:l});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:h}}case"request":{let u=cy(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:h}=await iy(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:l}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:h}}}}catch(a){return x(a)?{data:null,error:a}:{data:null,error:new Be("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return{data:null,error:new Gt("rpId is required for WebAuthn authentication")};try{if(!Hu())return{data:null,error:new Be("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:s});if(!o)return{data:null,error:a};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:n,credential_response:c.credential_response}})}catch(o){return x(o)?{data:null,error:o}:{data:null,error:new Be("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return{data:null,error:new Gt("rpId is required for WebAuthn registration")};try{if(!Hu())return{data:null,error:new Be("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return(d=u.data)===null||d===void 0?void 0:d.all.find(h=>h.factor_type==="webauthn"&&h.friendly_name===e&&h.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};let{data:c,error:l}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:s});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:n,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:l}}catch(o){return x(o)?{data:null,error:o}:{data:null,error:new Be("Unexpected error in register",o)}}}};Mu();var ly={url:fu,storageKey:mu,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:pu,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Ju(t,e,r){return await r()}var on={},Os=class t{get jwks(){var e,r;return(r=(e=on[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){on[this.storageKey]=Object.assign(Object.assign({},on[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=on[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){on[this.storageKey]=Object.assign(Object.assign({},on[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,i;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({},ly),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&&he()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new br({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Ss(s.fetch),this.lock=s.lock||Ju,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&&he()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=Ya:this.lock=Ju,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 Ts(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:vs()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Ga(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Ga(this.memoryStorage)),he()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${fs}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if(he()&&(r=Tu(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),he()&&this.detectSessionInUrl&&n!=="none"){let{data:i,error:s}=await this._getSessionFromURL(r,n);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),bu(s)){let c=(e=s.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:s}}return{error:s}}let{session:o,redirectType:a}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return x(r)?this._returnResult({error:r}):this._returnResult({error:new Be("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{let s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:Ve}),{data:o,error:a}=s;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(s){if(x(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,n,i;try{let s;if("email"in e){let{email:u,password:d,options:h}=e,f=null,m=null;this.flowType==="pkce"&&([f,m]=await gr(this.storage,this.storageKey)),s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h?.emailRedirectTo,body:{email:u,password:d,data:(r=h?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:h?.captchaToken},code_challenge:f,code_challenge_method:m},xform:Ve})}else if("phone"in e){let{phone:u,password:d,options:h}=e;s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(n=h?.data)!==null&&n!==void 0?n:{},channel:(i=h?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:Ve})}else throw new dr("You must provide either an email or phone number and a password");let{data:o,error:a}=s;if(a||!o)return await be(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(s){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(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:o,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:za})}else if("phone"in e){let{phone:s,password:o,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:za})}else throw new dr("You must provide either an email or phone number and a password");let{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){let s=new Rt;return this._returnResult({data:{user:null,session:null},error:s})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.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,n,i,s,o,a,c,l,u,d,h;let f,m;if("message"in e)f=e.message,m=e.signature;else{let{chain:g,wallet:y,statement:p,options:_}=e,b;if(he())if(typeof y=="object")b=y;else{let M=window;if("ethereum"in M&&typeof M.ethereum=="object"&&"request"in M.ethereum&&typeof M.ethereum.request=="function")b=M.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"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=y}let w=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href),D=await b.request({method:"eth_requestAccounts"}).then(M=>M).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!D||D.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let S=Za(D[0]),C=(n=_?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!C){let M=await b.request({method:"eth_chainId"});C=Uu(M)}let K={domain:w.host,address:S,statement:p,uri:w.href,version:"1",chainId:C,nonce:(i=_?.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(s=_?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=_?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(c=_?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(l=_?.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(u=_?.signInWithEthereum)===null||u===void 0?void 0:u.resources};f=qu(K),m=await b.request({method:"personal_sign",params:[Fu(f),S]})}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:f,signature:m},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:Ve});if(y)throw y;if(!g||!g.session||!g.user){let p=new Rt;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(x(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,n,i,s,o,a,c,l,u,d,h,f;let m,g;if("message"in e)m=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:_,options:b}=e,w;if(he())if(typeof p=="object")w=p;else{let S=window;if("solana"in S&&typeof S.solana=="object"&&("signIn"in S.solana&&typeof S.solana.signIn=="function"||"signMessage"in S.solana&&typeof S.solana.signMessage=="function"))w=S.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"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=p}let D=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in w&&w.signIn){let S=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},b?.signInWithSolana),{version:"1",domain:D.host,uri:D.href}),_?{statement:_}:null)),C;if(Array.isArray(S)&&S[0]&&typeof S[0]=="object")C=S[0];else if(S&&typeof S=="object"&&"signedMessage"in S&&"signature"in S)C=S;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in C&&"signature"in C&&(typeof C.signedMessage=="string"||C.signedMessage instanceof Uint8Array)&&C.signature instanceof Uint8Array)m=typeof C.signedMessage=="string"?C.signedMessage:new TextDecoder().decode(C.signedMessage),g=C.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in w)||typeof w.signMessage!="function"||!("publicKey"in w)||typeof w!="object"||!w.publicKey||!("toBase58"in w.publicKey)||typeof w.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");m=[`${D.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${D.href}`,`Issued At: ${(i=(n=b?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((s=b?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${b.signInWithSolana.notBefore}`]:[],...!((o=b?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${b.signInWithSolana.expirationTime}`]:[],...!((a=b?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${b.signInWithSolana.chainId}`]:[],...!((c=b?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${b.signInWithSolana.nonce}`]:[],...!((l=b?.signInWithSolana)===null||l===void 0)&&l.requestId?[`Request ID: ${b.signInWithSolana.requestId}`]:[],...!((d=(u=b?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...b.signInWithSolana.resources.map(C=>`- ${C}`)]:[]].join(`
45
- `);let S=await w.signMessage(new TextEncoder().encode(m),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=S}}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:m,signature:At(g)},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:Ve});if(p)throw p;if(!y||!y.session||!y.user){let _=new Rt;return this._returnResult({data:{user:null,session:null},error:_})}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(x(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){let r=await Yt(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new ys;let{data:s,error:o}=await O(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Ve});if(await be(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!s||!s.session||!s.user){let a=new Rt;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:i??null}),error:o})}catch(s){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:n,token:i,access_token:s,nonce:o}=e,a=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:Ve}),{data:c,error:l}=a;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let u=new Rt;return this._returnResult({data:{user:null,session:null},error:u})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,s,o;try{if("email"in e){let{email:a,options:c}=e,l=null,u=null;this.flowType==="pkce"&&([l,u]=await gr(this.storage,this.storageKey));let{error:d}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=c?.data)!==null&&r!==void 0?r:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:c}=e,{data:l,error:u}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:u})}throw new dr("You must provide either an email or phone number.")}catch(a){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let i,s;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,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:i,xform:Ve});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(x(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,s,o;try{let a=null,c=null;this.flowType==="pkce"&&([a,c]=await gr(this.storage,this.storageKey));let l=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:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:c}),headers:this.headers,xform:Lu});return!((s=l.data)===null||s===void 0)&&s.url&&he()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(a){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new Se;let{error:i}=await O(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(x(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:i,options:s}=e,{error:o}=await O(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:i,options:s}=e,{data:o,error:a}=await O(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new dr("You must provide either an email or phone number and a type")}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await Yt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<ps:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await Yt(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=xs()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Du(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:i},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:wt}):await this._useSession(async r=>{var n,i,s;let{data:o,error:a}=r;if(a)throw a;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Se}:await O(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:wt})})}catch(r){if(x(r))return _s(r)&&(await this._removeSession(),await be(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{let{data:i,error:s}=n;if(s)throw s;if(!i.session)throw new Se;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await gr(this.storage,this.storageKey));let{data:l,error:u}=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:c}),jwt:o.access_token,xform:wt});if(u)throw u;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Se;let r=Date.now()/1e3,n=r,i=!0,s=null,{payload:o}=ci(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){let{data:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!a)return{data:{user:null,session:null},error:null};s=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(x(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!e?.refresh_token)throw new Se;let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!he())throw new hr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new hr(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 si("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new hr("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 si("No code detected.");let{data:_,error:b}=await this._exchangeCodeForSession(e.code);if(b)throw b;let w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:_.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:a,expires_at:c,token_type:l}=e;if(!s||!a||!o||!l)throw new hr("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),h=u+d;c&&(h=parseInt(c));let f=h-u;f*1e3<=ur&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${d}s`);let m=h-d;u-m>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",m,h,u):u-m<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",m,h,u);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:n,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:h,refresh_token:o,token_type:l,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(n){if(x(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let r=await Yt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s&&!_s(s))return this._returnResult({error:s});let o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(_u(a)&&(a.status===404||a.status===401||a.status===403)||_s(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await be(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Eu(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{let{data:{session:s},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await gr(this.storage,this.storageKey,!0));try{return await O(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:n,error:i}=await this._useSession(async s=>{var o,a,c,l,u;let{data:d,error:h}=s;if(h)throw h;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await O(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return he()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if(x(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:i,data:{session:s}}=r;if(i)throw i;let{options:o,provider:a,token:c,access_token:l,nonce:u}=e,d=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=s?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:c,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:Ve}),{data:h,error:f}=d;return f?this._returnResult({data:{user:null,session:null},error:f}):!h||!h.session||!h.user?this._returnResult({data:{user:null,session:null},error:new Rt}):(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:f}))}catch(i){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)throw o;return await O(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let n=Date.now();return await Cu(async i=>(i>0&&await Pu(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await O(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ve})),(i,s)=>{let o=200*Math.pow(2,i);return s&&bs(s)&&Date.now()+o-n<ur})}catch(n){if(this._debug(r,"error",n),x(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),he()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let i=await Yt(this.storage,this.storageKey);if(i&&this.userStorage){let o=await Yt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await pr(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o?.user)!==null&&e!==void 0?e:xs()}else if(i&&!i.user&&!i.user){let o=await Yt(this.storage,this.storageKey+"-user");o&&o?.user?(i.user=o.user,await be(this.storage,this.storageKey+"-user"),await pr(this.storage,this.storageKey,i)):i.user=xs()}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}let s=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<ps;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${ps}s`),s){if(this.autoRefreshToken&&i.refresh_token){let{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),bs(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(i.access_token);!a&&o?.user?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new Se;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new ai;let{data:s,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!s.session)throw new Se;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(i,"error",s),x(s)){let o={data:null,error:s};return bs(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,r,n=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(c){s.push(c)}});if(await Promise.all(o),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await be(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await pr(this.userStorage,this.storageKey+"-user",{user:r.user});let i=Object.assign({},r);delete i.user;let s=Wa(i);await pr(this.storage,this.storageKey,s)}else{let i=Wa(r);await pr(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await be(this.storage,this.storageKey),await be(this.storage,this.storageKey+"-code-verifier"),await be(this.storage,this.storageKey+"-user"),this.userStorage&&await be(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&he()&&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(),ur);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((n.expires_at*1e3-e)/ur);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${ur}ms, refresh threshold is ${ms} ticks`),i<=ms&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof sn)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!he()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){let i=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[s,o]=await gr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(n?.queryParams){let s=new URLSearchParams(n.queryParams);i.push(s.toString())}return n?.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:i,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:(n=i?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:l}=await O(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(e.factorType==="totp"&&c.type==="totp"&&(!((i=c?.totp)===null||i===void 0)&&i.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Ku(e.webauthn.credential_response):Gu(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:c}=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(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:c}))})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Wu(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:zu(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};let i={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])i.all.push(s),s.status==="verified"&&i[s.factor_type].push(s);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,s;if(e)try{let{payload:f}=ci(e),m=null;f.aal&&(m=f.aal);let g=m,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((n=(r=y?.factors)===null||r===void 0?void 0:r.filter(w=>w.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(g="aal2");let b=f.amr||[];return{data:{currentLevel:m,nextLevel:g,currentAuthenticationMethods:b},error:null}}catch(f){if(x(f))return this._returnResult({data:null,error:f});throw f}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=ci(o.access_token),l=null;c.aal&&(l=c.aal);let u=l;((s=(i=o.user.factors)===null||i===void 0?void 0:i.filter(f=>f.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(u="aal2");let h=c.amr||[];return{data:{currentLevel:l,nextLevel:u,currentAuthenticationMethods:h},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await O(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Se})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new Se});let o=await O(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&he()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(x(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new Se});let o=await O(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&he()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(x(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await O(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Se})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await O(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Se})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let i=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+yu>i)return n;let{data:s,error:o}=await O(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=i,n=s.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:f,error:m}=await this.getSession();if(m||!f.session)return this._returnResult({data:null,error:m});n=f.session.access_token}let{header:i,payload:s,signature:o,raw:{header:a,payload:c}}=ci(n);r?.allowExpired||Ru(s.exp);let l=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!l){let{error:f}=await this.getUser(n);if(f)throw f;return{data:{claims:s,header:i,signature:o},error:null}}let u=Au(i.alg),d=await crypto.subtle.importKey("jwk",l,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,xu(`${a}.${c}`)))throw new fr("Invalid JWT signature");return{data:{claims:s,header:i,signature:o},error:null}}catch(n){if(x(n))return this._returnResult({data:null,error:n});throw n}}};Os.nextInstanceID={};var tc=Os;var uy=tc,rc=uy;var dy="2.100.1",ui="";typeof Deno<"u"?ui="deno":typeof document<"u"?ui="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ui="react-native":ui="node";var hy={"X-Client-Info":`supabase-js-${ui}/${dy}`},fy={headers:hy},my={schema:"public"},py={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},gy={};function di(t){"@babel/helpers - typeof";return di=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},di(t)}function yy(t,e){if(di(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(di(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function _y(t){var e=yy(t,"string");return di(e)=="symbol"?e:e+""}function by(t,e,r){return(e=_y(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Yu(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function ie(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Yu(Object(r),!0).forEach(function(n){by(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Yu(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var wy=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),vy=()=>Headers,Sy=(t,e,r)=>{let n=wy(r),i=vy();return async(s,o)=>{var a;let c=(a=await e())!==null&&a!==void 0?a:t,l=new i(o?.headers);return l.has("apikey")||l.set("apikey",t),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),n(s,ie(ie({},o),{},{headers:l}))}};function xy(t){return t.endsWith("/")?t:t+"/"}function ky(t,e){var r,n;let{db:i,auth:s,realtime:o,global:a}=t,{db:c,auth:l,realtime:u,global:d}=e,h={db:ie(ie({},c),i),auth:ie(ie({},l),s),realtime:ie(ie({},u),o),storage:{},global:ie(ie(ie({},d),a),{},{headers:ie(ie({},(r=d?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?h.accessToken=t.accessToken:delete h.accessToken,h}function Ey(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(xy(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Ty=class extends rc{constructor(t){super(t)}},Oy=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;let s=Ey(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 o=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:my,realtime:gy,auth:ie(ie({},py),{},{storageKey:o}),global:fy},c=ky(r??{},a);if(this.storageKey=(n=c.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=c.global.headers)!==null&&i!==void 0?i:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var l;this.auth=this._initSupabaseAuthClient((l=c.auth)!==null&&l!==void 0?l:{},this.headers,c.global.fetch)}this.fetch=Sy(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(ie({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new Jl(new URL("rest/v1",s).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new hu(this.storageUrl.href,this.headers,this.fetch,r?.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new Hn(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:s,flowType:o,lock:a,debug:c,throwOnError:l},u,d){let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ty({url:this.authUrl.href,headers:ie(ie({},h),u),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:a,debug:c,throwOnError:l,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new en(this.realtimeUrl.href,ie(ie({},t),{},{params:ie(ie({},{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)}},Xu=(t,e,r)=>new Oy(t,e,r);function Py(){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}Py()&&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 Zu=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var an=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}},hi=class extends an{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},cn=class extends an{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},ln=class extends an{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},fi;(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"})(fi||(fi={}));var mi=class{constructor(e,{headers:r={},customFetch:n,region:i=fi.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=Zu(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Qi(this,arguments,void 0,function*(r,n={}){var i;let s,o;try{let{headers:a,method:c,body:l,signal:u,timeout:d}=n,h={},{region:f}=n;f||(f=this.region);let m=new URL(`${this.url}/${r}`);f&&f!=="any"&&(h["x-region"]=f,m.searchParams.set("forceFunctionRegion",f));let g;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",g=l):typeof l=="string"?(h["Content-Type"]="text/plain",g=l):typeof FormData<"u"&&l instanceof FormData?g=l:(h["Content-Type"]="application/json",g=JSON.stringify(l)):l&&typeof l!="string"&&!(typeof Blob<"u"&&l instanceof Blob)&&!(l instanceof ArrayBuffer)&&!(typeof FormData<"u"&&l instanceof FormData)?g=JSON.stringify(l):g=l;let y=u;d&&(o=new AbortController,s=setTimeout(()=>o.abort(),d),u?(y=o.signal,u.addEventListener("abort",()=>o.abort())):y=o.signal);let p=yield this.fetch(m.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),a),body:g,signal:y}).catch(D=>{throw new hi(D)}),_=p.headers.get("x-relay-error");if(_&&_==="true")throw new cn(p);if(!p.ok)throw new ln(p);let b=((i=p.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),w;return b==="application/json"?w=yield p.json():b==="application/octet-stream"||b==="application/pdf"?w=yield p.blob():b==="text/event-stream"?w=p:b==="multipart/form-data"?w=yield p.formData():w=yield p.text(),{data:w,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof ln||a instanceof cn?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var td=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Cy=class{constructor(t){var e,r,n;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let n=this.fetch,i=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let o=null,a=null,c=null,l=s.status,u=s.statusText;if(s.ok){var d,h;if(r.method!=="HEAD"){var f;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let m=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(h=s.headers.get("content-range"))===null||h===void 0?void 0:h.split("/");m&&g&&g.length>1&&(c=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,c=null,l=406,u="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let m=await s.text();try{o=JSON.parse(m),Array.isArray(o)&&s.status===404&&(a=[],o=null,l=200,u="OK")}catch{s.status===404&&m===""?(l=204,u="No Content"):o={message:m}}if(o&&r.shouldThrowOnError)throw new td(o)}return{error:o,data:a,count:c,status:l,statusText:u}});return this.shouldThrowOnError||(i=i.catch(s=>{var o;let a="",c="",l="",u=s?.cause;if(u){var d,h,f,m;let p=(d=u?.message)!==null&&d!==void 0?d:"",_=(h=u?.code)!==null&&h!==void 0?h:"";a=`${(f=s?.name)!==null&&f!==void 0?f:"FetchError"}: ${s?.message}`,a+=`
46
-
47
- Caused by: ${(m=u?.name)!==null&&m!==void 0?m:"Error"}: ${p}`,_&&(a+=` (${_})`),u?.stack&&(a+=`
48
- ${u.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"?(l="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. 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.`)):(u?.name==="HeadersOverflowError"||u?.code==="UND_ERR_HEADERS_OVERFLOW")&&(l="",c="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(c+=`. 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:`${(o=s?.name)!==null&&o!==void 0?o:"FetchError"}: ${s?.message}`,details:a,hint:c,code:l},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}returns(){return this}overrideTypes(){return this}},Iy=class extends Cy{select(t){let e=!1,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:i=n}={}){let s=i?`${i}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let i=typeof n>"u"?"offset":`${n}.offset`,s=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${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:n=!1,wal:i=!1,format:s="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${c}"; 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}},Qu=new RegExp("[,()]"),un=class extends Iy{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Qu.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Qu.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}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 n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Ry=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:i=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:n}=e??{},i=r?"HEAD":"GET",s=!1,o=(t??"*").split("").map(l=>/\s/.test(l)&&!s?"":(l==='"'&&(s=!s),l)).join(""),{url:a,headers:c}=this.cloneRequestState();return a.searchParams.set("select",o),n&&c.append("Prefer",`count=${n}`),new un({method:i,url:a,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;let i="POST",{url:s,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((c,l)=>c.concat(Object.keys(l)),[]);if(a.length>0){let c=[...new Set(a)].map(l=>`"${l}"`);s.searchParams.set("columns",c.join(","))}}return new un({method:i,url:s,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){var s;let o="POST",{url:a,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&c.append("Prefer",`count=${n}`),i||c.append("Prefer","missing=default"),Array.isArray(t)){let l=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(l.length>0){let u=[...new Set(l)].map(d=>`"${d}"`);a.searchParams.set("columns",u.join(","))}}return new un({method:o,url:a,headers:c,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 n="PATCH",{url:i,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new un({method:n,url:i,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:n,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new un({method:r,url:n,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function pi(t){"@babel/helpers - typeof";return pi=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},pi(t)}function Ay(t,e){if(pi(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(pi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Dy(t){var e=Ay(t,"string");return pi(e)=="symbol"?e:e+""}function Ny(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 ed(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Ps(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?ed(Object(r),!0).forEach(function(n){Ny(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):ed(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var rd=class nd{constructor(e,{headers:r={},schema:n,fetch:i,timeout:s,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let a=i??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,l)=>{let u=new AbortController,d=setTimeout(()=>u.abort(),s),h=l?.signal;if(h){if(h.aborted)return clearTimeout(d),a(c,l);let f=()=>{clearTimeout(d),u.abort()};return h.addEventListener("abort",f,{once:!0}),a(c,Ps(Ps({},l),{},{signal:u.signal})).finally(()=>{clearTimeout(d),h.removeEventListener("abort",f)})}return a(c,Ps(Ps({},l),{},{signal:u.signal})).finally(()=>clearTimeout(d))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Ry(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new nd(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:n=!1,get:i=!1,count:s}={}){var o;let a,c=new URL(`${this.url}/rpc/${e}`),l,u=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(u)),d=n&&Object.values(r).some(u);d?(a="POST",l=r):n||i?(a=n?"HEAD":"GET",Object.entries(r).filter(([f,m])=>m!==void 0).map(([f,m])=>[f,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([f,m])=>{c.searchParams.append(f,m)})):(a="POST",l=r);let h=new Headers(this.headers);return d?h.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&h.set("Prefer",`count=${s}`),new un({method:a,url:c,headers:h,schema:this.schemaName,body:l,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var nc=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let n=r.versions;if(n&&n.node){let i=n.node,s=parseInt(i.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:
35
+ Version: ${f}
36
+ Chain ID: ${r}${i?`
37
+ Nonce: ${i}`:""}
38
+ Issued At: ${s.toISOString()}`;if(n&&(p+=`
39
+ Expiration Time: ${n.toISOString()}`),a&&(p+=`
40
+ Not Before: ${a.toISOString()}`),l&&(p+=`
41
+ Request ID: ${l}`),u){let b=`
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
+ - ${_}`}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+=`
46
+
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:
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}}},ic=nc;var id="2.100.1";var sd=`realtime-js/${id}`,od="1.0.0",sc="2.0.0",ad=sc;var cd=1e4;var ld=100;var vt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Cs={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var gi={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var yi=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var i,s;let o=e.topic,a=(i=e.ref)!==null&&i!==void 0?i:"",c=(s=e.join_ref)!==null&&s!==void 0?s:"",l=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(u).length===0?"":JSON.stringify(u);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`userEvent length ${l.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let h=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+a.length+o.length+l.length+d.length,f=new ArrayBuffer(this.HEADER_LENGTH+h),m=new DataView(f),g=0;m.setUint8(g++,this.KINDS.userBroadcastPush),m.setUint8(g++,c.length),m.setUint8(g++,a.length),m.setUint8(g++,o.length),m.setUint8(g++,l.length),m.setUint8(g++,d.length),m.setUint8(g++,r),Array.from(c,p=>m.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>m.setUint8(g++,p.charCodeAt(0))),Array.from(o,p=>m.setUint8(g++,p.charCodeAt(0))),Array.from(l,p=>m.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>m.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(f.byteLength+n.byteLength);return y.set(new Uint8Array(f),0),y.set(new Uint8Array(n),f.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[i,s,o,a,c]=n;return r({join_ref:i,ref:s,topic:o,event:a,payload:c})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),i=new TextDecoder;if(n===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,i)}_decodeUserBroadcast(e,r,n){let i=r.getUint8(1),s=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),c=this.HEADER_LENGTH+4,l=n.decode(e.slice(c,c+i));c=c+i;let u=n.decode(e.slice(c,c+s));c=c+s;let d=n.decode(e.slice(c,c+o));c=c+o;let h=e.slice(c,e.byteLength),f=a===this.JSON_ENCODING?JSON.parse(n.decode(h)):h,m={type:this.BROADCAST_EVENT,event:u,payload:f};return o>0&&(m.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:m}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};var Z;(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"})(Z||(Z={}));var ac=(t,e,r={})=>{var n;let i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((s,o)=>(s[o]=Ly(o,t,e,i),s),{}):{}},Ly=(t,e,r,n)=>{let i=e.find(a=>a.name===t),s=i?.type,o=r[t];return s&&!n.includes(s)?ud(s,o):oc(o)},ud=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Uy(e,r)}switch(t){case Z.bool:return jy(e);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return $y(e);case Z.json:case Z.jsonb:return My(e);case Z.timestamp:return Fy(e);case Z.abstime:case Z.date:case Z.daterange:case Z.int4range:case Z.int8range:case Z.money:case Z.reltime:case Z.text:case Z.time:case Z.timestamptz:case Z.timetz:case Z.tsrange:case Z.tstzrange:return oc(e);default:return oc(e)}},oc=t=>t,jy=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},$y=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},My=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Uy=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let s,o=t.slice(1,r);try{s=JSON.parse("["+o+"]")}catch{s=o?o.split(","):[]}return s.map(a=>ud(e,a))}return t},Fy=t=>typeof t=="string"?t.replace(" ","T"):t,Is=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 _i=class t{constructor(e,r){let n=Vy(r);this.presence=new os(e.getChannel(),n),this.presence.onJoin((i,s,o)=>{let a=t.onJoinPayload(i,s,o);e.getChannel().trigger("presence",a)}),this.presence.onLeave((i,s,o)=>{let a=t.onLeavePayload(i,s,o);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=By(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let i=e[n];return r[n]=Rs(i),r},{})}static onJoinPayload(e,r,n){let i=dd(r),s=Rs(n);return{event:"join",key:e,currentPresences:i,newPresences:s}}static onLeavePayload(e,r,n){let i=dd(r),s=Rs(n);return{event:"leave",key:e,currentPresences:i,leftPresences:s}}};function Rs(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function By(t){return JSON.parse(JSON.stringify(t))}function Vy(t){return t?.events&&{events:t.events}}function dd(t){return t?.metas?Rs(t):[]}var cc;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(cc||(cc={}));var dn=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new _i(this.channel.channelAdapter,r)}};var bi=class{constructor(e,r,n){let i=Hy(n);this.channel=e.getSocket().channel(r,i),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,n){let i;try{i=this.channel.push(e,r,n)}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 i}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===vt.joined}isJoined(){return this.state===vt.joined}isJoining(){return this.state===vt.joining}isClosed(){return this.state===vt.closed}isLeaving(){return this.state===vt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function Hy(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var lc;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(lc||(lc={}));var hn;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(hn||(hn={}));var St;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(St||(St={}));var fn=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:{}},n){var i,s;if(this.topic=e,this.params=r,this.socket=n,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 bi(this.socket.socketAdapter,e,this.params),this.presence=new dn(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Is(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(i=this.params.config)===null||i===void 0?void 0:i.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 n,i,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:o,presence:a,private:c}}=this.params,l=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(f=>f.filter))!==null&&i!==void 0?i:[],u=!!this.bindings[hn.PRESENCE]&&this.bindings[hn.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},h={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:l,private:c};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(f=>{e?.(St.CHANNEL_ERROR,f)}),this._onClose(()=>e?.(St.CLOSED)),this.updateJoinPayload(Object.assign({config:h},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:f})=>{if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e?.(St.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",f=>{this.state=vt.errored,e?.(St.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e?.(St.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var n;let i=this.bindings.postgres_changes,s=(n=i?.length)!==null&&n!==void 0?n:0,o=[];for(let a=0;a<s;a++){let c=i[a],{filter:{event:l,schema:u,table:d,filter:h}}=c,f=e&&e[a];if(f&&f.event===l&&t.isFilterValueEqual(f.schema,u)&&t.isFilterValueEqual(f.table,d)&&t.isFilterValueEqual(f.filter,h))o.push(Object.assign(Object.assign({},c),{id:f.id}));else{this.unsubscribe(),this.state=vt.errored,r?.(St.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=vt.errored&&r&&r(St.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,n){if(this.channelAdapter.isJoined()&&e===hn.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,n)}async httpSend(e,r,n={}){var i;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 o={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(i=n.timeout)!==null&&i!==void 0?i:this.timeout);if(a.status===202)return{success:!0};let c=a.statusText;try{let l=await a.json();c=l.error||l.message||c}catch{}return Promise.reject(new Error(c))}async send(e,r={}){var n,i;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:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let c={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o,private:this.private}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,a,c;let l=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&s("ok"),l.receive("ok",()=>s("ok")),l.receive("error",()=>s("error")),l.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,n){let i=new AbortController,s=setTimeout(()=>i.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(s),o}_on(e,r,n){let i=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,n),o={type:i,filter:r,callback:n,ref:s};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var i,s,o,a,c,l,u;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,n))return!1;let h=(i=this.bindings[d])===null||i===void 0?void 0:i.find(f=>f.ref===e.ref);if(!h)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in h){let f=h.id,m=(s=h.filter)===null||s===void 0?void 0:s.event;return f&&((o=r.ids)===null||o===void 0?void 0:o.includes(f))&&(m==="*"||m?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let f=(l=(c=h?.filter)===null||c===void 0?void 0:c.event)===null||l===void 0?void 0:l.toLocaleLowerCase();return f==="*"||f===((u=r?.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return h.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:n,error:i,leave:s,join:o}=Cs;return r&&[n,i,s,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){let i=r.data,{schema:s,table:o,commit_timestamp:a,type:c,errors:l}=i;return Object.assign(Object.assign({},{schema:s,table:o,commit_timestamp:a,eventType:c,new:{},old:{},errors:l}),this._getPayloadRecords(i))}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=ac(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=ac(e.columns,e.old_record)),r}};var wi=class{constructor(e,r){this.socket=new as(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,n,i=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),i),this.socket.disconnect(()=>{e(),s("ok")},r,n)})}push(e){this.socket.push(e)}log(e,r,n){this.socket.log(e,r,n)}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()==gi.connecting}isDisconnecting(){return this.socket.connectionState()==gi.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var Wy={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},zy=[1e3,2e3,5e3,1e4],Ky=1e4,Gy=`
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_=`
53
53
  addEventListener("message", (e) => {
54
54
  if (e.data.event === "start") {
55
55
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
56
56
  }
57
- });`,mn=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var n;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new yi,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...o)=>s(...o):(...o)=>fetch(...o),!(!((n=r?.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let i=this._initializeOptions(r);this.socketAdapter=new wi(e,i),this.httpEndpoint=Is(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let r=e.message;throw r.includes("Node.js")?new Error(`${r}
57
+ });`,No=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var o;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new Gn,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((o=r?.params)===null||o===void 0)&&o.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let n=this._initializeOptions(r);this.socketAdapter=new Yn(e,n),this.httpEndpoint=ci(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let r=e.message;throw r.includes("Node.js")?new Error(`${r}
58
58
 
59
59
  To use Realtime in Node.js, you need to provide a WebSocket implementation:
60
60
 
@@ -67,29 +67,29 @@ 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 n=>{let i=await n.unsubscribe();return n.teardown(),i}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,n){this.socketAdapter.log(e,r,n)}connectionState(){return this.socketAdapter.connectionState()||gi.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let n=`realtime:${e}`,i=this.getChannels().find(s=>s.topic===n);if(i)return i;{let s=new fn(`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,n=!1;if(e)r=e,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue}else r=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{let s={access_token:r,version:sd};r&&i.updateJoinPayload(s),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(Cs.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,n)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,n)}}_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 n=new Blob([Gy],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_initializeOptions(e){var r,n,i,s,o,a,c,l,u;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(n=e?.accessToken)!==null&&n!==void 0?n:null;let d={};d.timeout=(i=e?.timeout)!==null&&i!==void 0?i:cd,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Wy.HEARTBEAT_INTERVAL,d.transport=(o=e?.transport)!==null&&o!==void 0?o:ic.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]||Ky);let h,f,m=(c=e?.vsn)!==null&&c!==void 0?c:ad;switch(m){case od:h=(g,y)=>y(JSON.stringify(g)),f=(g,y)=>y(JSON.parse(g));break;case sc:h=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=m,d.encode=(l=e?.encode)!==null&&l!==void 0?l:h,d.decode=(u=e?.decode)!==null&&u!==void 0?u:f,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 As=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}};function Ds(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var uc=class extends As{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},pd=class extends As{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var Jy=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Yy=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)},dc=t=>{if(Array.isArray(t))return t.map(r=>dc(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let i=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[i]=dc(n)}),e},Xy=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function Si(t){"@babel/helpers - typeof";return Si=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},Si(t)}function Zy(t,e){if(Si(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Si(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Qy(t){var e=Zy(t,"string");return Si(e)=="symbol"?e:e+""}function e_(t,e,r){return(e=Qy(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function hd(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function R(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?hd(Object(r),!0).forEach(function(n){e_(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):hd(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var fd=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)},t_=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let i=t,s=parseInt(i.status,10);Number.isFinite(s)||(s=500),i.json().then(o=>{let a=o?.statusCode||o?.code||s+"";e(new uc(fd(o),s,a,n))}).catch(()=>{let o=s+"";e(new uc(i.statusText||`HTTP ${s} error`,s,o,n))})}else e(new pd(fd(t),t,n))},r_=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!n?R(R({},i),r):(Yy(n)?(i.headers=R({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(n)):i.body=n,e?.duplex&&(i.duplex=e.duplex),R(R({},i),r))};async function vi(t,e,r,n,i,s,o){return new Promise((a,c)=>{t(r,r_(e,n,i,s)).then(l=>{if(!l.ok)throw l;if(n?.noResolveJson)return l;if(o==="vectors"){let u=l.headers.get("content-type");if(l.headers.get("content-length")==="0"||l.status===204)return{};if(!u||!u.includes("application/json"))return{}}return l.json()}).then(l=>a(l)).catch(l=>t_(l,c,n,o))})}function gd(t="storage"){return{get:async(e,r,n,i)=>vi(e,"GET",r,n,i,void 0,t),post:async(e,r,n,i,s)=>vi(e,"POST",r,i,s,n,t),put:async(e,r,n,i,s)=>vi(e,"PUT",r,i,s,n,t),head:async(e,r,n,i)=>vi(e,"HEAD",r,R(R({},n),{},{noResolveJson:!0}),i,void 0,t),remove:async(e,r,n,i,s)=>vi(e,"DELETE",r,i,s,n,t)}}var n_=gd("storage"),{get:xi,post:st,put:hc,head:i_,remove:fc}=n_,Ne=gd("vectors"),pn=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Jy(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=R(R({},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(Ds(r))return{data:null,error:r};throw r}}},s_=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(Ds(e))return{data:null,error:e};throw e}}},yd;yd=Symbol.toStringTag;var o_=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[yd]="BlobDownloadBuilder",this.promise=null}asStream(){return new s_(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(Ds(e))return{data:null,error:e};throw e}}},a_={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},md={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},c_=class extends pn{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var i=this;return i.handleOperation(async()=>{let s,o=R(R({},md),n),a=R(R({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),c=o.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),c&&s.append("metadata",i.encodeMetadata(c)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",o.cacheControl),c&&!s.has("metadata")&&s.append("metadata",i.encodeMetadata(c))):(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,c&&(a["x-metadata"]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=R(R({},a),n.headers));let l=i._removeEmptyFolders(e),u=i._getFinalPath(l),d=await(t=="PUT"?hc:st)(i.fetch,`${i.url}/object/${u}`,s,R({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:l,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var i=this;let s=i._removeEmptyFolders(t),o=i._getFinalPath(s),a=new URL(i.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),i.handleOperation(async()=>{let c,l=R(R({},md),n),u=R(R({},i.headers),{"x-upsert":String(l.upsert)});return typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",l.cacheControl)):(c=r,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType),{path:s,fullPath:(await hc(i.fetch,a.toString(),c,{headers:u})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),i=R({},r.headers);e?.upsert&&(i["x-upsert"]="true");let s=await st(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:i}),o=new URL(r.url+s.url),a=o.searchParams.get("token");if(!a)throw new As("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await st(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await st(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await st(n.fetch,`${n.url}/object/sign/${i}`,R({expiresIn:e},s?{transform:r.transform}:{}),{headers:n.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",c=s&&o.signedURL.includes("/object/sign/")?o.signedURL.replace("/object/sign/","/render/image/sign/"):o.signedURL;return{signedUrl:encodeURI(`${n.url}${c}${a}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let i=await st(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return i.map(o=>R(R({},o),{},{signedUrl:o.signedURL?encodeURI(`${n.url}${o.signedURL}${s}`):null}))})}download(t,e,r){let n=typeof e?.transform<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString(e?.transform||{}),s=i?`?${i}`:"",o=this._getFinalPath(t),a=()=>xi(this.fetch,`${this.url}/${n}/${o}${s}`,{headers:this.headers,noResolveJson:!0},r);return new o_(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>dc(await xi(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await i_(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(Ds(i)){var n;let s=i instanceof uc?i.status:i instanceof pd?(n=i.originalError)===null||n===void 0?void 0:n.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:i}}throw i}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=[],i=e?.download?`download=${e.download===!0?"":e.download}`:"";i!==""&&n.push(i);let s=typeof e?.transform<"u"?"render/image":"object",o=this.transformOptsToQueryString(e?.transform||{});o!==""&&n.push(o);let a=n.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await fc(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let i=R(R(R({},a_),e),{},{prefix:t||""});return await st(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=R({},t);return await st(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},l_="2.100.1",ki={"X-Client-Info":`storage-js/${l_}`},u_=class extends pn{constructor(t,e={},r,n){let i=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));let s=i.href.replace(/\/$/,""),o=R(R({},ki),e);super(s,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await xi(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await xi(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await st(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 hc(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 st(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await fc(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():""}},d_=class extends pn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=R(R({},ki),e);super(n,i,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await st(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),i=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await xi(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await fc(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Xy(t))throw new As("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 us({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,s){let o=i[s];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(i,a),error:null}}catch(c){if(n)throw c;return{data:null,error:c}}}}})}},h_=class extends pn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=R(R({},ki),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ne.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ne.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},f_=class extends pn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=R(R({},ki),{},{"Content-Type":"application/json"},e);super(n,i,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 Ne.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ne.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 Ne.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ne.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 Ne.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},m_=class extends pn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=R(R({},ki),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},p_=class extends m_{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new g_(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)}},g_=class extends h_{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,R(R({},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 y_(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},y_=class extends f_{constructor(t,e,r,n,i){super(t,e,i),this.vectorBucketName=r,this.indexName=n}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},_d=class extends u_{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new c_(this.url,this.headers,t,this.fetch)}get vectors(){return new p_(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new d_(this.url+"/iceberg",this.headers,this.fetch)}};var Ns="2.100.1";var vr=30*1e3,Ls=3,js=Ls*vr,bd="http://localhost:9999",wd="supabase.auth.token";var vd={"X-Client-Info":`gotrue-js/${Ns}`};var Ei="X-Supabase-Api-Version",mc={"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 Xt=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}};function k(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var $s=class extends Xt{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}};function kd(t){return k(t)&&t.name==="AuthApiError"}var He=class extends Xt{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},ot=class extends Xt{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}},xe=class extends ot{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function Us(t){return k(t)&&t.name==="AuthSessionMissingError"}var Dt=class extends ot{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Sr=class extends ot{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},xr=class extends ot{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 Ed(t){return k(t)&&t.name==="AuthImplicitGrantRedirectError"}var Ti=class extends ot{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}}},Ms=class extends ot{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 gn=class extends ot{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function Fs(t){return k(t)&&t.name==="AuthRetryableFetchError"}var Oi=class extends ot{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}};var kr=class extends ot{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var qs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Td=`
71
- \r=`.split(""),__=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Td.length;e+=1)t[Td[e].charCodeAt(0)]=-2;for(let e=0;e<qs.length;e+=1)t[qs[e].charCodeAt(0)]=e;return t})();function Od(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(qs[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(qs[n]),e.queuedBits-=6}}function Pd(t,e,r){let n=__[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function pc(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=o=>{v_(o,n,r)};for(let o=0;o<t.length;o+=1)Pd(t.charCodeAt(o),i,s);return e.join("")}function b_(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 w_(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}b_(n,e)}}function v_(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function Zt(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;i<t.length;i+=1)Pd(t.charCodeAt(i),r,n);return new Uint8Array(e)}function Cd(t){let e=[];return w_(t,r=>e.push(r)),new Uint8Array(e)}function Nt(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};return t.forEach(i=>Od(i,r,n)),Od(null,r,n),e.join("")}function Id(t){return Math.round(Date.now()/1e3)+t}function Rd(){return Symbol("auth-callback")}var fe=()=>typeof window<"u"&&typeof document<"u",Er={tested:!1,writable:!1},Bs=()=>{if(!fe())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Er.tested)return Er.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Er.tested=!0,Er.writable=!0}catch{Er.tested=!0,Er.writable=!1}return Er.writable};function Ad(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,s)=>{e[s]=i})}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n}),e}var Vs=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",Tr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},Qt=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},we=async(t,e)=>{await t.removeItem(e)},Pi=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};Pi.promiseConstructor=Promise;function Ci(t){let e=t.split(".");if(e.length!==3)throw new kr("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!Sd.test(e[n]))throw new kr("JWT not in base64url format");return{header:JSON.parse(pc(e[0])),payload:JSON.parse(pc(e[1])),signature:Zt(e[2]),raw:{header:e[0],payload:e[1]}}}async function Nd(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Ld(t,e){return new Promise((n,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{let o=await t(s);if(!e(s,null,o)){n(o);return}}catch(o){if(!e(s,o)){i(o);return}}})()})}function S_(t){return("0"+t.toString(16)).substr(-2)}function x_(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,i="";for(let s=0;s<56;s++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,S_).join("")}async function k_(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}async function E_(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 k_(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Or(t,e,r=!1){let n=x_(),i=n;r&&(i+="/PASSWORD_RECOVERY"),await Tr(t,`${e}-code-verifier`,i);let s=await E_(n);return[s,n===s?"plain":"s256"]}var T_=/^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(Ei);if(!e||!e.match(T_))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function $d(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 Md(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 O_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Pr(t){if(!O_.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Hs(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Ud(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){let s=n.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,n,i)}return!e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,n,i)}})}function gc(t){return JSON.parse(JSON.stringify(t))}var Cr=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),P_=[502,503,504];async function Fd(t){var e;if(!Dd(t))throw new gn(Cr(t),0);if(P_.includes(t.status))throw new gn(Cr(t),t.status);let r;try{r=await t.json()}catch(s){throw new He(Cr(s),s)}let n,i=jd(t);if(i&&i.getTime()>=mc["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Oi(Cr(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new xe}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,o)=>s&&typeof o=="string",!0))throw new Oi(Cr(r),t.status,r.weak_password.reasons);throw new $s(Cr(r),t.status||500,n)}var C_=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};async function P(t,e,r,n){var i;let s=Object.assign({},n?.headers);s[Ei]||(s[Ei]=mc["2024-01-01"].name),n?.jwt&&(s.Authorization=`Bearer ${n.jwt}`);let o=(i=n?.query)!==null&&i!==void 0?i:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await I_(t,e,r+a,{headers:s,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(c):{data:Object.assign({},c),error:null}}async function I_(t,e,r,n,i,s){let o=C_(e,n,i,s),a;try{a=await t(r,Object.assign({},o))}catch(c){throw console.error(c),new gn(Cr(c),0)}if(a.ok||await Fd(a),n?.noResolveJson)return a;try{return await a.json()}catch(c){await Fd(c)}}function We(t){var e;let r=null;R_(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Id(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function yc(t){let e=We(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function xt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function qd(t){return{data:t,error:null}}function Bd(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s}=t,o=Oe(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function _c(t){return t}function R_(t){return t.access_token&&t.refresh_token&&t.expires_in}var Ws=["global","local","others"];var Ir=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=Vs(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},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=Ws[0]){if(Ws.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ws.join(", ")}`);try{return await P(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(k(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await P(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:xt})}catch(n){if(k(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=Oe(e,["options"]),i=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(i.new_email=n?.newEmail,delete i.newEmail),await P(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Bd,redirectTo:r?.redirectTo})}catch(r){if(k(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await P(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:xt})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,s,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await P(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:_c});if(u.error)throw u.error;let d=await u.json(),h=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(m=>{let g=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(m.split(";")[1].split("=")[1]);l[`${y}Page`]=g}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(k(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){Pr(e);try{return await P(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:xt})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Pr(e);try{return await P(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:xt})}catch(n){if(k(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){Pr(e);try{return await P(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:xt})}catch(n){if(k(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){Pr(e.userId);try{let{data:r,error:n}=await P(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:r,error:n}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Pr(e.userId),Pr(e.id);try{return{data:await P(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,n,i,s,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await P(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:_c});if(u.error)throw u.error;let d=await u.json(),h=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(m=>{let g=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(m.split(";")[1].split("=")[1]);l[`${y}Page`]=g}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(k(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await P(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 P(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 P(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(k(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await P(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 P(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 P(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:n=>{var i;return{data:{providers:(i=n?.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(k(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await P(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 P(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 P(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(k(n))return{data:null,error:n};throw n}}async _deleteCustomProvider(e){try{return await P(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 bc(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var at={debug:!!(globalThis&&Bs()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ii=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Ri=class extends Ii{};async function wc(t,e,r){at.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController,i;e>0&&(i=setTimeout(()=>{n.abort(),at.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){clearTimeout(i),at.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{at.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw at.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Ri(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(at.debug)try{let o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "))}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o)}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(i),await r()}})}catch(s){if(e>0&&clearTimeout(i),s?.name==="AbortError"&&e>0){if(n.signal.aborted)return at.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 o=>{if(o){at.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,o.name);try{return await r()}finally{at.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,o.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw at.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Ri(`Lock "${t}" was released because another request stole it`)}throw s}}function Vd(){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 vc(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 Wd(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function zd(t){var e;let{chainId:r,domain:n,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:c,resources:l,scheme:u,uri:d,version:h}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(h!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);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 f=vc(t.address),m=u?`${u}://${n}`:n,g=t.statement?`${t.statement}
73
- `:"",y=`${m} wants you to sign in with your Ethereum account:
74
- ${f}
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=iu(t.address),h=c?`${c}://${o}`:o,g=t.statement?`${t.statement}
73
+ `:"",y=`${h} wants you to sign in with your Ethereum account:
74
+ ${m}
75
75
 
76
76
  ${g}`,p=`URI: ${d}
77
- Version: ${h}
78
- Chain ID: ${r}${o?`
79
- Nonce: ${o}`:""}
80
- Issued At: ${s.toISOString()}`;if(i&&(p+=`
81
- Expiration Time: ${i.toISOString()}`),a&&(p+=`
82
- Not Before: ${a.toISOString()}`),c&&(p+=`
83
- Request ID: ${c}`),l){let _=`
84
- Resources:`;for(let b of l){if(!b||typeof b!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);_+=`
85
- - ${b}`}p+=_}return`${y}
86
- ${p}`}var re=class extends Error{constructor({message:e,code:r,cause:n,name:i}){var s;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(s=i??(n instanceof Error?n.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},Rr=class extends re{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,n,i;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 re({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 re({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new re({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=s.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new re({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 re({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new re({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 re({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new re({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Sc(o)){if(s.rp.id!==o)return new re({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new re({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 re({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 re({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 re({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 re({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new re({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if(Sc(n)){if(r.rpId!==n)return new re({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new re({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new re({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 re({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var xc=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}}},A_=new xc;function Yd(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:n}=t,i=Oe(t,["challenge","user","excludeCredentials"]),s=Zt(e).buffer,o=Object.assign(Object.assign({},r),{id:Zt(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:s,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let c=0;c<n.length;c++){let l=n[c];a.excludeCredentials[c]=Object.assign(Object.assign({},l),{id:Zt(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return a}function Xd(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,n=Oe(t,["challenge","allowCredentials"]),i=Zt(e).buffer,s=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];s.allowCredentials[o]=Object.assign(Object.assign({},a),{id:Zt(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:Nt(new Uint8Array(t.response.attestationObject)),clientDataJSON:Nt(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,n=t.getClientExtensionResults(),i=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Nt(new Uint8Array(i.authenticatorData)),clientDataJSON:Nt(new Uint8Array(i.clientDataJSON)),signature:Nt(new Uint8Array(i.signature)),userHandle:i.userHandle?Nt(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Sc(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Jd(){var t,e;return!!(fe()&&"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 D_(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Rr("Browser returned unexpected credential type",e)}:{data:null,error:new Rr("Empty credential response",e)}}catch(e){return{data:null,error:Kd({error:e,options:t})}}}async function N_(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Rr("Browser returned unexpected credential type",e)}:{data:null,error:new Rr("Empty credential response",e)}}catch(e){return{data:null,error:Gd({error:e,options:t})}}}var L_={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},j_={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function zs(...t){let e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(let i of t)if(i)for(let s in i){let o=i[s];if(o!==void 0)if(Array.isArray(o))n[s]=o;else if(r(o))n[s]=o;else if(e(o)){let a=n[s];e(a)?n[s]=zs(a,o):n[s]=zs(o)}else n[s]=o}return n}function $_(t,e){return zs(L_,t,e||{})}function M_(t,e){return zs(j_,t,e||{})}var Ks=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:i},s){var o;try{let{data:a,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:c};let l=i??A_.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let d=n;if(d)u.name=`${u.id}:${d}`;else{let f=(await this.client.getUser()).data.user,m=((o=f?.user_metadata)===null||o===void 0?void 0:o.name)||f?.email||f?.id||"User";u.name=`${u.id}:${m}`}}u.displayName||(u.displayName=u.name)}switch(a.webauthn.type){case"create":{let u=$_(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:h}=await D_({publicKey:u,signal:l});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:h}}case"request":{let u=M_(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:h}=await N_(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:l}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:h}}}}catch(a){return k(a)?{data:null,error:a}:{data:null,error:new He("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return{data:null,error:new Xt("rpId is required for WebAuthn authentication")};try{if(!Jd())return{data:null,error:new He("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:s});if(!o)return{data:null,error:a};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:n,credential_response:c.credential_response}})}catch(o){return k(o)?{data:null,error:o}:{data:null,error:new He("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return{data:null,error:new Xt("rpId is required for WebAuthn registration")};try{if(!Jd())return{data:null,error:new He("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return(d=u.data)===null||d===void 0?void 0:d.all.find(h=>h.factor_type==="webauthn"&&h.friendly_name===e&&h.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};let{data:c,error:l}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:s});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:n,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:l}}catch(o){return k(o)?{data:null,error:o}:{data:null,error:new He("Unexpected error in register",o)}}}};Vd();var U_={url:bd,storageKey:wd,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:vd,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function eh(t,e,r){return await r()}var yn={},Gs=class t{get jwks(){var e,r;return(r=(e=yn[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){yn[this.storageKey]=Object.assign(Object.assign({},yn[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=yn[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){yn[this.storageKey]=Object.assign(Object.assign({},yn[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,i;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({},U_),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&&fe()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Ir({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Vs(s.fetch),this.lock=s.lock||eh,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&&fe()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=wc:this.lock=eh,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 Ks(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:Bs()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=bc(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=bc(this.memoryStorage)),fe()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ns}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if(fe()&&(r=Ad(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),fe()&&this.detectSessionInUrl&&n!=="none"){let{data:i,error:s}=await this._getSessionFromURL(r,n);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),Ed(s)){let c=(e=s.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:s}}return{error:s}}let{session:o,redirectType:a}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return k(r)?this._returnResult({error:r}):this._returnResult({error:new He("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{let s=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:We}),{data:o,error:a}=s;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(s){if(k(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,n,i;try{let s;if("email"in e){let{email:u,password:d,options:h}=e,f=null,m=null;this.flowType==="pkce"&&([f,m]=await Or(this.storage,this.storageKey)),s=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h?.emailRedirectTo,body:{email:u,password:d,data:(r=h?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:h?.captchaToken},code_challenge:f,code_challenge_method:m},xform:We})}else if("phone"in e){let{phone:u,password:d,options:h}=e;s=await P(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(n=h?.data)!==null&&n!==void 0?n:{},channel:(i=h?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:We})}else throw new Sr("You must provide either an email or phone number and a password");let{data:o,error:a}=s;if(a||!o)return await we(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(s){if(await we(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:o,options:a}=e;r=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:yc})}else if("phone"in e){let{phone:s,password:o,options:a}=e;r=await P(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:yc})}else throw new Sr("You must provide either an email or phone number and a password");let{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){let s=new Dt;return this._returnResult({data:{user:null,session:null},error:s})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.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,n,i,s,o,a,c,l,u,d,h;let f,m;if("message"in e)f=e.message,m=e.signature;else{let{chain:g,wallet:y,statement:p,options:_}=e,b;if(fe())if(typeof y=="object")b=y;else{let M=window;if("ethereum"in M&&typeof M.ethereum=="object"&&"request"in M.ethereum&&typeof M.ethereum.request=="function")b=M.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"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=y}let w=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href),D=await b.request({method:"eth_requestAccounts"}).then(M=>M).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!D||D.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let S=vc(D[0]),C=(n=_?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!C){let M=await b.request({method:"eth_chainId"});C=Hd(M)}let K={domain:w.host,address:S,statement:p,uri:w.href,version:"1",chainId:C,nonce:(i=_?.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(s=_?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=_?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(c=_?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(l=_?.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(u=_?.signInWithEthereum)===null||u===void 0?void 0:u.resources};f=zd(K),m=await b.request({method:"personal_sign",params:[Wd(f),S]})}try{let{data:g,error:y}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:m},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:We});if(y)throw y;if(!g||!g.session||!g.user){let p=new Dt;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,n,i,s,o,a,c,l,u,d,h,f;let m,g;if("message"in e)m=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:_,options:b}=e,w;if(fe())if(typeof p=="object")w=p;else{let S=window;if("solana"in S&&typeof S.solana=="object"&&("signIn"in S.solana&&typeof S.solana.signIn=="function"||"signMessage"in S.solana&&typeof S.solana.signMessage=="function"))w=S.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"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=p}let D=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in w&&w.signIn){let S=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},b?.signInWithSolana),{version:"1",domain:D.host,uri:D.href}),_?{statement:_}:null)),C;if(Array.isArray(S)&&S[0]&&typeof S[0]=="object")C=S[0];else if(S&&typeof S=="object"&&"signedMessage"in S&&"signature"in S)C=S;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in C&&"signature"in C&&(typeof C.signedMessage=="string"||C.signedMessage instanceof Uint8Array)&&C.signature instanceof Uint8Array)m=typeof C.signedMessage=="string"?C.signedMessage:new TextDecoder().decode(C.signedMessage),g=C.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in w)||typeof w.signMessage!="function"||!("publicKey"in w)||typeof w!="object"||!w.publicKey||!("toBase58"in w.publicKey)||typeof w.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");m=[`${D.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${D.href}`,`Issued At: ${(i=(n=b?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((s=b?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${b.signInWithSolana.notBefore}`]:[],...!((o=b?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${b.signInWithSolana.expirationTime}`]:[],...!((a=b?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${b.signInWithSolana.chainId}`]:[],...!((c=b?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${b.signInWithSolana.nonce}`]:[],...!((l=b?.signInWithSolana)===null||l===void 0)&&l.requestId?[`Request ID: ${b.signInWithSolana.requestId}`]:[],...!((d=(u=b?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...b.signInWithSolana.resources.map(C=>`- ${C}`)]:[]].join(`
87
- `);let S=await w.signMessage(new TextEncoder().encode(m),"utf8");if(!S||!(S instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=S}}try{let{data:y,error:p}=await P(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:m,signature:Nt(g)},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:We});if(p)throw p;if(!y||!y.session||!y.user){let _=new Dt;return this._returnResult({data:{user:null,session:null},error:_})}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 Qt(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new Ms;let{data:s,error:o}=await P(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:We});if(await we(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!s||!s.session||!s.user){let a=new Dt;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:i??null}),error:o})}catch(s){if(await we(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:n,token:i,access_token:s,nonce:o}=e,a=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:We}),{data:c,error:l}=a;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let u=new Dt;return this._returnResult({data:{user:null,session:null},error:u})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,s,o;try{if("email"in e){let{email:a,options:c}=e,l=null,u=null;this.flowType==="pkce"&&([l,u]=await Or(this.storage,this.storageKey));let{error:d}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=c?.data)!==null&&r!==void 0?r:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:c}=e,{data:l,error:u}=await P(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:u})}throw new Sr("You must provide either an email or phone number.")}catch(a){if(await we(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,n;try{let i,s;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await P(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:We});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(k(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,s,o;try{let a=null,c=null;this.flowType==="pkce"&&([a,c]=await Or(this.storage,this.storageKey));let l=await P(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:c}),headers:this.headers,xform:qd});return!((s=l.data)===null||s===void 0)&&s.url&&fe()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(a){if(await we(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:n}=e;if(n)throw n;if(!r)throw new xe;let{error:i}=await P(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}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:n,type:i,options:s}=e,{error:o}=await P(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:i,options:s}=e,{data:o,error:a}=await P(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new Sr("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 n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await Qt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<js:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await Qt(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=Hs()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Ud(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:i},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 P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:xt}):await this._useSession(async r=>{var n,i,s;let{data:o,error:a}=r;if(a)throw a;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new xe}:await P(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:xt})})}catch(r){if(k(r))return Us(r)&&(await this._removeSession(),await we(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{let{data:i,error:s}=n;if(s)throw s;if(!i.session)throw new xe;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await Or(this.storage,this.storageKey));let{data:l,error:u}=await P(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:xt});if(u)throw u;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await we(this.storage,`${this.storageKey}-code-verifier`),k(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new xe;let r=Date.now()/1e3,n=r,i=!0,s=null,{payload:o}=Ci(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){let{data:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!a)return{data:{user:null,session:null},error:null};s=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(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 n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!e?.refresh_token)throw new xe;let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):i?this._returnResult({data:{user:i.user,session:i},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(!fe())throw new xr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new xr(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 Ti("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new xr("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 Ti("No code detected.");let{data:_,error:b}=await this._exchangeCodeForSession(e.code);if(b)throw b;let w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:_.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:a,expires_at:c,token_type:l}=e;if(!s||!a||!o||!l)throw new xr("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),h=u+d;c&&(h=parseInt(c));let f=h-u;f*1e3<=vr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${d}s`);let m=h-d;u-m>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",m,h,u):u-m<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",m,h,u);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:n,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:h,refresh_token:o,token_type:l,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(n){if(k(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let r=await Qt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s&&!Us(s))return this._returnResult({error:s});let o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(kd(a)&&(a.status===404||a.status===401||a.status===403)||Us(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await we(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Rd(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{let{data:{session:s},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await Or(this.storage,this.storageKey,!0));try{return await P(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await we(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:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(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:n,error:i}=await this._useSession(async s=>{var o,a,c,l,u;let{data:d,error:h}=s;if(h)throw h;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await P(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return fe()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if(k(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:i,data:{session:s}}=r;if(i)throw i;let{options:o,provider:a,token:c,access_token:l,nonce:u}=e,d=await P(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=s?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:c,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:We}),{data:h,error:f}=d;return f?this._returnResult({data:{user:null,session:null},error:f}):!h||!h.session||!h.user?this._returnResult({data:{user:null,session:null},error:new Dt}):(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:f}))}catch(i){if(await we(this.storage,`${this.storageKey}-code-verifier`),k(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)throw o;return await P(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i: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 n=Date.now();return await Ld(async i=>(i>0&&await Nd(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await P(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:We})),(i,s)=>{let o=200*Math.pow(2,i);return s&&Fs(s)&&Date.now()+o-n<vr})}catch(n){if(this._debug(r,"error",n),k(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),fe()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let i=await Qt(this.storage,this.storageKey);if(i&&this.userStorage){let o=await Qt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await Tr(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o?.user)!==null&&e!==void 0?e:Hs()}else if(i&&!i.user&&!i.user){let o=await Qt(this.storage,this.storageKey+"-user");o&&o?.user?(i.user=o.user,await we(this.storage,this.storageKey+"-user"),await Tr(this.storage,this.storageKey,i)):i.user=Hs()}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}let s=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<js;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${js}s`),s){if(this.autoRefreshToken&&i.refresh_token){let{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),Fs(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(i.access_token);!a&&o?.user?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new xe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Pi;let{data:s,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!s.session)throw new xe;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(i,"error",s),k(s)){let o={data:null,error:s};return Fs(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,r,n=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(c){s.push(c)}});if(await Promise.all(o),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await we(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await Tr(this.userStorage,this.storageKey+"-user",{user:r.user});let i=Object.assign({},r);delete i.user;let s=gc(i);await Tr(this.storage,this.storageKey,s)}else{let i=gc(r);await Tr(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await we(this.storage,this.storageKey),await we(this.storage,this.storageKey+"-code-verifier"),await we(this.storage,this.storageKey+"-user"),this.userStorage&&await we(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&fe()&&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(),vr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((n.expires_at*1e3-e)/vr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${vr}ms, refresh threshold is ${Ls} ticks`),i<=Ls&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ii)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!fe()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){let i=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[s,o]=await Or(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(n?.queryParams){let s=new URLSearchParams(n.queryParams);i.push(s.toString())}return n?.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;return s?this._returnResult({data:null,error:s}):await P(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.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 n,i;let{data:s,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:l}=await P(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(e.factorType==="totp"&&c.type==="totp"&&(!((i=c?.totp)===null||i===void 0)&&i.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,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 n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=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):Qd(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:c}=await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(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:c}))})}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 n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=await P(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Yd(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:Xd(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:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};let i={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])i.all.push(s),s.status==="verified"&&i[s.factor_type].push(s);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,s;if(e)try{let{payload:f}=Ci(e),m=null;f.aal&&(m=f.aal);let g=m,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((n=(r=y?.factors)===null||r===void 0?void 0:r.filter(w=>w.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(g="aal2");let b=f.amr||[];return{data:{currentLevel:m,nextLevel:g,currentAuthenticationMethods:b},error:null}}catch(f){if(k(f))return this._returnResult({data:null,error:f});throw f}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=Ci(o.access_token),l=null;c.aal&&(l=c.aal);let u=l;((s=(i=o.user.factors)===null||i===void 0?void 0:i.filter(f=>f.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(u="aal2");let h=c.amr||[];return{data:{currentLevel:l,nextLevel:u,currentAuthenticationMethods:h},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await P(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new xe})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new xe});let o=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&fe()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(k(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new xe});let o=await P(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&fe()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(k(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await P(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new xe})})}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:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await P(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new xe})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let i=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+xd>i)return n;let{data:s,error:o}=await P(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=i,n=s.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:f,error:m}=await this.getSession();if(m||!f.session)return this._returnResult({data:null,error:m});n=f.session.access_token}let{header:i,payload:s,signature:o,raw:{header:a,payload:c}}=Ci(n);r?.allowExpired||$d(s.exp);let l=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!l){let{error:f}=await this.getUser(n);if(f)throw f;return{data:{claims:s,header:i,signature:o},error:null}}let u=Md(i.alg),d=await crypto.subtle.importKey("jwk",l,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,Cd(`${a}.${c}`)))throw new kr("Invalid JWT signature");return{data:{claims:s,header:i,signature:o},error:null}}catch(n){if(k(n))return this._returnResult({data:null,error:n});throw n}}};Gs.nextInstanceID={};var kc=Gs;var F_=kc,Ec=F_;var q_="2.100.1",Ai="";typeof Deno<"u"?Ai="deno":typeof document<"u"?Ai="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ai="react-native":Ai="node";var B_={"X-Client-Info":`supabase-js-${Ai}/${q_}`},V_={headers:B_},H_={schema:"public"},W_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},z_={};function Di(t){"@babel/helpers - typeof";return Di=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},Di(t)}function K_(t,e){if(Di(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Di(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function G_(t){var e=K_(t,"string");return Di(e)=="symbol"?e:e+""}function J_(t,e,r){return(e=G_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function th(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function se(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?th(Object(r),!0).forEach(function(n){J_(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):th(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var Y_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),X_=()=>Headers,Z_=(t,e,r)=>{let n=Y_(r),i=X_();return async(s,o)=>{var a;let c=(a=await e())!==null&&a!==void 0?a:t,l=new i(o?.headers);return l.has("apikey")||l.set("apikey",t),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),n(s,se(se({},o),{},{headers:l}))}};function Q_(t){return t.endsWith("/")?t:t+"/"}function eb(t,e){var r,n;let{db:i,auth:s,realtime:o,global:a}=t,{db:c,auth:l,realtime:u,global:d}=e,h={db:se(se({},c),i),auth:se(se({},l),s),realtime:se(se({},u),o),storage:{},global:se(se(se({},d),a),{},{headers:se(se({},(r=d?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?h.accessToken=t.accessToken:delete h.accessToken,h}function tb(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(Q_(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var rb=class extends Ec{constructor(t){super(t)}},nb=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;let s=tb(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 o=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:H_,realtime:z_,auth:se(se({},W_),{},{storageKey:o}),global:V_},c=eb(r??{},a);if(this.storageKey=(n=c.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=c.global.headers)!==null&&i!==void 0?i:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var l;this.auth=this._initSupabaseAuthClient((l=c.auth)!==null&&l!==void 0?l:{},this.headers,c.global.fetch)}this.fetch=Z_(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(se({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new rd(new URL("rest/v1",s).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new _d(this.storageUrl.href,this.headers,this.fetch,r?.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new mi(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:s,flowType:o,lock:a,debug:c,throwOnError:l},u,d){let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new rb({url:this.authUrl.href,headers:se(se({},h),u),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:a,debug:c,throwOnError:l,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new mn(this.realtimeUrl.href,se(se({},t),{},{params:se(se({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},rh=(t,e,r)=>new nb(t,e,r);function ib(){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}ib()&&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 Tc="0.5.2";var sh=qn(Pc());function Ar(){return typeof window<"u"&&typeof window.document<"u"}var er={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4};var gb=/^(.*)[.](0|[1-9][0-9]*)$/;function Ni(t,e){if(t===e)return!0;let r=t.match(gb);return!!(r&&r[1]===e)}function Cc(t,e,r){let n=r??3180,i=encodeURIComponent(e);if(i.length<=n)return[{name:t,value:e}];let s=[];for(;i.length>0;){let o=i.slice(0,n),a=o.lastIndexOf("%");a>n-3&&(o=o.slice(0,a));let c="";for(;o.length>0;)try{c=decodeURIComponent(o);break}catch(l){if(l instanceof URIError&&o.at(-3)==="%"&&o.length>3)o=o.slice(0,o.length-3);else throw l}s.push(c),i=i.slice(o.length)}return s.map((o,a)=>({name:`${t}.${a}`,value:o}))}async function Ic(t,e){let r=await e(t);if(r)return r;let n=[];for(let i=0;;i++){let s=`${t}.${i}`,o=await e(s);if(!o)break;n.push(o)}return n.length>0?n.join(""):null}var Js="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),oh=`
88
- \r=`.split(""),yb=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<oh.length;e+=1)t[oh[e].charCodeAt(0)]=-2;for(let e=0;e<Js.length;e+=1)t[Js[e].charCodeAt(0)]=e;return t})();function Rc(t){let e=[],r=0,n=0;if(bb(t,s=>{for(r=r<<8|s,n+=8;n>=6;){let o=r>>n-6&63;e.push(Js[o]),n-=6}}),n>0)for(r=r<<6-n,n=6;n>=6;){let s=r>>n-6&63;e.push(Js[s]),n-=6}return e.join("")}function Ac(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},i=0,s=0;for(let o=0;o<t.length;o+=1){let a=t.charCodeAt(o),c=yb[a];if(c>-1)for(i=i<<6|c,s+=6;s>=8;)wb(i>>s-8&255,n,r),s-=8;else{if(c===-2)continue;throw new Error(`Invalid Base64-URL character "${t.at(o)}" at position ${o}`)}}return e.join("")}function _b(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 bb(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}_b(n,e)}}function wb(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}var Ys=qn(Pc());var _n="base64-";function Dc(t,e){let r=t.cookies??null,n=t.cookieEncoding,i={},s={},o,a;if(r)if("get"in r){let c=async l=>{let u=l.flatMap(h=>[h,...Array.from({length:5}).map((f,m)=>`${h}.${m}`)]),d=[];for(let h=0;h<u.length;h+=1){let f=await r.get(u[h]);!f&&typeof f!="string"||d.push({name:u[h],value:f})}return d};if(o=async l=>await c(l),"set"in r&&"remove"in r)a=async l=>{for(let u=0;u<l.length;u+=1){let{name:d,value:h,options:f}=l[u];h?await r.set(d,h,f):await r.remove(d,f)}};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(o=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).${Ar()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""}`);else if(!e&&Ar()){let c=()=>{let l=(0,Ys.parse)(document.cookie);return Object.keys(l).map(u=>({name:u,value:l[u]}))};o=()=>c(),a=l=>{l.forEach(({name:u,value:d,options:h})=>{document.cookie=(0,Ys.serialize)(u,d,h)})}}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)");o=()=>[],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:o,setAll:a,setItems:i,removedItems:s,storage:{isServer:!0,getItem:async c=>{if(typeof i[c]=="string")return i[c];if(s[c])return null;let l=await o([c]),u=await Ic(c,async h=>{let f=l?.find(({name:m})=>m===h)||null;return f?f.value:null});if(!u)return null;let d=u;return typeof u=="string"&&u.startsWith(_n)&&(d=Ac(u.substring(_n.length))),d},setItem:async(c,l)=>{c.endsWith("-code-verifier")&&await ah({getAll:o,setAll:a,setItems:{[c]:l},removedItems:{}},{cookieOptions:t?.cookieOptions??null,cookieEncoding:n}),i[c]=l,delete s[c]},removeItem:async c=>{delete i[c],s[c]=!0}}}:{getAll:o,setAll:a,setItems:i,removedItems:s,storage:{isServer:!1,getItem:async c=>{let l=await o([c]),u=await Ic(c,async h=>{let f=l?.find(({name:m})=>m===h)||null;return f?f.value:null});if(!u)return null;let d=u;return u.startsWith(_n)&&(d=Ac(u.substring(_n.length))),d},setItem:async(c,l)=>{let d=(await o([c]))?.map(({name:_})=>_)||[],h=new Set(d.filter(_=>Ni(_,c))),f=l;n==="base64url"&&(f=_n+Rc(l));let m=Cc(c,f);m.forEach(({name:_})=>{h.delete(_)});let g={...er,...t?.cookieOptions,maxAge:0},y={...er,...t?.cookieOptions,maxAge:er.maxAge};delete g.name,delete y.name;let p=[...[...h].map(_=>({name:_,value:"",options:g})),...m.map(({name:_,value:b})=>({name:_,value:b,options:y}))];p.length>0&&await a(p)},removeItem:async c=>{let d=((await o([c]))?.map(({name:f})=>f)||[]).filter(f=>Ni(f,c)),h={...er,...t?.cookieOptions,maxAge:0};delete h.name,d.length>0&&await a(d.map(f=>({name:f,value:"",options:h})))}}}}async function ah({getAll:t,setAll:e,setItems:r,removedItems:n},i){let s=i.cookieEncoding,o=i.cookieOptions??null,c=(await t([...r?Object.keys(r):[],...n?Object.keys(n):[]]))?.map(({name:f})=>f)||[],l=Object.keys(n).flatMap(f=>c.filter(m=>Ni(m,f))),u=Object.keys(r).flatMap(f=>{let m=new Set(c.filter(p=>Ni(p,f))),g=r[f];s==="base64url"&&(g=_n+Rc(g));let y=Cc(f,g);return y.forEach(p=>{m.delete(p.name)}),l.push(...m),y}),d={...er,...o,maxAge:0},h={...er,...o,maxAge:er.maxAge};delete d.name,delete h.name,await e([...l.map(f=>({name:f,value:"",options:d})),...u.map(({name:f,value:m})=>({name:f,value:m,options:h}))])}var Nc;function ch(t,e,r){let n=r?.isSingleton===!0||(!r||!("isSingleton"in r))&&Ar();if(n&&Nc)return Nc;if(!t||!e)throw new Error(`@supabase/ssr: Your project's URL and API key are required to create a Supabase client!
77
+ Version: ${f}
78
+ Chain ID: ${r}${i?`
79
+ Nonce: ${i}`:""}
80
+ Issued At: ${s.toISOString()}`;if(n&&(p+=`
81
+ Expiration Time: ${n.toISOString()}`),a&&(p+=`
82
+ Not Before: ${a.toISOString()}`),l&&(p+=`
83
+ Request ID: ${l}`),u){let b=`
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
+ - ${_}`}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<dm.length;e+=1)t[dm[e].charCodeAt(0)]=-2;for(let e=0;e<Oi.length;e+=1)t[Oi[e].charCodeAt(0)]=e;return t})();function gu(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 yu(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(mu());var Fo="base64-";function bu(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 pu(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=yu(c.substring(Fo.length))),d},setItem:async(l,u)=>{l.endsWith("-code-verifier")&&await fm({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 pu(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=yu(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+gu(u));let h=hu(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 fm({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+gu(g));let y=hu(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 _u;function mm(t,e,r){let o=r?.isSingleton===!0||(!r||!("isSingleton"in r))&&Qr();if(o&&_u)return _u;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:i}=Dc({...r,cookieEncoding:r?.cookieEncoding??"base64url"},!1),s=rh(t,e,{...r,global:{...r?.global,headers:{...r?.global?.headers,"X-Client-Info":`supabase-ssr/${Tc}`}},auth:{...r?.auth,...r?.cookieOptions?.name?{storageKey:r.cookieOptions.name}:null,flowType:"pkce",autoRefreshToken:Ar(),detectSessionInUrl:Ar(),persistSession:!0,storage:i}});return n&&(Nc=s),s}var Lc="https://dhnpoxorllfdobwftkyb.supabase.co",jc="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRobnBveG9ybGxmZG9id2Z0a3liIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzkwNTQxMDgsImV4cCI6MjA1NDYzMDEwOH0.zI8PwbgKwijHZ1QmxJqmaPrFvg02w1vOY2Qcs7SddzI";var Xs=process.env.NODE_ENV==="production"?"https://api.zorgotech.com":"http://localhost:3000";var lh={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},POS_METHOD_ID:3,ORDER_TYPE:{DINE_IN:1,TAKEOUT:2,DELIVERY:3},MODIFICATION_HIGHLIGHT_MS:8e3,LISTENER_SYNC_INTERVAL_MS:6e4,ORDER_SELECT:`
92
+ https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=bu({...r,cookieEncoding:r?.cookieEncoding??"base64url"},!1),s=am(t,e,{...r,global:{...r?.global,headers:{...r?.global?.headers,"X-Client-Info":`supabase-ssr/${du}`}},auth:{...r?.auth,...r?.cookieOptions?.name?{storageKey:r.cookieOptions.name}:null,flowType:"pkce",autoRefreshToken:Qr(),detectSessionInUrl:Qr(),persistSession:!0,storage:n}});return o&&(_u=s),s}var wu=process.env.NEXT_PUBLIC_SUPABASE_URL||process.env.EXPO_PUBLIC_SUPABASE_URL||"https://dhnpoxorllfdobwftkyb.supabase.co",vu=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 (
@@ -119,6 +119,11 @@ https://supabase.com/dashboard/project/_/settings/api`);let{storage:i}=Dc({...r,
119
119
  base_items (
120
120
  base_item_id, category_id, name,
121
121
  categories (category_id, name, is_catering)
122
+ ),
123
+ item_components (
124
+ servings_per_item,
125
+ component_quantity_behaviors (headcount_threshold, starting_amount, step_size, step_interval, maximum),
126
+ components (id, name, component_type_id, serving_weight, measurement_type, display_unit)
122
127
  )
123
128
  ),
124
129
  item_rules (rule_id, group_name)
@@ -132,7 +137,7 @@ https://supabase.com/dashboard/project/_/settings/api`);let{storage:i}=Dc({...r,
132
137
  components (id, name, component_type_id, serving_weight, measurement_type, display_unit)
133
138
  )
134
139
  )
135
- `};var uh=null;var $c=(t,e)=>{if(!uh)return fetch(t,e);let r=new Headers(e?.headers);return r.set("Authorization",`Bearer ${uh}`),fetch(t,{...e,headers:r})};var Bc=globalThis?.navigator?.product==="ReactNative",Eh=typeof process<"u"&&process.versions?.node,Cb=!Bc&&!Eh&&typeof globalThis?.document<"u";function kh(){if(!Eh&&Bc)try{return(qc(),Hl(Fc)).default}catch{return}}function Ib(){return Cb?ch(Lc,jc,{global:{fetch:$c}}):Xu(Lc,jc,{auth:{autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!Bc,...kh()?{storage:kh()}:{},lock:Xa},global:{fetch:$c}})}var j=Ib();import{immer as Av}from"zustand/middleware/immer";import{createJSONStorage as Dv,devtools as Nv,persist as Lv}from"zustand/middleware";var Rb=Math.pow(10,8)*24*60*60*1e3,rC=-Rb,to=6048e5,Th=864e5,ro=6e4,no=36e5,Oh=1e3;var Ab=3600;var Ph=Ab*24,nC=Ph*7,Db=Ph*365.2425,Nb=Db/12,iC=Nb*3,Vc=Symbol.for("constructDateFrom");function F(t,e){return typeof t=="function"?t(e):t&&typeof t=="object"&&Vc in t?t[Vc](e):t instanceof Date?new t.constructor(e):new Date(e)}function A(t,e){return F(e||t,t)}function io(t,e,r){let n=A(t,r?.in);return isNaN(e)?F(r?.in||t,NaN):(e&&n.setDate(n.getDate()+e),n)}function Ch(t,e,r){return F(r?.in||t,+A(t)+e)}function Sn(t,e,r){return Ch(t,e*no,r)}var Lb={};function ze(){return Lb}function Ce(t,e){let r=ze(),n=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,i=A(t,e?.in),s=i.getDay(),o=(s<n?7:0)+s-n;return i.setDate(i.getDate()-o),i.setHours(0,0,0,0),i}function ct(t,e){return Ce(t,{...e,weekStartsOn:1})}function so(t,e){let r=A(t,e?.in),n=r.getFullYear(),i=F(r,0);i.setFullYear(n+1,0,4),i.setHours(0,0,0,0);let s=ct(i),o=F(r,0);o.setFullYear(n,0,4),o.setHours(0,0,0,0);let a=ct(o);return r.getTime()>=s.getTime()?n+1:r.getTime()>=a.getTime()?n:n-1}function Nr(t){let e=A(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 Ih(t,...e){let r=F.bind(null,t||e.find(n=>typeof n=="object"));return e.map(r)}function lt(t,e){let r=A(t,e?.in);return r.setHours(0,0,0,0),r}function Rh(t,e,r){let[n,i]=Ih(r?.in,t,e),s=lt(n),o=lt(i),a=+s-Nr(s),c=+o-Nr(o);return Math.round((a-c)/Th)}function Ah(t,e){let r=so(t,e),n=F(e?.in||t,0);return n.setFullYear(r,0,4),n.setHours(0,0,0,0),ct(n)}function Dh(t,e,r){let n=A(t,r?.in);return n.setTime(n.getTime()+e*ro),n}function Nh(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function Lr(t){return!(!Nh(t)&&typeof t!="number"||isNaN(+A(t)))}function Lh(t,e){let r=A(t,e?.in);return r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0),r}var jb={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"}},jh=(t,e,r)=>{let n,i=jb[t];return typeof i=="string"?n=i:e===1?n=i.one:n=i.other.replace("{{count}}",e.toString()),r?.addSuffix?r.comparison&&r.comparison>0?"in "+n:n+" ago":n};function oo(t){return(e={})=>{let r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}var $b={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Mb={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Ub={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},$h={date:oo({formats:$b,defaultWidth:"full"}),time:oo({formats:Mb,defaultWidth:"full"}),dateTime:oo({formats:Ub,defaultWidth:"full"})};var Fb={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Mh=(t,e,r,n)=>Fb[t];function xn(t){return(e,r)=>{let n=r?.context?String(r.context):"standalone",i;if(n==="formatting"&&t.formattingValues){let o=t.defaultFormattingWidth||t.defaultWidth,a=r?.width?String(r.width):o;i=t.formattingValues[a]||t.formattingValues[o]}else{let o=t.defaultWidth,a=r?.width?String(r.width):t.defaultWidth;i=t.values[a]||t.values[o]}let s=t.argumentCallback?t.argumentCallback(e):e;return i[s]}}var qb={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Bb={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Vb={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"]},Hb={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"]},Wb={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"}},zb={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"}},Kb=(t,e)=>{let r=Number(t),n=r%100;if(n>20||n<10)switch(n%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},Uh={ordinalNumber:Kb,era:xn({values:qb,defaultWidth:"wide"}),quarter:xn({values:Bb,defaultWidth:"wide",argumentCallback:t=>t-1}),month:xn({values:Vb,defaultWidth:"wide"}),day:xn({values:Hb,defaultWidth:"wide"}),dayPeriod:xn({values:Wb,defaultWidth:"wide",formattingValues:zb,defaultFormattingWidth:"wide"})};function kn(t){return(e,r={})=>{let n=r.width,i=n&&t.matchPatterns[n]||t.matchPatterns[t.defaultMatchWidth],s=e.match(i);if(!s)return null;let o=s[0],a=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],c=Array.isArray(a)?Jb(a,d=>d.test(o)):Gb(a,d=>d.test(o)),l;l=t.valueCallback?t.valueCallback(c):c,l=r.valueCallback?r.valueCallback(l):l;let u=e.slice(o.length);return{value:l,rest:u}}}function Gb(t,e){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function Jb(t,e){for(let r=0;r<t.length;r++)if(e(t[r]))return r}function Fh(t){return(e,r={})=>{let n=e.match(t.matchPattern);if(!n)return null;let i=n[0],s=e.match(t.parsePattern);if(!s)return null;let o=t.valueCallback?t.valueCallback(s[0]):s[0];o=r.valueCallback?r.valueCallback(o):o;let a=e.slice(i.length);return{value:o,rest:a}}}var Yb=/^(\d+)(th|st|nd|rd)?/i,Xb=/\d+/i,Zb={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},Qb={any:[/^b/i,/^(a|c)/i]},ew={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},tw={any:[/1/i,/2/i,/3/i,/4/i]},rw={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},nw={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]},iw={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},sw={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]},ow={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},aw={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}},qh={ordinalNumber:Fh({matchPattern:Yb,parsePattern:Xb,valueCallback:t=>parseInt(t,10)}),era:kn({matchPatterns:Zb,defaultMatchWidth:"wide",parsePatterns:Qb,defaultParseWidth:"any"}),quarter:kn({matchPatterns:ew,defaultMatchWidth:"wide",parsePatterns:tw,defaultParseWidth:"any",valueCallback:t=>t+1}),month:kn({matchPatterns:rw,defaultMatchWidth:"wide",parsePatterns:nw,defaultParseWidth:"any"}),day:kn({matchPatterns:iw,defaultMatchWidth:"wide",parsePatterns:sw,defaultParseWidth:"any"}),dayPeriod:kn({matchPatterns:ow,defaultMatchWidth:"any",parsePatterns:aw,defaultParseWidth:"any"})};var ji={code:"en-US",formatDistance:jh,formatLong:$h,formatRelative:Mh,localize:Uh,match:qh,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Bh(t,e){let r=A(t,e?.in);return Rh(r,Lh(r))+1}function ao(t,e){let r=A(t,e?.in),n=+ct(r)-+Ah(r);return Math.round(n/to)+1}function En(t,e){let r=A(t,e?.in),n=r.getFullYear(),i=ze(),s=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??i.firstWeekContainsDate??i.locale?.options?.firstWeekContainsDate??1,o=F(e?.in||t,0);o.setFullYear(n+1,0,s),o.setHours(0,0,0,0);let a=Ce(o,e),c=F(e?.in||t,0);c.setFullYear(n,0,s),c.setHours(0,0,0,0);let l=Ce(c,e);return+r>=+a?n+1:+r>=+l?n:n-1}function Vh(t,e){let r=ze(),n=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,i=En(t,e),s=F(e?.in||t,0);return s.setFullYear(i,0,n),s.setHours(0,0,0,0),Ce(s,e)}function co(t,e){let r=A(t,e?.in),n=+Ce(r,e)-+Vh(r,e);return Math.round(n/to)+1}function W(t,e){let r=t<0?"-":"",n=Math.abs(t).toString().padStart(e,"0");return r+n}var Lt={y(t,e){let r=t.getFullYear(),n=r>0?r:1-r;return W(e==="yy"?n%100:n,e.length)},M(t,e){let r=t.getMonth();return e==="M"?String(r+1):W(r+1,2)},d(t,e){return W(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 W(t.getHours()%12||12,e.length)},H(t,e){return W(t.getHours(),e.length)},m(t,e){return W(t.getMinutes(),e.length)},s(t,e){return W(t.getSeconds(),e.length)},S(t,e){let r=e.length,n=t.getMilliseconds(),i=Math.trunc(n*Math.pow(10,r-3));return W(i,e.length)}};var Tn={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Hc={G:function(t,e,r){let n=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return r.era(n,{width:"abbreviated"});case"GGGGG":return r.era(n,{width:"narrow"});default:return r.era(n,{width:"wide"})}},y:function(t,e,r){if(e==="yo"){let n=t.getFullYear(),i=n>0?n:1-n;return r.ordinalNumber(i,{unit:"year"})}return Lt.y(t,e)},Y:function(t,e,r,n){let i=En(t,n),s=i>0?i:1-i;if(e==="YY"){let o=s%100;return W(o,2)}return e==="Yo"?r.ordinalNumber(s,{unit:"year"}):W(s,e.length)},R:function(t,e){let r=so(t);return W(r,e.length)},u:function(t,e){let r=t.getFullYear();return W(r,e.length)},Q:function(t,e,r){let n=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return W(n,2);case"Qo":return r.ordinalNumber(n,{unit:"quarter"});case"QQQ":return r.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(n,{width:"narrow",context:"formatting"});default:return r.quarter(n,{width:"wide",context:"formatting"})}},q:function(t,e,r){let n=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return W(n,2);case"qo":return r.ordinalNumber(n,{unit:"quarter"});case"qqq":return r.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(n,{width:"narrow",context:"standalone"});default:return r.quarter(n,{width:"wide",context:"standalone"})}},M:function(t,e,r){let n=t.getMonth();switch(e){case"M":case"MM":return Lt.M(t,e);case"Mo":return r.ordinalNumber(n+1,{unit:"month"});case"MMM":return r.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(n,{width:"narrow",context:"formatting"});default:return r.month(n,{width:"wide",context:"formatting"})}},L:function(t,e,r){let n=t.getMonth();switch(e){case"L":return String(n+1);case"LL":return W(n+1,2);case"Lo":return r.ordinalNumber(n+1,{unit:"month"});case"LLL":return r.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(n,{width:"narrow",context:"standalone"});default:return r.month(n,{width:"wide",context:"standalone"})}},w:function(t,e,r,n){let i=co(t,n);return e==="wo"?r.ordinalNumber(i,{unit:"week"}):W(i,e.length)},I:function(t,e,r){let n=ao(t);return e==="Io"?r.ordinalNumber(n,{unit:"week"}):W(n,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):Lt.d(t,e)},D:function(t,e,r){let n=Bh(t);return e==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):W(n,e.length)},E:function(t,e,r){let n=t.getDay();switch(e){case"E":case"EE":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"})}},e:function(t,e,r,n){let i=t.getDay(),s=(i-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(s);case"ee":return W(s,2);case"eo":return r.ordinalNumber(s,{unit:"day"});case"eee":return r.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(i,{width:"short",context:"formatting"});default:return r.day(i,{width:"wide",context:"formatting"})}},c:function(t,e,r,n){let i=t.getDay(),s=(i-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(s);case"cc":return W(s,e.length);case"co":return r.ordinalNumber(s,{unit:"day"});case"ccc":return r.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(i,{width:"narrow",context:"standalone"});case"cccccc":return r.day(i,{width:"short",context:"standalone"});default:return r.day(i,{width:"wide",context:"standalone"})}},i:function(t,e,r){let n=t.getDay(),i=n===0?7:n;switch(e){case"i":return String(i);case"ii":return W(i,e.length);case"io":return r.ordinalNumber(i,{unit:"day"});case"iii":return r.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(n,{width:"short",context:"formatting"});default:return r.day(n,{width:"wide",context:"formatting"})}},a:function(t,e,r){let i=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(i,{width:"narrow",context:"formatting"});default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(t,e,r){let n=t.getHours(),i;switch(n===12?i=Tn.noon:n===0?i=Tn.midnight:i=n/12>=1?"pm":"am",e){case"b":case"bb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(i,{width:"narrow",context:"formatting"});default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(t,e,r){let n=t.getHours(),i;switch(n>=17?i=Tn.evening:n>=12?i=Tn.afternoon:n>=4?i=Tn.morning:i=Tn.night,e){case"B":case"BB":case"BBB":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(i,{width:"narrow",context:"formatting"});default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(t,e,r){if(e==="ho"){let n=t.getHours()%12;return n===0&&(n=12),r.ordinalNumber(n,{unit:"hour"})}return Lt.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):Lt.H(t,e)},K:function(t,e,r){let n=t.getHours()%12;return e==="Ko"?r.ordinalNumber(n,{unit:"hour"}):W(n,e.length)},k:function(t,e,r){let n=t.getHours();return n===0&&(n=24),e==="ko"?r.ordinalNumber(n,{unit:"hour"}):W(n,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):Lt.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):Lt.s(t,e)},S:function(t,e){return Lt.S(t,e)},X:function(t,e,r){let n=t.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return Wh(n);case"XXXX":case"XX":return jr(n);default:return jr(n,":")}},x:function(t,e,r){let n=t.getTimezoneOffset();switch(e){case"x":return Wh(n);case"xxxx":case"xx":return jr(n);default:return jr(n,":")}},O:function(t,e,r){let n=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Hh(n,":");default:return"GMT"+jr(n,":")}},z:function(t,e,r){let n=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Hh(n,":");default:return"GMT"+jr(n,":")}},t:function(t,e,r){let n=Math.trunc(+t/1e3);return W(n,e.length)},T:function(t,e,r){return W(+t,e.length)}};function Hh(t,e=""){let r=t>0?"-":"+",n=Math.abs(t),i=Math.trunc(n/60),s=n%60;return s===0?r+String(i):r+String(i)+e+W(s,2)}function Wh(t,e){return t%60===0?(t>0?"-":"+")+W(Math.abs(t)/60,2):jr(t,e)}function jr(t,e=""){let r=t>0?"-":"+",n=Math.abs(t),i=W(Math.trunc(n/60),2),s=W(n%60,2);return r+i+e+s}var zh=(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"})}},Kh=(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"})}},cw=(t,e)=>{let r=t.match(/(P+)(p+)?/)||[],n=r[1],i=r[2];if(!i)return zh(t,e);let s;switch(n){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}}",zh(n,e)).replace("{{time}}",Kh(i,e))},$i={p:Kh,P:cw};var lw=/^D+$/,uw=/^Y+$/,dw=["D","DD","YY","YYYY"];function lo(t){return lw.test(t)}function uo(t){return uw.test(t)}function Mi(t,e,r){let n=hw(t,e,r);if(console.warn(n),dw.includes(t))throw new RangeError(n)}function hw(t,e,r){let n=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${n} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var fw=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,mw=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,pw=/^'([^]*?)'?$/,gw=/''/g,yw=/[a-zA-Z]/;function Ke(t,e,r){let n=ze(),i=r?.locale??n.locale??ji,s=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,a=A(t,r?.in);if(!Lr(a))throw new RangeError("Invalid time value");let c=e.match(mw).map(u=>{let d=u[0];if(d==="p"||d==="P"){let h=$i[d];return h(u,i.formatLong)}return u}).join("").match(fw).map(u=>{if(u==="''")return{isToken:!1,value:"'"};let d=u[0];if(d==="'")return{isToken:!1,value:_w(u)};if(Hc[d])return{isToken:!0,value:u};if(d.match(yw))throw new RangeError("Format string contains an unescaped latin alphabet character `"+d+"`");return{isToken:!1,value:u}});i.localize.preprocessor&&(c=i.localize.preprocessor(a,c));let l={firstWeekContainsDate:s,weekStartsOn:o,locale:i};return c.map(u=>{if(!u.isToken)return u.value;let d=u.value;(!r?.useAdditionalWeekYearTokens&&uo(d)||!r?.useAdditionalDayOfYearTokens&&lo(d))&&Mi(d,e,String(t));let h=Hc[d[0]];return h(a,d,i.localize,l)}).join("")}function _w(t){let e=t.match(pw);return e?e[1].replace(gw,"'"):t}function ho(t,e){return A(t,e?.in).getDay()}function fo(){return Object.assign({},ze())}function Gh(t,e){let r=A(t,e?.in).getDay();return r===0?7:r}function kt(t,e){return+A(t)>+A(e)}function Ie(t,e){return+A(t)<+A(e)}function Jh(t,e){let r=bw(e)?new e(0):F(e,0);return r.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),r.setHours(t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()),r}function bw(t){return typeof t=="function"&&t.prototype?.constructor===t}var ww=10,mo=class{subPriority=0;validate(e,r){return!0}},po=class extends mo{constructor(e,r,n,i,s){super(),this.value=e,this.validateValue=r,this.setValue=n,this.priority=i,s&&(this.subPriority=s)}validate(e,r){return this.validateValue(e,this.value,r)}set(e,r,n){return this.setValue(e,r,this.value,n)}},go=class extends mo{priority=ww;subPriority=-1;constructor(e,r){super(),this.context=e||(n=>F(r,n))}set(e,r){return r.timestampIsSet?e:F(e,Jh(e,this.context))}};var E=class{run(e,r,n,i){let s=this.parse(e,r,n,i);return s?{setter:new po(s.value,this.validate,this.set,this.priority,this.subPriority),rest:s.rest}:null}validate(e,r,n){return!0}};var yo=class extends E{priority=140;parse(e,r,n){switch(r){case"G":case"GG":case"GGG":return n.era(e,{width:"abbreviated"})||n.era(e,{width:"narrow"});case"GGGGG":return n.era(e,{width:"narrow"});default:return n.era(e,{width:"wide"})||n.era(e,{width:"abbreviated"})||n.era(e,{width:"narrow"})}}set(e,r,n){return r.era=n,e.setFullYear(n,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["R","u","t","T"]};var B={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}/},Ge={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 z(t,e){return t&&{value:e(t.value),rest:t.rest}}function q(t,e){let r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function Je(t,e){let r=e.match(t);if(!r)return null;if(r[0]==="Z")return{value:0,rest:e.slice(1)};let n=r[1]==="+"?1:-1,i=r[2]?parseInt(r[2],10):0,s=r[3]?parseInt(r[3],10):0,o=r[5]?parseInt(r[5],10):0;return{value:n*(i*no+s*ro+o*Oh),rest:e.slice(r[0].length)}}function _o(t){return q(B.anyDigitsSigned,t)}function $(t,e){switch(t){case 1:return q(B.singleDigit,e);case 2:return q(B.twoDigits,e);case 3:return q(B.threeDigits,e);case 4:return q(B.fourDigits,e);default:return q(new RegExp("^\\d{1,"+t+"}"),e)}}function On(t,e){switch(t){case 1:return q(B.singleDigitSigned,e);case 2:return q(B.twoDigitsSigned,e);case 3:return q(B.threeDigitsSigned,e);case 4:return q(B.fourDigitsSigned,e);default:return q(new RegExp("^-?\\d{1,"+t+"}"),e)}}function Pn(t){switch(t){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function bo(t,e){let r=e>0,n=r?e:1-e,i;if(n<=50)i=t||100;else{let s=n+50,o=Math.trunc(s/100)*100,a=t>=s%100;i=t+o-(a?100:0)}return r?i:1-i}function wo(t){return t%400===0||t%4===0&&t%100!==0}var vo=class extends E{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(e,r,n){let i=s=>({year:s,isTwoDigitYear:r==="yy"});switch(r){case"y":return z($(4,e),i);case"yo":return z(n.ordinalNumber(e,{unit:"year"}),i);default:return z($(r.length,e),i)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,n){let i=e.getFullYear();if(n.isTwoDigitYear){let o=bo(n.year,i);return e.setFullYear(o,0,1),e.setHours(0,0,0,0),e}let s=!("era"in r)||r.era===1?n.year:1-n.year;return e.setFullYear(s,0,1),e.setHours(0,0,0,0),e}};var So=class extends E{priority=130;parse(e,r,n){let i=s=>({year:s,isTwoDigitYear:r==="YY"});switch(r){case"Y":return z($(4,e),i);case"Yo":return z(n.ordinalNumber(e,{unit:"year"}),i);default:return z($(r.length,e),i)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,n,i){let s=En(e,i);if(n.isTwoDigitYear){let a=bo(n.year,s);return e.setFullYear(a,0,i.firstWeekContainsDate),e.setHours(0,0,0,0),Ce(e,i)}let o=!("era"in r)||r.era===1?n.year:1-n.year;return e.setFullYear(o,0,i.firstWeekContainsDate),e.setHours(0,0,0,0),Ce(e,i)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]};var xo=class extends E{priority=130;parse(e,r){return r==="R"?On(4,e):On(r.length,e)}set(e,r,n){let i=F(e,0);return i.setFullYear(n,0,4),i.setHours(0,0,0,0),ct(i)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]};var ko=class extends E{priority=130;parse(e,r){return r==="u"?On(4,e):On(r.length,e)}set(e,r,n){return e.setFullYear(n,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]};var Eo=class extends E{priority=120;parse(e,r,n){switch(r){case"Q":case"QQ":return $(r.length,e);case"Qo":return n.ordinalNumber(e,{unit:"quarter"});case"QQQ":return n.quarter(e,{width:"abbreviated",context:"formatting"})||n.quarter(e,{width:"narrow",context:"formatting"});case"QQQQQ":return n.quarter(e,{width:"narrow",context:"formatting"});default:return n.quarter(e,{width:"wide",context:"formatting"})||n.quarter(e,{width:"abbreviated",context:"formatting"})||n.quarter(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=1&&r<=4}set(e,r,n){return e.setMonth((n-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 To=class extends E{priority=120;parse(e,r,n){switch(r){case"q":case"qq":return $(r.length,e);case"qo":return n.ordinalNumber(e,{unit:"quarter"});case"qqq":return n.quarter(e,{width:"abbreviated",context:"standalone"})||n.quarter(e,{width:"narrow",context:"standalone"});case"qqqqq":return n.quarter(e,{width:"narrow",context:"standalone"});default:return n.quarter(e,{width:"wide",context:"standalone"})||n.quarter(e,{width:"abbreviated",context:"standalone"})||n.quarter(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=1&&r<=4}set(e,r,n){return e.setMonth((n-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 Oo=class extends E{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(e,r,n){let i=s=>s-1;switch(r){case"M":return z(q(B.month,e),i);case"MM":return z($(2,e),i);case"Mo":return z(n.ordinalNumber(e,{unit:"month"}),i);case"MMM":return n.month(e,{width:"abbreviated",context:"formatting"})||n.month(e,{width:"narrow",context:"formatting"});case"MMMMM":return n.month(e,{width:"narrow",context:"formatting"});default:return n.month(e,{width:"wide",context:"formatting"})||n.month(e,{width:"abbreviated",context:"formatting"})||n.month(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=11}set(e,r,n){return e.setMonth(n,1),e.setHours(0,0,0,0),e}};var Po=class extends E{priority=110;parse(e,r,n){let i=s=>s-1;switch(r){case"L":return z(q(B.month,e),i);case"LL":return z($(2,e),i);case"Lo":return z(n.ordinalNumber(e,{unit:"month"}),i);case"LLL":return n.month(e,{width:"abbreviated",context:"standalone"})||n.month(e,{width:"narrow",context:"standalone"});case"LLLLL":return n.month(e,{width:"narrow",context:"standalone"});default:return n.month(e,{width:"wide",context:"standalone"})||n.month(e,{width:"abbreviated",context:"standalone"})||n.month(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=11}set(e,r,n){return e.setMonth(n,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]};function Yh(t,e,r){let n=A(t,r?.in),i=co(n,r)-e;return n.setDate(n.getDate()-i*7),A(n,r?.in)}var Co=class extends E{priority=100;parse(e,r,n){switch(r){case"w":return q(B.week,e);case"wo":return n.ordinalNumber(e,{unit:"week"});default:return $(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,n,i){return Ce(Yh(e,n,i),i)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]};function Xh(t,e,r){let n=A(t,r?.in),i=ao(n,r)-e;return n.setDate(n.getDate()-i*7),n}var Io=class extends E{priority=100;parse(e,r,n){switch(r){case"I":return q(B.week,e);case"Io":return n.ordinalNumber(e,{unit:"week"});default:return $(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,n){return ct(Xh(e,n))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]};var vw=[31,28,31,30,31,30,31,31,30,31,30,31],Sw=[31,29,31,30,31,30,31,31,30,31,30,31],Ro=class extends E{priority=90;subPriority=1;parse(e,r,n){switch(r){case"d":return q(B.date,e);case"do":return n.ordinalNumber(e,{unit:"date"});default:return $(r.length,e)}}validate(e,r){let n=e.getFullYear(),i=wo(n),s=e.getMonth();return i?r>=1&&r<=Sw[s]:r>=1&&r<=vw[s]}set(e,r,n){return e.setDate(n),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]};var Ao=class extends E{priority=90;subpriority=1;parse(e,r,n){switch(r){case"D":case"DD":return q(B.dayOfYear,e);case"Do":return n.ordinalNumber(e,{unit:"date"});default:return $(r.length,e)}}validate(e,r){let n=e.getFullYear();return wo(n)?r>=1&&r<=366:r>=1&&r<=365}set(e,r,n){return e.setMonth(0,n),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]};function Cn(t,e,r){let n=ze(),i=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,s=A(t,r?.in),o=s.getDay(),c=(e%7+7)%7,l=7-i,u=e<0||e>6?e-(o+l)%7:(c+l)%7-(o+l)%7;return io(s,u,r)}var Do=class extends E{priority=90;parse(e,r,n){switch(r){case"E":case"EE":case"EEE":return n.day(e,{width:"abbreviated",context:"formatting"})||n.day(e,{width:"short",context:"formatting"})||n.day(e,{width:"narrow",context:"formatting"});case"EEEEE":return n.day(e,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(e,{width:"short",context:"formatting"})||n.day(e,{width:"narrow",context:"formatting"});default:return n.day(e,{width:"wide",context:"formatting"})||n.day(e,{width:"abbreviated",context:"formatting"})||n.day(e,{width:"short",context:"formatting"})||n.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,n,i){return e=Cn(e,n,i),e.setHours(0,0,0,0),e}incompatibleTokens=["D","i","e","c","t","T"]};var No=class extends E{priority=90;parse(e,r,n,i){let s=o=>{let a=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+a};switch(r){case"e":case"ee":return z($(r.length,e),s);case"eo":return z(n.ordinalNumber(e,{unit:"day"}),s);case"eee":return n.day(e,{width:"abbreviated",context:"formatting"})||n.day(e,{width:"short",context:"formatting"})||n.day(e,{width:"narrow",context:"formatting"});case"eeeee":return n.day(e,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(e,{width:"short",context:"formatting"})||n.day(e,{width:"narrow",context:"formatting"});default:return n.day(e,{width:"wide",context:"formatting"})||n.day(e,{width:"abbreviated",context:"formatting"})||n.day(e,{width:"short",context:"formatting"})||n.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,n,i){return e=Cn(e,n,i),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]};var Lo=class extends E{priority=90;parse(e,r,n,i){let s=o=>{let a=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+a};switch(r){case"c":case"cc":return z($(r.length,e),s);case"co":return z(n.ordinalNumber(e,{unit:"day"}),s);case"ccc":return n.day(e,{width:"abbreviated",context:"standalone"})||n.day(e,{width:"short",context:"standalone"})||n.day(e,{width:"narrow",context:"standalone"});case"ccccc":return n.day(e,{width:"narrow",context:"standalone"});case"cccccc":return n.day(e,{width:"short",context:"standalone"})||n.day(e,{width:"narrow",context:"standalone"});default:return n.day(e,{width:"wide",context:"standalone"})||n.day(e,{width:"abbreviated",context:"standalone"})||n.day(e,{width:"short",context:"standalone"})||n.day(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=6}set(e,r,n,i){return e=Cn(e,n,i),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]};function Zh(t,e,r){let n=A(t,r?.in),i=Gh(n,r),s=e-i;return io(n,s,r)}var jo=class extends E{priority=90;parse(e,r,n){let i=s=>s===0?7:s;switch(r){case"i":case"ii":return $(r.length,e);case"io":return n.ordinalNumber(e,{unit:"day"});case"iii":return z(n.day(e,{width:"abbreviated",context:"formatting"})||n.day(e,{width:"short",context:"formatting"})||n.day(e,{width:"narrow",context:"formatting"}),i);case"iiiii":return z(n.day(e,{width:"narrow",context:"formatting"}),i);case"iiiiii":return z(n.day(e,{width:"short",context:"formatting"})||n.day(e,{width:"narrow",context:"formatting"}),i);default:return z(n.day(e,{width:"wide",context:"formatting"})||n.day(e,{width:"abbreviated",context:"formatting"})||n.day(e,{width:"short",context:"formatting"})||n.day(e,{width:"narrow",context:"formatting"}),i)}}validate(e,r){return r>=1&&r<=7}set(e,r,n){return e=Zh(e,n),e.setHours(0,0,0,0),e}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]};var $o=class extends E{priority=80;parse(e,r,n){switch(r){case"a":case"aa":case"aaa":return n.dayPeriod(e,{width:"abbreviated",context:"formatting"})||n.dayPeriod(e,{width:"narrow",context:"formatting"});case"aaaaa":return n.dayPeriod(e,{width:"narrow",context:"formatting"});default:return n.dayPeriod(e,{width:"wide",context:"formatting"})||n.dayPeriod(e,{width:"abbreviated",context:"formatting"})||n.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,n){return e.setHours(Pn(n),0,0,0),e}incompatibleTokens=["b","B","H","k","t","T"]};var Mo=class extends E{priority=80;parse(e,r,n){switch(r){case"b":case"bb":case"bbb":return n.dayPeriod(e,{width:"abbreviated",context:"formatting"})||n.dayPeriod(e,{width:"narrow",context:"formatting"});case"bbbbb":return n.dayPeriod(e,{width:"narrow",context:"formatting"});default:return n.dayPeriod(e,{width:"wide",context:"formatting"})||n.dayPeriod(e,{width:"abbreviated",context:"formatting"})||n.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,n){return e.setHours(Pn(n),0,0,0),e}incompatibleTokens=["a","B","H","k","t","T"]};var Uo=class extends E{priority=80;parse(e,r,n){switch(r){case"B":case"BB":case"BBB":return n.dayPeriod(e,{width:"abbreviated",context:"formatting"})||n.dayPeriod(e,{width:"narrow",context:"formatting"});case"BBBBB":return n.dayPeriod(e,{width:"narrow",context:"formatting"});default:return n.dayPeriod(e,{width:"wide",context:"formatting"})||n.dayPeriod(e,{width:"abbreviated",context:"formatting"})||n.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,n){return e.setHours(Pn(n),0,0,0),e}incompatibleTokens=["a","b","t","T"]};var Fo=class extends E{priority=70;parse(e,r,n){switch(r){case"h":return q(B.hour12h,e);case"ho":return n.ordinalNumber(e,{unit:"hour"});default:return $(r.length,e)}}validate(e,r){return r>=1&&r<=12}set(e,r,n){let i=e.getHours()>=12;return i&&n<12?e.setHours(n+12,0,0,0):!i&&n===12?e.setHours(0,0,0,0):e.setHours(n,0,0,0),e}incompatibleTokens=["H","K","k","t","T"]};var qo=class extends E{priority=70;parse(e,r,n){switch(r){case"H":return q(B.hour23h,e);case"Ho":return n.ordinalNumber(e,{unit:"hour"});default:return $(r.length,e)}}validate(e,r){return r>=0&&r<=23}set(e,r,n){return e.setHours(n,0,0,0),e}incompatibleTokens=["a","b","h","K","k","t","T"]};var Bo=class extends E{priority=70;parse(e,r,n){switch(r){case"K":return q(B.hour11h,e);case"Ko":return n.ordinalNumber(e,{unit:"hour"});default:return $(r.length,e)}}validate(e,r){return r>=0&&r<=11}set(e,r,n){return e.getHours()>=12&&n<12?e.setHours(n+12,0,0,0):e.setHours(n,0,0,0),e}incompatibleTokens=["h","H","k","t","T"]};var Vo=class extends E{priority=70;parse(e,r,n){switch(r){case"k":return q(B.hour24h,e);case"ko":return n.ordinalNumber(e,{unit:"hour"});default:return $(r.length,e)}}validate(e,r){return r>=1&&r<=24}set(e,r,n){let i=n<=24?n%24:n;return e.setHours(i,0,0,0),e}incompatibleTokens=["a","b","h","H","K","t","T"]};var Ho=class extends E{priority=60;parse(e,r,n){switch(r){case"m":return q(B.minute,e);case"mo":return n.ordinalNumber(e,{unit:"minute"});default:return $(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,n){return e.setMinutes(n,0,0),e}incompatibleTokens=["t","T"]};var Wo=class extends E{priority=50;parse(e,r,n){switch(r){case"s":return q(B.second,e);case"so":return n.ordinalNumber(e,{unit:"second"});default:return $(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,n){return e.setSeconds(n,0),e}incompatibleTokens=["t","T"]};var zo=class extends E{priority=30;parse(e,r){let n=i=>Math.trunc(i*Math.pow(10,-r.length+3));return z($(r.length,e),n)}set(e,r,n){return e.setMilliseconds(n),e}incompatibleTokens=["t","T"]};var Ko=class extends E{priority=10;parse(e,r){switch(r){case"X":return Je(Ge.basicOptionalMinutes,e);case"XX":return Je(Ge.basic,e);case"XXXX":return Je(Ge.basicOptionalSeconds,e);case"XXXXX":return Je(Ge.extendedOptionalSeconds,e);default:return Je(Ge.extended,e)}}set(e,r,n){return r.timestampIsSet?e:F(e,e.getTime()-Nr(e)-n)}incompatibleTokens=["t","T","x"]};var Go=class extends E{priority=10;parse(e,r){switch(r){case"x":return Je(Ge.basicOptionalMinutes,e);case"xx":return Je(Ge.basic,e);case"xxxx":return Je(Ge.basicOptionalSeconds,e);case"xxxxx":return Je(Ge.extendedOptionalSeconds,e);default:return Je(Ge.extended,e)}}set(e,r,n){return r.timestampIsSet?e:F(e,e.getTime()-Nr(e)-n)}incompatibleTokens=["t","T","X"]};var Jo=class extends E{priority=40;parse(e){return _o(e)}set(e,r,n){return[F(e,n*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"};var Yo=class extends E{priority=20;parse(e){return _o(e)}set(e,r,n){return[F(e,n),{timestampIsSet:!0}]}incompatibleTokens="*"};var Qh={G:new yo,y:new vo,Y:new So,R:new xo,u:new ko,Q:new Eo,q:new To,M:new Oo,L:new Po,w:new Co,I:new Io,d:new Ro,D:new Ao,E:new Do,e:new No,c:new Lo,i:new jo,a:new $o,b:new Mo,B:new Uo,h:new Fo,H:new qo,K:new Bo,k:new Vo,m:new Ho,s:new Wo,S:new zo,X:new Ko,x:new Go,t:new Jo,T:new Yo};var xw=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,kw=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Ew=/^'([^]*?)'?$/,Tw=/''/g,Ow=/\S/,Pw=/[a-zA-Z]/;function Le(t,e,r,n){let i=()=>F(n?.in||r,NaN),s=fo(),o=n?.locale??s.locale??ji,a=n?.firstWeekContainsDate??n?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,c=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0;if(!e)return t?i():A(r,n?.in);let l={firstWeekContainsDate:a,weekStartsOn:c,locale:o},u=[new go(n?.in,r)],d=e.match(kw).map(y=>{let p=y[0];if(p in $i){let _=$i[p];return _(y,o.formatLong)}return y}).join("").match(xw),h=[];for(let y of d){!n?.useAdditionalWeekYearTokens&&uo(y)&&Mi(y,e,t),!n?.useAdditionalDayOfYearTokens&&lo(y)&&Mi(y,e,t);let p=y[0],_=Qh[p];if(_){let{incompatibleTokens:b}=_;if(Array.isArray(b)){let D=h.find(S=>b.includes(S.token)||S.token===p);if(D)throw new RangeError(`The format string mustn't contain \`${D.fullToken}\` and \`${y}\` at the same time`)}else if(_.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${y}\` and any other token at the same time`);h.push({token:p,fullToken:y});let w=_.run(t,y,o.match,l);if(!w)return i();u.push(w.setter),t=w.rest}else{if(p.match(Pw))throw new RangeError("Format string contains an unescaped latin alphabet character `"+p+"`");if(y==="''"?y="'":p==="'"&&(y=Cw(y)),t.indexOf(y)===0)t=t.slice(y.length);else return i()}}if(t.length>0&&Ow.test(t))return i();let f=u.map(y=>y.priority).sort((y,p)=>p-y).filter((y,p,_)=>_.indexOf(y)===p).map(y=>u.filter(p=>p.priority===y).sort((p,_)=>_.subPriority-p.subPriority)).map(y=>y[0]),m=A(r,n?.in);if(isNaN(+m))return i();let g={};for(let y of f){if(!y.validate(m,l))return i();let p=y.set(m,g,l);Array.isArray(p)?(m=p[0],Object.assign(g,p[1])):m=p}return m}function Cw(t){return t.match(Ew)[1].replace(Tw,"'")}function ef(t,e){let r=A(t,e?.in);return r.setSeconds(0,0),r}import{z as Wc}from"zod";var tf=["pos","kds","kiosk"],XD=Wc.enum(tf),Iw=[...tf,"restaurant_site","developer_dashboard","zorgo_site","backend"],rf=Wc.enum(Iw),Rw=["gateway","main_service","agent_service","background_workers"],ZD=Wc.enum(Rw);var Ui=()=>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 sf(t){let e=(t||"").replace(/\D/g,"");return e.length===11?`+${e}`:`+1${e}`}var tr=typeof globalThis.document<"u"&&globalThis.navigator?.product!=="ReactNative",nf={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function rr(){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(qc(),Hl(Fc)).default}catch{return nf}return nf}function Xo(t){return`(${t.join(",")})`}var zc=(i=>(i.Website="website",i.Kiosk="kiosk",i.Pos="pos",i.KitchenDisplay="kitchen_display",i))(zc||{});var rN={website:"Website",kiosk:"Kiosk",pos:"POS"},Et=class extends Error{constructor(e){super(e),this.name="VisibilityConditionError"}};function of(t){let e=t?.date??new Date,r=["su","m","t","w","th","f","sa"],n=e.getHours().toString().padStart(2,"0"),i=e.getMinutes().toString().padStart(2,"0");return{dayOfWeek:r[e.getDay()]??"m",currentTime:`${n}:${i}`,platform:t?.platform??"website"}}function Aw(t){if(t.version!==1)throw new Et("Unsupported visibility condition version.");cf(t.root)}function af(t,e){return Aw(t),Kc(t.root,e)}function cf(t){switch(t.type){case"group":if(t.children.length===0)throw new Et("Condition groups cannot be empty.");t.children.forEach(cf);return;case"constant":return;case"rule":Dw(t);return;default:throw new Et("Unknown visibility condition node.")}}function Dw(t){if(t.variable==="dayOfWeek"){if(!Array.isArray(t.value)||t.value.length===0)throw new Et("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 Et("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 Et("Between rules require a start and end time.");Qo(t.value.start),Qo(t.value.end);return}if(typeof t.value!="string")throw new Et("Time rules require a single time value.");Qo(t.value)}}function Kc(t,e){return t.type==="group"?t.operator==="and"?t.children.every(r=>Kc(r,e)):t.children.some(r=>Kc(r,e)):t.type==="constant"?t.value:Nw(t,e)}function Nw(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=Zo(e.currentTime);if(t.operator==="between"){let i=t.value,s=Zo(i.start),o=Zo(i.end);return r>=s&&r<=o}let n=Zo(t.value);switch(t.operator){case"before":return r<n;case"after":return r>n;case"on_or_before":return r<=n;case"on_or_after":return r>=n;default:return!1}}default:return!1}}function Zo(t){Qo(t);let e=t.split(":"),r=Number(e[0]),n=Number(e[1]);return r*60+n}function Qo(t){if(!/^\d{2}:\d{2}$/.test(t))throw new Et(`Invalid time "${t}". Use HH:mm format.`)}async function lf(t,e,r=hf(),n=!1){let i=await $w(t,e,r.categoryIds);if(i.length===0)return Jc([],[],[],[],[]);let s=await Mw(t,e,r.baseItemIds,i);if(s.length===0)return Jc([],[],i,[],[]);let o=await Fw(t,s,r.itemIds),a=await qw(t,o,n),c=await Bw(t,s,i,o,n);return Jc(o,s,i,a,c)}function uf(t,e){let r=new Map,n=(o,a)=>a.promotion_type_id===1?Math.max(0,Math.floor(o*(1-a.discount_value/100))):a.promotion_type_id===2?Math.max(0,o-a.discount_value):o,i=t.items.map(o=>{let c=e.find(u=>{if(!u.is_active||u.id==null||!u.discount_target_ids?.length||!u.min_purchase_quantity)return!1;let d=u.discount_target_ids;return u.discount_target_type==="category"&&d.includes(o.category_id)||u.discount_target_type==="item"&&d.includes(o.base_item_id)})?.id,l=o.variants.map(u=>{let d,h=u.price;for(let f of e){if(!f.is_active||f.id==null||!f.discount_target_ids?.length||f.min_purchase_amount||f.min_purchase_quantity)continue;let m=f.discount_target_ids;if(!(f.discount_target_type==="category"&&m.includes(o.category_id)||f.discount_target_type==="item"&&m.includes(o.base_item_id)||f.discount_target_type==="item_variant"&&m.includes(u.item_id)))continue;let y=n(u.price,f);y<h&&(d=f,h=y)}return!d||h>=u.price?u:(c??=d.id,d.discount_target_type==="category"&&r.set(o.category_id,d.id),{...u,active_promo_id:d.id,display_price:h})});return{...o,variants:l,active_promo_id:c}}),s=t.categories.map(o=>{let{active_promo_id:a,...c}=o,l=r.get(c.category_id);return l==null?c:{...c,active_promo_id:l}});return{...t,items:i,categories:s}}async function df(t,e,r,n){let i=await Lw(t,e),s=await jw(t,e,n);if(s.length===0)return hf();let o=Gc(s,p=>p.category_id),a=Gc(s,p=>p.base_item_id),c=Gc(s,p=>p.item_id),l=new Map(i.baseItems.map(p=>[p.base_item_id,p])),u=new Map(i.items.map(p=>[p.item_id,p])),d=p=>o.get(p)!=="exclude",h=p=>{let _=a.get(p);if(_==="include")return!0;if(_==="exclude")return!1;let b=l.get(p)?.category_id;return b==null||d(b)},f=p=>{let _=c.get(p);if(_==="include")return!0;if(_==="exclude")return!1;let b=u.get(p);return b?.base_item_id==null?!0:h(b.base_item_id)},m=new Set(i.items.filter(p=>f(p.item_id)).map(p=>p.item_id)),g=new Set(i.baseItems.filter(p=>h(p.base_item_id)).map(p=>p.base_item_id));for(let p of i.items)m.has(p.item_id)&&p.base_item_id!=null&&g.add(p.base_item_id);let y=new Set(i.categories.filter(p=>d(p.category_id)).map(p=>p.category_id));for(let p of i.baseItems)g.has(p.base_item_id)&&y.add(p.category_id);return{categoryIds:i.categories.map(p=>p.category_id).filter(p=>!y.has(p)),baseItemIds:i.baseItems.map(p=>p.base_item_id).filter(p=>!g.has(p)),itemIds:i.items.map(p=>p.item_id).filter(p=>!m.has(p))}}function hf(){return{categoryIds:[],baseItemIds:[],itemIds:[]}}async function Lw(t,e){let{data:r,error:n}=await t.from("categories").select("category_id").eq("franchise_id",e);if(n)throw n;let{data:i,error:s}=await t.from("base_items").select("base_item_id, category_id").eq("franchise_id",e);if(s)throw s;let o=(i??[]).map(l=>l.base_item_id),{data:a,error:c}=o.length>0?await t.from("items").select("item_id, base_item_id").in("base_item_id",o):{data:[],error:null};if(c)throw c;return{categories:r??[],baseItems:i??[],items:a??[]}}async function jw(t,e,r){let{data:n,error:i}=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(i||!n)return[];let s=of({platform:r});return n.filter(o=>{let a=o.visibility_condition_groups;if(!a?.condition||a.platform!==s.platform)return!1;try{return af(a.condition,s)}catch{return!1}})}function Gc(t,e){let r=new Map;for(let n of t){let i=e(n);i!=null&&r.set(i,[...r.get(i)??[],n.effect])}return new Map(Array.from(r.entries()).map(([n,i])=>[n,i.includes("exclude")?"exclude":"include"]))}async function $w(t,e,r){let n=t.from("categories").select("*").eq("franchise_id",e);r&&r.length>0&&(n=n.not("category_id","in",Xo(r)));let{data:i,error:s}=await n;if(s)throw s;return i??[]}async function Mw(t,e,r,n){if(n&&n.length===0)return[];let i=t.from("base_items").select("*").eq("franchise_id",e);r&&r.length>0&&(i=i.not("base_item_id","in",Xo(r))),n&&(i=i.in("category_id",n.map(l=>l.category_id)));let{data:s,error:o}=await i;if(o)throw o;if(!s||s.length===0)return[];let{data:a,error:c}=await t.from("base_item_images").select("*").in("base_item_id",s.map(l=>l.base_item_id)).order("sort_index",{ascending:!0}).order("image_id",{ascending:!0});if(c)throw c;return Uw(s,a??[])}function Uw(t,e){let r=new Map;for(let n of e){let i=r.get(n.base_item_id);i?i.push(n):r.set(n.base_item_id,[n])}return t.map(n=>({...n,images:r.get(n.base_item_id)??[]}))}async function Fw(t,e,r){if(e&&e.length===0)return[];let n=t.from("items").select("*, portion_scheme:portion_schemes(*)").in("base_item_id",e.map(o=>o.base_item_id));r&&r.length>0&&(n=n.not("item_id","in",Xo(r)));let{data:i,error:s}=await n;if(s)throw s;return i??[]}async function qw(t,e,r=!1){let n=e.length>0&&typeof e[0]=="number"?e:e.map(o=>o.item_id);if(n.length===0)return[];let i=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(i).in("item_id",n).throwOnError();return s.map(o=>({servings_per_item:o.servings_per_item,is_base:o.components?.is_base,serving_weight:o.components?.serving_weight,component_type_id:o.components?.component_type_id,id:o.components?.id,name:o.components?.name,item_id:o.item_id,...r&&{behavior:o.component_quantity_behaviors??void 0}}))}function ff(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})),...(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}))]}async function Bw(t,e,r,n,i=!1,s){let o=n?.map(g=>g.item_id)??[],a=e?.map(g=>g.base_item_id)??[],c=r?.map(g=>g.category_id)??[];if(o.length===0&&a.length===0&&c.length===0&&!s?.length)return[];let l=[`item_id.in.(${o.length>0?o.join(","):-1})`,`base_item_id.in.(${a.length>0?a.join(","):-1})`,`category_id.in.(${c.length>0?c.join(","):-1})`,...s?.length?[`rule_id.in.(${s.join(",")})`]:[]].join(","),u=i?"component_quantity_behaviors(headcount_threshold, starting_amount, step_size, step_interval, maximum)":null,d=["component_id, upcharge_price, components(name, description, serving_weight)",u].filter(Boolean).join(", "),h=["item_id, upcharge_price, items(item_id, name, description)",u].filter(Boolean).join(", "),{data:f,error:m}=await t.from("item_rules").select(`
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(`
136
141
  rule_id,
137
142
  category_id,
138
143
  item_id,
@@ -142,14 +147,15 @@ https://supabase.com/dashboard/project/_/settings/api`);let{storage:i}=Dc({...r,
142
147
  max_selection,
143
148
  included_quantity,
144
149
  is_portionable,
150
+ sort_index,
145
151
  rule_components (${d}),
146
- rule_items (${h})
147
- `).or(l);if(m)throw m;return(f??[]).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,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,...i&&{behavior:y.component_quantity_behaviors??void 0}})),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,...i&&{behavior:y.component_quantity_behaviors??void 0}}))}))}function Jc(t,e,r,n,i){let s={items:[],categories:[],rules:i,components:n};return s.items=e.map(o=>{let a=i.filter(l=>l.category_id===o.category_id),c=i.filter(l=>l.base_item_id===o.base_item_id);return{is_catering:o.per_person!==null,...o,variants:t.filter(l=>l.base_item_id===o.base_item_id).map(l=>({...l,components:n.filter(u=>u.item_id===l.item_id),rules:[...a,...c,...i.filter(u=>u.item_id===l.item_id)]})),rules:c}}),s.categories=r.map(o=>({...o,rules:i.filter(a=>a.category_id===o.category_id)})),s}function Fi(t,e,r,n=new Date){return t.filter(i=>{if(i.start_date&&new Date(i.start_date)>n||i.end_date&&new Date(i.end_date)<n||i.platforms&&i.platforms.length>0&&!i.platforms.includes(e)||!i.is_automatic)return!1;if(i.location_id!=null&&r!==void 0){if(i.location_id!==r)return!1}else if(i.location_id!=null&&r===void 0)return!1;if(i.schedule_details_json){let{interval:s,days:o,start_time:a,end_time:c}=i.schedule_details_json;if(s==="weekly"&&o&&!o.includes(ho(n)+1))return!1;let l=lt(n);if(a&&Ie(n,Le(a,"HH:mm",l))||c&&kt(n,Le(c,"HH:mm",l)))return!1}return!0})}var Yc=null;function mf(t){Yc=t}async function Vw(){if(!Yc)throw new Error("apiFetch called before registerTokenProvider");return Yc()}async function jt(t,e={}){let r=await Vw(),n={...e.headers};return n["x-request-id"]||(n["x-request-id"]=Ui()),fetch(`${Xs}${t}`,{...e,headers:{"Content-Type":"application/json",...r&&{Authorization:`Bearer ${r}`},...n}})}function $t(t){let[e,r]=t.split("/").map(Number);return{index:e,divisions:r}}function ea(t){return t?1/$t(t).divisions:1}function In(t,e){return e?`${t}@${e}`:t}function ut(t){let e=t.indexOf("@");return e===-1?{baseKey:t,portion:null}:{baseKey:t.slice(0,e),portion:t.slice(e+1)}}function dN(t,e){return Math.ceil(t/e)}function hN(t){let{min_divisions:e,max_divisions:r}=t;return Array.from({length:r-e+1},(n,i)=>e+i)}var Hw={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 fN(t,e){if(!t)return"Whole";let{index:r,divisions:n}=$t(t);return Hw[e.geometry][n]?.[r-1]??`Part ${r} of ${n}`}function gf(t,e,r){let n=e[t]??r,i=Object.entries(e).flatMap(([a,c])=>{let l=ut(a);return l.baseKey===t&&l.portion?[{portion:l.portion,value:c}]:[]});if(!i.length)return[{portion:null,value:n}];let{divisions:s}=$t(i[0].portion),o=Array.from({length:s},(a,c)=>{let l=`${c+1}/${s}`;return{portion:l,value:i.find(u=>u.portion===l)?.value??n}});return o.every(a=>a.value===o[0].value)?[{portion:null,value:o[0].value}]:o}function Xc(t){return t.reduce((e,r)=>e+ea(ut(r).portion),0)}function yf(t,e,r){let n=new Map,i=new Map;for(let s of t){let{baseKey:o,portion:a}=ut(s);i.has(o)||i.set(o,i.size),n.set(s,i.get(o)<r?0:Math.ceil(e(o)*ea(a)))}return n}function _f(t,e){let{index:r,divisions:n}=$t(t);if(n===e)return[t];if(e%n===0){let i=e/n,s=(r-1)*i+1;return Array.from({length:i},(o,a)=>`${s+a}/${e}`)}return n%e===0?[`${Math.ceil(r*e/n)}/${e}`]:null}function Ww(t){if(!t)return"Whole";let{index:e,divisions:r}=$t(t);return`Section ${e} of ${r}`}var zw={radial:"\u25CF",grid:"\u25A0",linear:"\u25A0",count:null},Kw={radial:{2:["\u25D0","\u25D1"]},grid:{2:["\u25E7","\u25E8"]},linear:{2:["\u25E7","\u25E8"]},count:{}};function Gw(t,e){if(!e)return null;if(!t)return zw[e];let{index:r,divisions:n}=$t(t);return Kw[e][n]?.[r-1]??null}function mN(t){let e=t.portion_scheme?.geometry,r=new Map,n=s=>{let o=s??"",a=r.get(o);return a||r.set(o,a={selections:[],removals:[],additions:[]}),a};for(let s of t.selections??[])for(let o of s.selections){let{selections:a}=n(o.portion),c=a.find(l=>l.rule_id===s.rule_id);c||a.push(c={...s,selections:[]}),c.selections.push(o)}for(let s of t.components??[])s.quantity_servings<=0?n(s.portion).removals.push(s):s.portion&&n(s.portion).additions.push(s);let i=s=>s?$t(s).index:-1;return[...r.entries()].sort(([s],[o])=>i(s)-i(o)).map(([s,o])=>({portion:s||null,label:Ww(s||null),glyph:Gw(s||null,e),...o}))}var pf=t=>Math.round(t*100)/100;function pN(t,e,r=48){if(e===1)return`M 50 ${50-r} A ${r} ${r} 0 1 0 49.9 ${50-r} Z`;let n=2*Math.PI/e,i=-Math.PI/2-(t-1)*n,s=i-n,o=a=>`${pf(50+r*Math.cos(a))} ${pf(50+r*Math.sin(a))}`;return`M 50 50 L ${o(i)} A ${r} ${r} 0 ${n>Math.PI?1:0} 0 ${o(s)} Z`}function bf(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 wf(t){switch(t){case 1:return"Kiosk";case 2:return"Website";case 3:return"POS";default:return""}}function vf(t){let{max_selection:e,min_selection:r}=t,n=e!=null&&e!==1/0,i=t.included_quantity??0,s=n?r===e?`Choose ${r}`:r>0?`Choose ${r} to ${e}`:`Choose up to ${e}`:r>0?`Choose at least ${r}`:"Choose any";return i>0?`${s}. ${i} included`:s}function Zc(t,e,r,n){let i=n/2,s=Math.log(99)/(n-i),o=1/(1+Math.exp(-s*(e-i))),a=1/(1+Math.exp(s*i)),c=(o-a)/(1-a);return t*(1-r*c)}var Jw=.06;var Yw=.02,Xw=.015;function Sf(t,e,r=!1){return e!==2?0:Math.floor(r?Xw*t:Yw*t)}function Rn(t,e=!1){let r=e?t.display_price||0:t.price||0,n=t.selections?.reduce((s,o)=>s+o.selections.reduce((a,c)=>a+c.upcharge,0),0)||0;return(r+n)*t.quantity}function An({order:t}){return t.items.filter(e=>e.status!=="removed").reduce((e,r)=>e+Rn(r),0)}function Mt(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 n=wf(e.method_id).toLowerCase();if(t.platforms&&t.platforms.length>0&&!t.platforms.includes(n)||t.location_id&&t.location_id!==e.location_id||t.start_date&&Ie(r,new Date(t.start_date))||t.end_date&&kt(r,new Date(t.end_date)))return 0;if(t.schedule_details_json){let{interval:d,days:h,start_time:f,end_time:m}=t.schedule_details_json;if(d==="weekly"&&h&&!h.includes(ho(r)+1))return 0;let g=lt(r);if(f){let y=Le(f,"HH:mm",g);if(Ie(r,y))return 0}if(m){let y=Le(m,"HH:mm",g);if(kt(r,y))return 0}}let i=e.is_catering||e.items.some(d=>d.is_catering);if(t.is_catering_only&&!i)return 0;let s=An({order:e});if(t.min_purchase_amount&&s<t.min_purchase_amount)return 0;let o=e.items.reduce((d,h)=>d+h.quantity,0),a=t.is_catering_only&&t.min_purchase_quantity;if(!a&&t.min_purchase_quantity&&o<t.min_purchase_quantity)return 0;let c=e.items,l=s;if(t.discount_target_type&&t.discount_target_ids?.length&&(c=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),l=c.reduce((d,h)=>d+Rn(h),0)),c.length===0)return 0;let u=0;if(a&&t.promotion_type_id===1){let d=c.reduce((f,m)=>f+m.quantity,0),h=Zc(l,d,t.discount_value/100,t.min_purchase_quantity);u=l-h}else t.promotion_type_id===1?u=l*(t.discount_value/100):t.promotion_type_id===2&&(u=t.discount_value);return Math.min(Math.floor(u),l)}function ta(t){return t.is_automatic?t.discount_target_type?"item":"order":"private"}function xf(t,e,r){if(!e.length)return{discount:0};let n,i=0;for(let l of e){if(ta(l)!=="order")continue;let u=Mt(l,t,r);u>i&&(i=u,n=l)}let s=t.items.filter(l=>l.status!=="removed"),o=e.filter(l=>ta(l)==="item"),a=[];o.length>0&&s.forEach((l,u)=>{let d=0,h;for(let f of o){let m={...t,items:[l]},g=Mt(f,m,r);g>d&&(d=g,h=f.id)}d>0&&h!==void 0&&a.push({itemIndex:u,itemId:l.item_id,promotionId:h,discount:d})});let c=a.reduce((l,u)=>l+u.discount,0);return i===0&&c===0?{discount:0}:i>=c?{discount:i,orderPromo:n}:{discount:c,itemDiscounts:a}}function kf(t,e,r=new Date){if(e)try{let i=Mt(e,t,r);return{name:e.name,discount:i}}catch{return{name:e.name,discount:0}}let n=t.items.reduce((i,s)=>i+(s.discount_amount??0),0);return n>0?{name:"Item discounts",discount:n}:{discount:0}}function Ef(t){return Math.round(t*Jw)}import{create as Sv}from"zustand";function Qc(t,e,r){let n=fo(),i=ev(t,r.timeZone,r.locale??n.locale);return"formatToParts"in i?Zw(i,e):Qw(i,e)}function Zw(t,e){let r=t.formatToParts(e);for(let n=r.length-1;n>=0;--n)if(r[n].type==="timeZoneName")return r[n].value}function Qw(t,e){let r=t.format(e).replace(/\u200E/g,""),n=/ [\w-+ ]+$/.exec(r);return n?n[0].substr(1):""}function ev(t,e,r){return new Intl.DateTimeFormat(r?[r.code,"en-US"]:void 0,{timeZone:e,timeZoneName:t})}function Of(t,e){let r=sv(e);return"formatToParts"in r?rv(r,t):nv(r,t)}var tv={year:0,month:1,day:2,hour:3,minute:4,second:5};function rv(t,e){try{let r=t.formatToParts(e),n=[];for(let i=0;i<r.length;i++){let s=tv[r[i].type];s!==void 0&&(n[s]=parseInt(r[i].value,10))}return n}catch(r){if(r instanceof RangeError)return[NaN];throw r}}function nv(t,e){let r=t.format(e),n=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(r);return[parseInt(n[3],10),parseInt(n[1],10),parseInt(n[2],10),parseInt(n[4],10),parseInt(n[5],10),parseInt(n[6],10)]}var el={},Tf=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")),iv=Tf==="06/25/2014, 00:00:00"||Tf==="\u200E06\u200E/\u200E25\u200E/\u200E2014\u200E \u200E00\u200E:\u200E00\u200E:\u200E00";function sv(t){return el[t]||(el[t]=iv?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"})),el[t]}function qi(t,e,r,n,i,s,o){let a=new Date(0);return a.setUTCFullYear(t,e,r),a.setUTCHours(n,i,s,o),a}var Pf=36e5,ov=6e4,tl={timezone:/([Z+-].*)$/,timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Ut(t,e,r){if(!t)return 0;let n=tl.timezoneZ.exec(t);if(n)return 0;let i,s;if(n=tl.timezoneHH.exec(t),n)return i=parseInt(n[1],10),Cf(i)?-(i*Pf):NaN;if(n=tl.timezoneHHMM.exec(t),n){i=parseInt(n[2],10);let o=parseInt(n[3],10);return Cf(i,o)?(s=Math.abs(i)*Pf+o*ov,n[1]==="+"?-s:s):NaN}if(lv(t)){e=new Date(e||Date.now());let o=r?e:av(e),a=rl(o,t);return-(r?a:cv(e,a,t))}return NaN}function av(t){return qi(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds())}function rl(t,e){let r=Of(t,e),n=qi(r[0],r[1]-1,r[2],r[3]%24,r[4],r[5],0).getTime(),i=t.getTime(),s=i%1e3;return i-=s>=0?s:1e3+s,n-i}function cv(t,e,r){let i=t.getTime()-e,s=rl(new Date(i),r);if(e===s)return e;i-=s-e;let o=rl(new Date(i),r);return s===o?s:Math.max(s,o)}function Cf(t,e){return-23<=t&&t<=23&&(e==null||0<=e&&e<=59)}var If={};function lv(t){if(If[t])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:t}),If[t]=!0,!0}catch{return!1}}var uv=60*1e3,Af={X:function(t,e,r){let n=nl(r.timeZone,t);if(n===0)return"Z";switch(e){case"X":return Rf(n);case"XXXX":case"XX":return Dn(n);default:return Dn(n,":")}},x:function(t,e,r){let n=nl(r.timeZone,t);switch(e){case"x":return Rf(n);case"xxxx":case"xx":return Dn(n);default:return Dn(n,":")}},O:function(t,e,r){let n=nl(r.timeZone,t);switch(e){case"O":case"OO":case"OOO":return"GMT"+dv(n,":");default:return"GMT"+Dn(n,":")}},z:function(t,e,r){switch(e){case"z":case"zz":case"zzz":return Qc("short",t,r);default:return Qc("long",t,r)}}};function nl(t,e){let r=t?Ut(t,e,!0)/uv:e?.getTimezoneOffset()??0;if(Number.isNaN(r))throw new RangeError("Invalid time zone specified: "+t);return r}function ra(t,e){let r=t<0?"-":"",n=Math.abs(t).toString();for(;n.length<e;)n="0"+n;return r+n}function Dn(t,e=""){let r=t>0?"-":"+",n=Math.abs(t),i=ra(Math.floor(n/60),2),s=ra(Math.floor(n%60),2);return r+i+e+s}function Rf(t,e){return t%60===0?(t>0?"-":"+")+ra(Math.abs(t)/60,2):Dn(t,e)}function dv(t,e=""){let r=t>0?"-":"+",n=Math.abs(t),i=Math.floor(n/60),s=n%60;return s===0?r+String(i):r+String(i)+e+ra(s,2)}function il(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 na=/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/;var sl=36e5,Df=6e4,hv=2,Te={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:na};function Ye(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?hv: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 n=fv(t),{year:i,restDateString:s}=mv(n.date,r),o=pv(s,i);if(o===null||isNaN(o.getTime()))return new Date(NaN);if(o){let a=o.getTime(),c=0,l;if(n.time&&(c=gv(n.time),c===null||isNaN(c)))return new Date(NaN);if(n.timeZone||e.timeZone){if(l=Ut(n.timeZone||e.timeZone,new Date(a+c)),isNaN(l))return new Date(NaN)}else l=il(new Date(a+c)),l=il(new Date(a+c+l));return new Date(a+c+l)}else return new Date(NaN)}function fv(t){let e={},r=Te.dateTimePattern.exec(t),n;if(r?(e.date=r[1],n=r[3]):(r=Te.datePattern.exec(t),r?(e.date=r[1],n=r[2]):(e.date=null,n=t)),n){let i=Te.timeZone.exec(n);i?(e.time=n.replace(i[1],""),e.timeZone=i[1].trim()):e.time=n}return e}function mv(t,e){if(t){let r=Te.YYY[e],n=Te.YYYYY[e],i=Te.YYYY.exec(t)||n.exec(t);if(i){let s=i[1];return{year:parseInt(s,10),restDateString:t.slice(s.length)}}if(i=Te.YY.exec(t)||r.exec(t),i){let s=i[1];return{year:parseInt(s,10)*100,restDateString:t.slice(s.length)}}}return{year:null}}function pv(t,e){if(e===null)return null;let r,n,i;if(!t||!t.length)return r=new Date(0),r.setUTCFullYear(e),r;let s=Te.MM.exec(t);if(s)return r=new Date(0),n=parseInt(s[1],10)-1,Lf(e,n)?(r.setUTCFullYear(e,n),r):new Date(NaN);if(s=Te.DDD.exec(t),s){r=new Date(0);let o=parseInt(s[1],10);return bv(e,o)?(r.setUTCFullYear(e,0,o),r):new Date(NaN)}if(s=Te.MMDD.exec(t),s){r=new Date(0),n=parseInt(s[1],10)-1;let o=parseInt(s[2],10);return Lf(e,n,o)?(r.setUTCFullYear(e,n,o),r):new Date(NaN)}if(s=Te.Www.exec(t),s)return i=parseInt(s[1],10)-1,jf(i)?Nf(e,i):new Date(NaN);if(s=Te.WwwD.exec(t),s){i=parseInt(s[1],10)-1;let o=parseInt(s[2],10)-1;return jf(i,o)?Nf(e,i,o):new Date(NaN)}return null}function gv(t){let e,r,n=Te.HH.exec(t);if(n)return e=parseFloat(n[1].replace(",",".")),ol(e)?e%24*sl:NaN;if(n=Te.HHMM.exec(t),n)return e=parseInt(n[1],10),r=parseFloat(n[2].replace(",",".")),ol(e,r)?e%24*sl+r*Df:NaN;if(n=Te.HHMMSS.exec(t),n){e=parseInt(n[1],10),r=parseInt(n[2],10);let i=parseFloat(n[3].replace(",","."));return ol(e,r,i)?e%24*sl+r*Df+i*1e3:NaN}return null}function Nf(t,e,r){e=e||0,r=r||0;let n=new Date(0);n.setUTCFullYear(t,0,4);let i=n.getUTCDay()||7,s=e*7+r+1-i;return n.setUTCDate(n.getUTCDate()+s),n}var yv=[31,28,31,30,31,30,31,31,30,31,30,31],_v=[31,29,31,30,31,30,31,31,30,31,30,31];function $f(t){return t%400===0||t%4===0&&t%100!==0}function Lf(t,e,r){if(e<0||e>11)return!1;if(r!=null){if(r<1)return!1;let n=$f(t);if(n&&r>_v[e]||!n&&r>yv[e])return!1}return!0}function bv(t,e){if(e<1)return!1;let r=$f(t);return!(r&&e>366||!r&&e>365)}function jf(t,e){return!(t<0||t>52||e!=null&&(e<0||e>6))}function ol(t,e,r){return!(t<0||t>=25||e!=null&&(e<0||e>=60)||r!=null&&(r<0||r>=60))}var wv=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function al(t,e,r={}){e=String(e);let n=e.match(wv);if(n){let i=Ye(r.originalDate||t,r);e=n.reduce(function(s,o){if(o[0]==="'")return s;let a=s.indexOf(o),c=s[a-1]==="'",l=s.replace(o,"'"+Af[o[0]](i,o,r)+"'");return c?l.substring(0,a-1)+l.substring(a+1):l},e)}return Ke(t,e,r)}function Bi(t,e,r){t=Ye(t,r);let n=Ut(e,t,!0),i=new Date(t.getTime()-n),s=new Date(0);return s.setFullYear(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate()),s.setHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),s}function ia(t,e,r,n){return n={...n,timeZone:e,originalDate:t},al(Bi(t,e,{timeZone:n.timeZone}),r,n)}function cl(t,e,r){if(typeof t=="string"&&!t.match(na))return Ye(t,{...r,timeZone:e});t=Ye(t,r);let n=qi(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()).getTime(),i=Ut(e,new Date(n));return new Date(n+i)}var ll="America/New_York",vv=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function Mf(t,e){if(e.force_close)return!0;let r=vv[t.getDay()],n=e[`${r}_open`],i=e[`${r}_close`];if(!n||!i)return!0;let s=ia(t,ll,"yyyy-MM-dd"),o=n.replace(/[+-].*$/,"").trim(),a=i.replace(/[+-].*$/,"").trim(),c=`${s}T${o}`,l=`${s}T${a}`,u=Ye(c,{timeZone:ll}),d=Ye(l,{timeZone:ll}),h=!Ie(t,u),f=Ie(t,d);return!(h&&f)}import{devtools as xv,persist as kv,createJSONStorage as Ev,subscribeWithSelector as Tv}from"zustand/middleware";async function Uf(t,e){let r=e||j,{data:n,error:i}=await r.from("permissions").select("franchise_id, location_id").eq("user_id",t);if(i)throw i;let s=new Set(n?.map(h=>h.franchise_id).filter(h=>h!=null)??[]),o=new Set(n?.filter(h=>h.location_id===null&&h.franchise_id!==null).map(h=>h.franchise_id)),a=n?.map(h=>h.location_id).filter(h=>h!=null)??[],{data:c,error:l}=await r.from("franchises").select("*").in("franchise_id",Array.from(s));if(l)throw l;let{data:u,error:d}=await r.from("locations").select("*").or(`location_id.in.(${a.join(",")}), franchise_id.in.(${Array.from(o).join(",")})`);if(d)throw d;return{franchises:c,locations:u}}async function Ff(t,e){let r=e||j,{data:n,error:i}=await r.from("franchises").select("*").eq("franchise_id",t);if(i)throw i;let{data:s,error:o}=await r.from("locations").select("*").eq("franchise_id",t).or("status.is.null,status.neq.permanently_closed");if(o)throw o;return{franchises:n,locations:s}}async function qf(t,e,r){let n=r||j,i={...e,...t},{data:s,error:o}=await n.from("locations").update(i).eq("location_id",e.location_id).select().single();if(o)throw o;return s}async function Bf(t,e,r){let n=r||j,{data:i,error:s}=await n.from("locations").update({force_close:e}).eq("location_id",t);if(s)throw s;return i}async function Vf(t,e){let r=e||j,{data:n,error:i}=await r.from("locations").insert(t).select().single();if(i)throw i;return n}async function Hf(t,e){let r=e||j,{data:n,error:i}=await r.from("locations").delete().eq("location_id",t);if(i)throw i;return n}async function Wf(t,e,r){let n=r||j,i={...t,...e},{data:s,error:o}=await n.from("franchises").update(i).eq("franchise_id",t.franchise_id).select().single();if(o)throw o;return s}function zf(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 Vi=Sv()(Tv(kv(xv((t,e)=>({selectedLocation:null,franchises:[],locations:[],userId:null,navScope:"franchise",initialize:async({userId:r,token:n,locationId:i})=>{if(r&&t({userId:r}),i){let{data:a}=await j.from("locations").select("*").eq("location_id",i).throwOnError().single(),{data:c}=await j.from("franchises").select("*").eq("franchise_id",a.franchise_id).throwOnError().single();t({selectedLocation:a,franchiseId:a.franchise_id,locations:[a],franchises:[c]});return}else if(n){let c=zf(n).franchise_ids?.[0],{locations:l,franchises:u}=await Ff(c),d=e().selectedLocation,h=d?l.find(f=>f.location_id===d.location_id)??null:null;t({locations:l,franchises:u,franchiseId:c,selectedLocation:h});return}else if(r){let{locations:a,franchises:c}=await Uf(r);t({locations:a,franchises:c})}let o=e().locations[0];t({selectedLocation:o,...o&&{franchiseId:o.franchise_id}})},hydrate:({franchises:r,locations:n})=>t({franchises:r??[],locations:n??[]},!1,"hydrate"),getCurrentLocation:()=>e().selectedLocation,getIsCurrentLocationOpen:()=>{let r=e().selectedLocation;return r?!Mf(new Date,r):!1},getAllLocations:()=>e().locations,setForceClose:async(r,n)=>{await Bf(n,r),t(i=>({locations:i.locations.map(s=>s.location_id===n?{...s,force_close:r}:s),selectedLocation:i.selectedLocation?.location_id===n?{...i.selectedLocation,force_close:r}:i.selectedLocation}))},setSelectedLocation:r=>{t({selectedLocation:r}),t({franchiseId:r.franchise_id})},setFranchiseId:r=>{if(t({franchiseId:r}),e().selectedLocation?.franchise_id!==r){let n=e().locations.find(i=>i.franchise_id===r&&i.location_id!==0)??e().locations.find(i=>i.franchise_id===r)??null;t({selectedLocation:n})}},enterFranchise:r=>{let n=e();if(t({franchiseId:r,navScope:"franchise"}),n.selectedLocation?.franchise_id!==r){let i=n.locations.find(s=>s.franchise_id===r&&s.location_id!==0)??n.locations.find(s=>s.franchise_id===r)??null;t({selectedLocation:i})}},enterLocation:r=>{t({selectedLocation:r,franchiseId:r.franchise_id,navScope:"location"})},exitToFranchise:()=>{t({navScope:"franchise"})},exitToAccount:()=>{t({navScope:"account"})},updateLocation:async(r,n)=>{await qf(r,n),t(i=>({locations:i.locations.map(s=>s.location_id===n.location_id?{...s,...r}:s)}))},createLocation:async r=>{let n=await Vf(r);return t(i=>({locations:[...i.locations,n]})),n},deleteLocation:async r=>{await Hf(r),t(n=>({locations:n.locations.filter(i=>i.location_id!==r)}))},updateFranchise:async(r,n)=>{let i=await Wf(r,n);return t(s=>({franchises:s.franchises.map(o=>o.franchise_id===r.franchise_id?i:o)})),i}})),{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:Ev(()=>rr()),skipHydration:tr,partialize:t=>({selectedLocation:t.selectedLocation,franchises:t.franchises,locations:t.locations,userId:t.userId,franchiseId:t.franchiseId,navScope:t.navScope})}))),H=Vi;import{create as Ov}from"zustand";import{immer as Pv}from"zustand/middleware/immer";import{devtools as Cv}from"zustand/middleware";async function Kf(t){let{data:e,error:r}=await j.from("promotions").select("*").eq("franchise_id",t);if(r)throw r;return e}async function Gf(t,e="website",r){let{data:n,error:i}=await j.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",t);if(i)throw i;let s=Fi(n,e,r);return{all:n,active:s}}async function Jf(t,e){let{data:r,error:n}=await j.from("promotions").select("*").eq("promo_code",t).eq("franchise_id",e).eq("is_active",!0).single();return n||!r?null:r}async function Yf(t){let{data:e,error:r}=await j.from("promotions").insert(t).select("*").single();if(r)throw r;return e}async function Xf(t){let{data:e,error:r}=await j.from("promotions").update(t).eq("id",t.id).select("*").single();if(r)throw r;return e}async function Zf(t){let{data:e,error:r}=await j.from("promotions").delete().eq("id",t).select("*").single();if(r)throw r;e||console.log("No promotion deleted")}async function Qf(t){let{data:e,error:r}=await j.from("franchise_marketing").select("personal_marketer").eq("franchise_id",t).maybeSingle();if(r)throw r;return e?.personal_marketer??!1}async function em(t,e){let{error:r}=await j.from("franchise_marketing").upsert({franchise_id:t,personal_marketer:e},{onConflict:"franchise_id"});if(r)throw r;let{error:n}=await j.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(n)throw n}async function tm(t,e=10){let{data:r,error:n}=await j.from("personal_marketer_runs").select("*").eq("franchise_id",t).order("created_at",{ascending:!1}).limit(e);if(n)throw n;return r}var Iv=Ov()(Cv(Pv((t,e)=>({logLevel:1,promotions:[],allPromotions:[],activePromotions:[],personalMarketerEnabled:!1,recentRuns:[],recentOutboundMessages:[],getPromotions:async r=>{let n=await Kf(r);return t({promotions:n},!1,"getPromotions"),n},getActivePromotions:async(r,n,i="website")=>{let{active:s,all:o}=await Gf(r,i,n);return t({allPromotions:o,activePromotions:s},!1,"getActivePromotions"),s},getPromotionByCode:async(r,n)=>await Jf(r,n),addPromotion:async r=>{let n=await Yf(r);t(i=>{i.promotions.push(n)})},updatePromotion:async r=>{let n=await Xf(r);t(i=>{i.promotions=i.promotions.map(s=>s.id===n.id?n:s)})},deletePromotion:async r=>{await Zf(r),t(n=>{n.promotions=n.promotions.filter(i=>i.id!==r)})},getPersonalMarketerSettings:async()=>{let r=Vi.getState().franchiseId;if(!r){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}let n=await Qf(r);t({personalMarketerEnabled:n},!1,"getPersonalMarketerSettings")},setPersonalMarketerEnabled:async r=>{let n=Vi.getState().selectedLocation?.franchise_id;if(!n){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}await em(n,r),t({personalMarketerEnabled:r},!1,"setPersonalMarketerEnabled")},getRecentRuns:async(r=10)=>{let n=Vi.getState().franchiseId;if(!n)return e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found"),[];let i=await tm(n,r);return t({recentRuns:i},!1,"getRecentRuns"),i},createBlastRun:async(r,n)=>{let i=await jt("/marketing/create-run",{method:"POST",body:JSON.stringify({franchiseId:r,source:"blast",strategyId:"promotionalBlast",promotionId:n,dryRun:!1})});if(!i.ok){let o=await i.json().catch(()=>({}));throw new Error(o?.error??`HTTP ${i.status}`)}let{run:s}=await i.json();return await e().getRecentRuns(),s}})),{name:"PromotionStore"})),me=Iv;var im=qn(nm(),1);import{useMemo as jv}from"react";function sa(t){return t===2?2:1}var sm=!1;function om(){sm=!0}var oa=Rv()(Lv(Nv(Av((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:H.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,n)=>{let i=r;if(n){t(a=>{a.promoOverrideActive=!0,a.selectedPromotion=void 0,a.workingOrder.promo_code=void 0});let s=e().workingOrder.location_id,o=Mt(n,{items:[r],location_id:s,method_id:3},new Date);i={...r,applied_promo_id:n.id,discount_amount:o>0?o:void 0}}t(s=>{s.workingOrder.items.push(i),i.is_catering&&(s.workingOrder.is_catering=!0),s.status!=="editing"&&(s.workingOrder.order_id=0)}),e().checkBestPromo()},setTip:r=>t(n=>{n.selectedTip=r}),removeItem:r=>{t(n=>{n.workingOrder.items.splice(r,1),n.status!=="editing"&&(n.workingOrder.order_id=0)}),e().checkBestPromo()},updateItem:(r,n,i)=>{let s=r;if(i!==void 0)if(t(o=>{o.promoOverrideActive=!0,i&&(o.selectedPromotion=void 0,o.workingOrder.promo_code=void 0)}),i){let o=e().workingOrder.location_id,a=Mt(i,{items:[r],location_id:o,method_id:3},new Date);s={...r,applied_promo_id:i.id,discount_amount:a>0?a:void 0}}else s={...r,applied_promo_id:void 0,discount_amount:void 0};t(o=>{o.workingOrder.items[n]=s,o.status!=="editing"&&(o.workingOrder.order_id=0)}),e().checkBestPromo()},setCustomer:r=>t(n=>{n.workingOrder.customer=r}),getAnonCustomer:()=>({customer_id:0,first_name:"Customer",last_name:"Customer",phone:"0"}),setCart:r=>t(n=>{n.workingOrder=r}),createCustomer:async()=>{let r=e().workingOrder.customer,{data:n,error:i}=await j.from("customers").insert({first_name:r.first_name,last_name:r.last_name,email:r.email,phone_number:parseInt(r.phone)}).select("*").single();return i?(console.log("Error creating customer:",i),null):(console.log("customer created",n),n)},setLocationId:r=>t(n=>{n.workingOrder.location_id=r}),setOrderType:r=>t(n=>{n.workingOrder.type_id=sa(r)}),setTableNumber:r=>t(n=>{n.workingOrder.table_number=r}),setTimeRequested:r=>t(n=>{n.workingOrder.time_requested=r}),applyCateringPreflight:r=>t(n=>{if(n.workingOrder.type_id=r.type_id,n.workingOrder.location_id=r.location_id,n.workingOrder.time_requested=r.time_requested,r.type_id===lh.ORDER_TYPE.DELIVERY){let i=r.delivery_address?.trim();n.workingOrder.delivery_address=i&&i.length>0?i:void 0}else n.workingOrder.delivery_address=void 0}),clearCateringSchedule:()=>t(r=>{r.workingOrder.time_requested=void 0}),setDeliveryFee:r=>t(n=>{n.deliveryFeeCents=r}),setPromoCode:r=>t(n=>{n.workingOrder.promo_code=r}),resetOrder:()=>t(r=>({workingOrder:{...r.workingOrder,order_id:0,location_id:H.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(n=>{n.workingOrder={...r,type_id:sa(r.type_id)}}),startEdit:r=>t(n=>{let i={...r,type_id:sa(r.type_id),charges:r.charges??[]};n.workingOrder=i,n.editingSourceOrder=i,n.status="editing",n.selectedTip=void 0;let s=Number(r.promo_code);n.selectedPromotion=s?me.getState().activePromotions.find(o=>o.id===s):void 0,n.promoOverrideActive=!!n.selectedPromotion}),cancelEdit:(r=!0)=>t(n=>{n.status="idle",n.editingSourceOrder=null,n.selectedTip=void 0,n.selectedPromotion=void 0,n.promoOverrideActive=!1,r&&(n.workingOrder={...n.workingOrder,location_id:H.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:H.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:n,workingOrder:i}=e();return r!=="editing"||!n?!1:!(0,im.default)(n.items,i.items)},getOrderTotal:()=>An({order:e().workingOrder}),setCartFromURL:async(r,n)=>{try{let i={"Content-Type":"application/json",...n?{"X-Zorgo-Api-Key":n}:{}},s=await fetch(`${Xs}/s/${r}`,{headers:i});if(!s.ok)return!1;let{cart_data:o,promotion_id:a}=await s.json();return o?(t(c=>{if(c.workingOrder={...c.workingOrder,...o,type_id:sa(o.type_id),order_id:0,order_status:1},c.workingOrder.time_requested=void 0,!a||o?.promo_code||o?.items?.some(d=>d.applied_promo_id))return;let u=me.getState().activePromotions.find(d=>d.id===a);if(!u){c.workingOrder.promo_code=String(a);return}if(u.promo_code){c.workingOrder.promo_code=u.promo_code;return}c.workingOrder.items=bf(c.workingOrder.items,u)}),e().checkBestPromo(),!0):!1}catch(i){return console.error("[CartStore] setCartFromURL failed:",i),!1}},dismissPromo:r=>{t(n=>{n.dismissedPromoIds=[...n.dismissedPromoIds||[],r]})},checkBestPromo:()=>{if(e().promoOverrideActive)return;let{workingOrder:r}=e();if(!r.location_id||!r.method_id)return;let n=me.getState().activePromotions,i=new Date,s=e().selectedPromotion;if(s&&ta(s)==="private")return;let o=s?Mt(s,r,i):0;if(s&&o===0){e().removeOrderPromotion();return}let a=xf(r,n,i);if(s){a.orderPromo&&a.orderPromo.id!==s.id&&a.discount>o&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo);return}if(a.itemDiscounts?.length?t(l=>{for(let u of l.workingOrder.items)u.display_price=void 0,u.applied_promo_id=void 0,u.discount_amount=void 0;for(let u of a.itemDiscounts){let d=l.workingOrder.items[u.itemIndex];d&&(d.applied_promo_id=u.promotionId,d.discount_amount=u.discount,d.display_price=d.price-Math.round(u.discount/d.quantity))}}):e().wipeItemPromos(),a.discount===0||!a.orderPromo)return;let c=e().workingOrder.items.reduce((l,u)=>l+(u.discount_amount??0),0);c===0?e().applyOrderPromotion(a.orderPromo):a.discount>c&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo)},setOnBestPromoChange:r=>{t(n=>(n.onBestPromoChange=r,n))},wipeItemPromos:()=>{t(r=>{r.workingOrder.items=r.workingOrder.items.map(n=>({...n,display_price:void 0,applied_promo_id:void 0,discount_amount:void 0}))})},applyOrderPromotion:r=>{t(n=>{n.selectedPromotion=r,n.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(n=>{n.promoOverrideActive=!0}),r?e().applyOrderPromotion(r):(t(n=>{n.selectedPromotion=void 0,n.workingOrder.promo_code=void 0}),e().wipeItemPromos())}}))),{name:"cart",version:1,storage:Dv(()=>rr()),skipHydration:tr,partialize:t=>({editingSourceOrder:t.editingSourceOrder,...sm&&{workingOrder:t.workingOrder,selectedTip:t.selectedTip,deliveryFeeCents:t.deliveryFeeCents}})})),J=oa;function am(){let t=oa(n=>n.workingOrder),e=oa(n=>n.selectedPromotion),r=oa(n=>n.selectedTip??0);return jv(()=>{let n=An({order:t}),{discount:i}=kf(t,e),s=n-i,o=Ef(s),a=Sf(s,t.method_id,t.is_catering??!1),c=s+o+a+r;return{subtotal:n,discount:i,tax:o,serviceFee:a,total:c}},[t,e,r])}import{create as Fv}from"zustand";import{z as dt}from"zod";var $v=dt.object({notification_email:dt.email().nullish(),minimum_notice_hours:dt.number().int().nullish(),minimum_people_required:dt.number().int().positive().nullish(),minimum_price:dt.number().nonnegative().nullish(),does_cater:dt.boolean().nullish()}),Mv=dt.object({does_deliver:dt.boolean().nullish(),delivery_fee_cents:dt.number().int().nullish(),max_delivery_radius_miles:dt.number().nullish(),cents_per_mile:dt.number().int().nullish()}),Uv={catering:$v,delivery:Mv};async function ul(t,e){let{data:r}=await j.from("franchise_feature_config").select("config").eq("franchise_id",t).eq("feature",e).maybeSingle();return r?Uv[e].parse(r.config):null}import{createJSONStorage as qv,devtools as Bv,persist as Vv}from"zustand/middleware";var Xe=null,Ft=null,qt=null,Hi=null;function Hv(t){return typeof t=="number"?{franchiseId:t}:t??{}}function cm(){return dl.getState().platform??"website"}var dl=Fv()(Vv(Bv((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:n}=await j.from("items").select("updated_at").order("updated_at",{ascending:!1}).limit(1).single();if(n)throw e().logLevel<=2&&console.warn(n,"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 n=Hv(r),i=n.franchiseId??e().franchiseId??H.getState().franchiseId;if(e().logLevel<=1&&console.debug("starting menu manager"),!i){e().logLevel<=3&&console.warn("franchise id is not set, cannot start menu manager");return}t({franchiseId:i}),n.platform&&t({platform:n.platform}),e().refreshLocalMenu(),e().menuChangeListener(),e().promotionsChangeListener()},items:[],hydrate:({items:r,categories:n,rules:i,components:s})=>t({items:r??[],categories:n??[],rules:i??[],components:s??[]},!1,"hydrate"),setItems:r=>{t({items:r})},addItem:r=>{t({items:[...e().items,r]})},updateItem:r=>{t({items:e().items.map(n=>n.base_item_id===r.base_item_id?r:n)})},deleteItem:r=>{t({items:e().items.filter(n=>n.base_item_id!==r)})},addVariant:(r,n)=>{t({items:e().items.map(i=>i.base_item_id===n?{...i,variants:[...i.variants,r]}:i)})},updateVariant:(r,n)=>{t({items:e().items.map(i=>i.base_item_id===n?{...i,variants:i.variants.map(s=>s.item_id===r.item_id?r:s)}:i)})},deleteVariant:(r,n)=>{t({items:e().items.map(i=>i.base_item_id===n?{...i,variants:i.variants.filter(s=>s.item_id!==r)}:i)})},categories:[],setCategories:r=>t({categories:r}),addCategory:r=>{t({categories:[...e().categories,r]})},updateCategory:r=>{t({categories:e().categories.map(n=>n.category_id===r.category_id?r:n)})},deleteCategory:r=>{t({categories:e().categories.filter(n=>n.category_id!==r)})},rules:[],setRules:r=>{t({rules:r})},addRule:r=>{t({rules:[...e().rules,r]})},updateRule:r=>{t({rules:e().rules.map(n=>n.rule_id===r.rule_id?r:n)})},deleteRule:r=>{t({rules:e().rules.filter(n=>n.rule_id!==r)})},components:[],setComponents:r=>{t({components:r})},addComponent:r=>{t({components:[...e().components,r]})},updateComponent:r=>{t({components:e().components.map(n=>n.id===r.id?r:n)})},deleteComponent:r=>{t({components:e().components.filter(n=>n.id!==r)})},isLocalMenuFresh:async()=>{let r=await e().remoteMenuLastUpdated(),n=e().lastUpdatedAt;return r>=n},refreshLocalMenu:async()=>{let r=e().franchiseId;if(!r){e().logLevel<=2&&console.warn("franchise id is not set, cannot refresh menu");return}let n=cm(),i=H.getState().selectedLocation?.location_id||0;e().logLevel<=1&&console.log("[MenuStore] refreshing menu:",{franchiseId:r,locationId:i,platform:n});let s=await df(j,r,i,n),o=Fi(me.getState().allPromotions,n,i||void 0,new Date);me.setState({activePromotions:o});let[a,c,l]=await Promise.all([lf(j,r,s),ul(r,"catering"),ul(r,"delivery")]),{items:u,categories:d,rules:h,components:f}=uf(a,o);t({items:u,categories:d,rules:h,components:f,franchiseCateringConfig:c??{},franchiseDeliveryConfig:l??{}},!1,"refreshLocalMenu"),Hi||(Hi=setInterval(()=>{let m=me.getState().allPromotions;if(!m.length)return;let g=cm(),y=H.getState().selectedLocation?.location_id??void 0,p=Fi(m,g,y,new Date),_=me.getState().activePromotions;(p.length!==_.length||p.some((w,D)=>w.id!==_[D]?.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(Ft&&(clearTimeout(Ft),Ft=null),Xe){try{Xe.unsubscribe?.()}catch{}try{j.removeChannel?.(Xe)}catch{}Xe=null}let n=j.channel(`menu-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"items",filter:`franchise_id=eq.${r}`},()=>{e().refreshLocalMenu()});Xe=n,n.subscribe(i=>{if(i==="SUBSCRIBED"){e().logLevel<=1&&console.log("[MenuStore] Subscribed to menu changes");return}if(i==="CLOSED"){e().logLevel<=1&&console.log(`[MenuStore] Subscription status: ${i}`);return}if(i!=="CHANNEL_ERROR"&&i!=="TIMED_OUT"){e().logLevel<=2&&console.warn(`[MenuStore] Subscription status: ${i}`);return}console.warn(`[MenuStore] Subscription status: ${i}. Reconnecting in 5s...`);try{Xe?.unsubscribe?.()}catch{}try{j.removeChannel?.(Xe)}catch{}Xe=null,Ft&&clearTimeout(Ft),Ft=setTimeout(()=>{e().menuChangeListener()},5e3)})},promotionsChangeListener:()=>{let r=e().franchiseId;if(!r)return;if(qt){try{qt.unsubscribe?.()}catch{}try{j.removeChannel?.(qt)}catch{}qt=null}qt=j.channel(`promotions-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"promotions",filter:`franchise_id=eq.${r}`},async()=>{let{data:i}=await j.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",r);me.setState({allPromotions:i||[]}),e().refreshLocalMenu()}).subscribe()},cleanup:()=>{if(Ft&&(clearTimeout(Ft),Ft=null),Xe){try{Xe.unsubscribe?.()}catch{}try{j.removeChannel?.(Xe)}catch{}Xe=null}if(qt){try{qt.unsubscribe?.()}catch{}try{j.removeChannel?.(qt)}catch{}qt=null}Hi&&(clearInterval(Hi),Hi=null)},setLastUpdatedAt:r=>t({lastUpdatedAt:r}),uploadMenuImage:async r=>{let n=H.getState().franchiseId;if(!n)throw e().logLevel<=2&&console.warn("[MenuStore] Cannot upload menu image without franchiseId"),new Error("franchise id is not set");let i=`franchise_id_${n}/menu-${Date.now()}`,{error:s}=await j.storage.from("menu-images").upload(i,r);if(s)throw s;return i}}),{name:"MenuStore"}),{name:"menu",onRehydrateStorage:()=>(t,e)=>{if(e||!t)return;let r=t.items;dl.setState({items:r??[]})},storage:qv(()=>rr()),skipHydration:tr}));var Tt=dl;import{z as pe}from"zod";import{z as Nn}from"zod";function aa(t,e){let r={};for(let[n,i]of Object.entries(e)){let s=`${t}.${n}`;r[n]=i instanceof Nn.ZodType?{name:s,schema:i}:aa(s,i)}return r}if(process.env.NODE_ENV!=="production"){let t=aa("order",{placed:Nn.object({orderId:Nn.number()}),catering:{placed:Nn.object({orderId:Nn.number(),headcount:Nn.number()})}}),e=(r,n)=>{if(!r)throw new Error(`define.ts assert: ${n}`)};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"),console.log("define.ts ok")}import{z as Q}from"zod";var lm=Q.object({source:Q.string().optional(),medium:Q.string().optional(),campaign:Q.string().optional()}),$r=aa("website",{session_started:Q.object({landing_page:Q.string(),referrer:Q.string().optional(),utm:lm.optional()}),session_ended:Q.object({duration_ms:Q.number(),pages_visited:Q.number()}),page_viewed:Q.object({path:Q.string(),referrer:Q.string().optional(),utm:lm.optional()}),page_exited:Q.object({path:Q.string(),duration_ms:Q.number()}),short_url_clicked:Q.object({slug:Q.string(),referrer:Q.string().optional(),run_id:Q.string().uuid().optional(),outbound_message_id:Q.string().uuid().optional(),strategy_id:Q.string().optional(),strategy_variant_id:Q.string().optional(),dry_run:Q.boolean().optional()})});var Pj=pe.object({id:pe.number(),created_at:pe.string(),severity:pe.enum(["debug","info","warn","error"]),event_name:pe.string(),source:rf,service:pe.string().nullable(),device_id:pe.number().nullable(),session_id:pe.string().nullable(),request_id:pe.string().nullable(),franchise_id:pe.number().nullable(),location_id:pe.number().nullable(),user_id:pe.string().nullable(),anonymous_id:pe.string().nullable(),customer_id:pe.number().nullable(),order_id:pe.number().nullable(),payload:pe.record(pe.string(),pe.unknown()),stack_trace:pe.string().nullable()}),Wv=()=>({}),um=null,Cj=new Proxy({},{get(t,e){return um?.[e]??(()=>{})}});function dm(t){let{source:e,getContext:r=Wv,dev:n=!1}=t,i=(o,a,c,l,u)=>{let d=a.schema.safeParse(c);if(!d.success){console.error(`[log] invalid payload for ${a.name}:`,d.error.issues);return}let h=r(),f=o==="error"?(l instanceof Error?l.stack:null)??new Error().stack??null:null;if(n){console.log(`[${o}] ${a.name}`,d.data);return}jt("/events",{method:"POST",body:JSON.stringify({severity:o,event_name:a.name,source:e,session_id:h.session_id??null,request_id:u?.request_id??h.request_id??null,location_id:h.location_id??null,franchise_id:h.franchise_id??null,anonymous_id:h.anonymous_id??null,customer_id:h.customer_id??null,payload:d.data,stack_trace:f})}).then(m=>{m.ok||m.text().then(g=>console.error(`[log] POST /events ${m.status} for ${a.name}:`,g))}).catch(m=>{console.error(`[log] POST /events failed for ${a.name}:`,m)})},s={info:(o,a,c)=>i("info",o,a,void 0,c),warn:(o,a,c)=>i("warn",o,a,void 0,c),error:(o,a,c,l)=>i("error",o,a,c,l)};return um=s,s}var Mr=class{diff(e,r,n={}){let i;typeof n=="function"?(i=n,n={}):"callback"in n&&(i=n.callback);let s=this.castInput(e,n),o=this.castInput(r,n),a=this.removeEmpty(this.tokenize(s,n)),c=this.removeEmpty(this.tokenize(o,n));return this.diffWithOptionsObj(a,c,n,i)}diffWithOptionsObj(e,r,n,i){var s;let o=_=>{if(_=this.postProcess(_,n),i){setTimeout(function(){i(_)},0);return}else return _},a=r.length,c=e.length,l=1,u=a+c;n.maxEditLength!=null&&(u=Math.min(u,n.maxEditLength));let d=(s=n.timeout)!==null&&s!==void 0?s:1/0,h=Date.now()+d,f=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(f[0],r,e,0,n);if(f[0].oldPos+1>=c&&m+1>=a)return o(this.buildValues(f[0].lastComponent,r,e));let g=-1/0,y=1/0,p=()=>{for(let _=Math.max(g,-l);_<=Math.min(y,l);_+=2){let b,w=f[_-1],D=f[_+1];w&&(f[_-1]=void 0);let S=!1;if(D){let K=D.oldPos-_;S=D&&0<=K&&K<a}let C=w&&w.oldPos+1<c;if(!S&&!C){f[_]=void 0;continue}if(!C||S&&w.oldPos<D.oldPos?b=this.addToPath(D,!0,!1,0,n):b=this.addToPath(w,!1,!0,1,n),m=this.extractCommon(b,r,e,_,n),b.oldPos+1>=c&&m+1>=a)return o(this.buildValues(b.lastComponent,r,e))||!0;f[_]=b,b.oldPos+1>=c&&(y=Math.min(y,_-1)),m+1>=a&&(g=Math.max(g,_+1))}l++};if(i)(function _(){setTimeout(function(){if(l>u||Date.now()>h)return i(void 0);p()||_()},0)})();else for(;l<=u&&Date.now()<=h;){let _=p();if(_)return _}}addToPath(e,r,n,i,s){let o=e.lastComponent;return o&&!s.oneChangePerToken&&o.added===r&&o.removed===n?{oldPos:e.oldPos+i,lastComponent:{count:o.count+1,added:r,removed:n,previousComponent:o.previousComponent}}:{oldPos:e.oldPos+i,lastComponent:{count:1,added:r,removed:n,previousComponent:o}}}extractCommon(e,r,n,i,s){let o=r.length,a=n.length,c=e.oldPos,l=c-i,u=0;for(;l+1<o&&c+1<a&&this.equals(n[c+1],r[l+1],s);)l++,c++,u++,s.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!s.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=c,l}equals(e,r,n){return n.comparator?n.comparator(e,r):e===r||!!n.ignoreCase&&e.toLowerCase()===r.toLowerCase()}removeEmpty(e){let r=[];for(let n=0;n<e.length;n++)e[n]&&r.push(e[n]);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,n){let i=[],s;for(;e;)i.push(e),s=e.previousComponent,delete e.previousComponent,e=s;i.reverse();let o=i.length,a=0,c=0,l=0;for(;a<o;a++){let u=i[a];if(u.removed)u.value=this.join(n.slice(l,l+u.count)),l+=u.count;else{if(!u.added&&this.useLongestToken){let d=r.slice(c,c+u.count);d=d.map(function(h,f){let m=n[l+f];return m.length>h.length?m:h}),u.value=this.join(d)}else u.value=this.join(r.slice(c,c+u.count));c+=u.count,u.added||(l+=u.count)}}return i}};var hl=class extends Mr{constructor(){super(...arguments),this.tokenize=fl}equals(e,r,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
148
- `))&&(e=e.trim()),(!n.newlineIsToken||!r.includes(`
149
- `))&&(r=r.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
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(`
154
+ `))&&(e=e.trim()),(!o.newlineIsToken||!r.includes(`
155
+ `))&&(r=r.trim())):o.ignoreNewlineAtEof&&!o.newlineIsToken&&(e.endsWith(`
150
156
  `)&&(e=e.slice(0,-1)),r.endsWith(`
151
- `)&&(r=r.slice(0,-1))),super.equals(e,r,n)}},Lj=new hl;function fl(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
152
- `));let r=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(let i=0;i<n.length;i++){let s=n[i];i%2&&!e.newlineIsToken?r[r.length-1]+=s:r.push(s)}return r}var ml=class extends Mr{constructor(){super(...arguments),this.tokenize=fl}get useLongestToken(){return!0}castInput(e,r){let{undefinedReplacement:n,stringifyReplacer:i=(s,o)=>typeof o>"u"?n:o}=r;return typeof e=="string"?e:JSON.stringify(ca(e,null,null,i),null," ")}equals(e,r,n){return super.equals(e.replace(/,([\r\n])/g,"$1"),r.replace(/,([\r\n])/g,"$1"),n)}},hm=new ml;function pl(t,e,r){return hm.diff(t,e,r)}function ca(t,e,r,n,i){e=e||[],r=r||[],n&&(t=n(i===void 0?"":i,t));let s;for(s=0;s<e.length;s+=1)if(e[s]===t)return r[s];let o;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),o=new Array(t.length),r.push(o),s=0;s<t.length;s+=1)o[s]=ca(t[s],e,r,n,String(s));return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),typeof t=="object"&&t!==null){e.push(t),o={},r.push(o);let a=[],c;for(c in t)Object.prototype.hasOwnProperty.call(t,c)&&a.push(c);for(a.sort(),s=0;s<a.length;s+=1)c=a[s],o[c]=ca(t[c],e,r,n,c);e.pop(),r.pop()}else o=t;return o}import{create as zv}from"zustand";import{devtools as Kv}from"zustand/middleware";var nr=zv()(Kv((t,e)=>({logLevel:4,stack:[],openModal:r=>t({stack:[...e().stack,r]}),goBack:()=>{let r=e().stack;if(r.length>1){let n=r[r.length-1];if(!n)return;let i=r.slice(0,-1),s=i[i.length-1];n.displayStyle!=="dialog"&&s&&(i[i.length-1]={...s,workingData:null}),t({stack:i})}else t({stack:[]})},close:()=>t({stack:[]}),setWorkingData:(r,n=0)=>{if(e().logLevel<=1&&e().stack.length>1){let a=e().getWorkingData(),c=pl(a,r);console.log("[MODAL STORE] working data diff from old:",c)}let i=e().stack,s=i.length-1-n;if(s<0)return;let o=[...i];o[s]={...o[s],workingData:r},t({stack:o})},getWorkingData:(r=0)=>{let n=e().stack;if(n.length!==0)return n[n.length-1-r]?.workingData}}),{name:"ModalStore"}));var Gv="v3",Jv=function(e){return e===3?"v3":e},pm="https://js.stripe.com",Yv="".concat(pm,"/v3"),Xv=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,Zv=/^https:\/\/js\.stripe\.com\/(v3|[a-z]+)\/stripe\.js(\?.*)?$/,fm="loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used",Qv=function(e){return Xv.test(e)||Zv.test(e)},e0=function(){for(var e=document.querySelectorAll('script[src^="'.concat(pm,'"]')),r=0;r<e.length;r++){var n=e[r];if(Qv(n.src))return n}return null},mm=function(e){var r=e&&!e.advancedFraudSignals?"?advancedFraudSignals=false":"",n=document.createElement("script");n.src="".concat(Yv).concat(r);var i=document.head||document.body;if(!i)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return i.appendChild(n),n},t0=function(e,r){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"5.10.0",startTime:r})},Wi=null,la=null,ua=null,r0=function(e){return function(r){e(new Error("Failed to load Stripe.js",{cause:r}))}},n0=function(e,r){return function(){window.Stripe?e(window.Stripe):r(new Error("Stripe.js not available"))}},i0=function(e){return Wi!==null?Wi:(Wi=new Promise(function(r,n){if(typeof window>"u"||typeof document>"u"){r(null);return}if(window.Stripe&&e&&console.warn(fm),window.Stripe){r(window.Stripe);return}try{var i=e0();if(i&&e)console.warn(fm);else if(!i)i=mm(e);else if(i&&ua!==null&&la!==null){var s;i.removeEventListener("load",ua),i.removeEventListener("error",la),(s=i.parentNode)===null||s===void 0||s.removeChild(i),i=mm(e)}ua=n0(r,n),la=r0(n),i.addEventListener("load",ua),i.addEventListener("error",la)}catch(o){n(o);return}}),Wi.catch(function(r){return Wi=null,Promise.reject(r)}))},s0=function(e,r,n){if(e===null)return null;var i=r[0],s=i.match(/^pk_test/),o=Jv(e.version),a=Gv;s&&o!==a&&console.warn("Stripe.js@".concat(o," 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 c=e.apply(void 0,r);return t0(c,n),c},zi,gm=!1,ym=function(){return zi||(zi=i0(null).catch(function(e){return zi=null,Promise.reject(e)}),zi)};Promise.resolve().then(function(){return ym()}).catch(function(t){gm||console.warn(t)});var _m=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];gm=!0;var i=Date.now();return ym().then(function(s){return s0(s,r,i)})};import{create as l0}from"zustand";import{devtools as u0}from"zustand/middleware";import Bt from"zod";import{create as o0}from"zustand";import{devtools as a0}from"zustand/middleware";var da=globalThis;function Ur(t){if(!da.document)return null;let e=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=da.document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return r?decodeURIComponent(r[1]):null}function gl(t,e,r=365){da.document&&(da.document.cookie=`${t}=${encodeURIComponent(e)}; path=/; max-age=${r*86400}; SameSite=Lax`)}var bm=Bt.object({shortUrlPath:Bt.string().optional().default("/s"),siteUrl:Bt.url().optional(),franchiseId:Bt.union([Bt.string(),Bt.number()]).optional(),locationId:Bt.union([Bt.string(),Bt.number()]).optional()});var c0=o0()(a0((t,e)=>({logLevel:1,config:bm.parse({}),sessionData:{},sessionId:Ui(),consentGiven:Ur("zorgo_consent")==="1",consentAnswered:Ur("zorgo_consent")!==null,anonymousId:Ur("zorgo_anon_id"),getSiteUrl:()=>{let r=e().config.siteUrl,n=typeof process<"u"?process.env.NEXT_PUBLIC_SITE_URL||process.env.NEXT_PUBLIC_BASE_URL:void 0,i=typeof globalThis<"u"&&"location"in globalThis&&globalThis.location?.origin?globalThis.location.origin:void 0,s=r||n||i;if(!s){e().logLevel<=3&&console.error("No site url found.");return}return s},getAnonymousId:()=>e().anonymousId,mergeSessionData:r=>{t(n=>{let i={...n.sessionData};for(let[s,o]of Object.entries(r))o===void 0?delete i[s]:i[s]=o;return{sessionData:i}})},setConsent:r=>{if(gl("zorgo_consent",r?"1":"0"),r&&!e().anonymousId){let n=`anon_${Ui()}`;gl("zorgo_anon_id",n),t({consentGiven:!0,consentAnswered:!0,anonymousId:n})}else t({consentGiven:r,consentAnswered:!0})},initialize:({token:r,config:n})=>{let i=bm.parse(n||{});t({token:r,config:i,consentGiven:Ur("zorgo_consent")==="1",consentAnswered:Ur("zorgo_consent")!==null,anonymousId:Ur("zorgo_anon_id")})}}),{name:"websiteCoreStore"})),ke=c0;var wm={logLevel:1,clientSecret:null,intentType:null,isLoading:!1,error:null,orderId:null,finalAmount:null},yl=!1,d0=l0()(u0((t,e)=>({...wm,start:async()=>{let r=H.getState().selectedLocation,n=process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY;if(!n||!r?.stripe_account_id)return null;let i=await _m(n,{stripeAccount:r.stripe_account_id});if(!i){e().logLevel<=3&&console.error("Failed to load Stripe");return}t({stripe:i})},createOrder:async(r,n)=>{if(!r?.items?.length||!n?.location_id)throw new Error("Order, location, and time_requested are required");let i={...r,method_id:2,location_id:n.location_id},{franchiseId:s}=ke.getState().config,o=await jt("/create-order",{method:"POST",body:JSON.stringify({order:i,anonymous_id:ke.getState().getAnonymousId(),franchise_id:s?String(s):void 0})});if(!o.ok){let c=await o.json();throw new Error(c.error||`Server error: ${o.status}`)}return(await o.json()).orderId},createPaymentIntentForOrder:async(r,n,i)=>{let s=await jt("/create-payment-intent",{method:"POST",body:JSON.stringify({orderId:r,tipAmount:n,deliveryFeeCents:i||0})});if(!s.ok){let l=await s.json();throw new Error(l.error||`Server error: ${s.status}`)}let o=await s.json(),a=o.charges?.total??o.amount??0,c=o.type==="setup_intent"?"setup_intent":"payment_intent";return{clientSecret:o.clientSecret,amount:a,intentType:c}},confirmPayment:async(r,n,i,s,o)=>{let a=r,c={name:`${o.first_name} ${o.last_name}`.trim()||void 0,email:o.email,phone:sf(o.phone)},l=e().intentType,u={return_url:s,payment_method_data:{billing_details:c}},d;return l==="setup_intent"?{error:d}=await a.confirmSetup({elements:n,clientSecret:i,confirmParams:u}):{error:d}=await a.confirmPayment({elements:n,clientSecret:i,confirmParams:u}),d?{success:!1,error:d.message}:l!=="setup_intent"?{success:!0,paymentIntentId:(await a.retrievePaymentIntent(i)).paymentIntent?.id}:{success:!0}},getReturnStatus:r=>{let n=typeof r=="string"?new URL(r):r,i=n.searchParams.get("redirect_status"),s=n.searchParams.get("payment_intent")??n.searchParams.get("setup_intent")??void 0,o=n.searchParams.get("amount");return i?i==="succeeded"?{succeeded:!0,amount:o?parseFloat(o):void 0,paymentIntentId:s}:{succeeded:!1,error:`Payment ${i}`,paymentIntentId:s}:{succeeded:!1,error:"No payment status found in URL"}},beginCheckout:async()=>{if(e().isLoading||yl)return;yl=!0,t({isLoading:!0,error:null});let r=J.getState().workingOrder,n=H.getState().selectedLocation,i=J.getState().selectedTip??0,s=J.getState().deliveryFeeCents??0;if(!n)throw new Error("Cannot start checkout without a selected location");if(!r)throw new Error("Cannot start checkout without a working order");if(i==null)throw new Error("Cannot start checkout without a selected tip");try{let o=e().orderId;o||(o=await e().createOrder(r,n),t({orderId:o}));let{clientSecret:a,amount:c,intentType:l}=await e().createPaymentIntentForOrder(o,i,s);t({clientSecret:a,intentType:l,orderId:o,finalAmount:c,isLoading:!1,error:null})}catch(o){let a=o instanceof Error?o.message:"Failed to setup payment";throw t({isLoading:!1,error:a}),o}finally{yl=!1}},reset:()=>t(wm)}),{name:"PaymentStore"})),Re=d0;import{create as O0}from"zustand";var qm=qn(Um(),1);import{z as Yi}from"zod";var xl=t=>(0,qm.default)(t).isLight()?"#000000":"#FFFFFF",ga=t=>Yi.string().nullish().transform(e=>e??t),Fm=t=>Yi.number().nullish().transform(e=>e??t),Bm=Yi.object({design_id:Fm(0),franchise_id:Fm(0),primary:ga("#9943E9"),accent:ga("#6636BF"),backgroundBase:ga("#EBEBEB"),fontFamily:ga("Inter"),created_at:Yi.string().optional(),updated_at:Yi.string().optional()}).transform(t=>({...t,foreground:xl(t.backgroundBase),primaryForeground:xl(t.primary),accentForeground:xl(t.accent)})),Vm=Bm.parse({});function Hm(t){return Bm.parse(t??{})}import{devtools as P0,persist as C0,createJSONStorage as I0}from"zustand/middleware";var kl=2,R0="branding-assets",A0=3600,D0=O0()(C0(P0((t,e)=>({branding:Vm,logoUrl:null,fetchFranchiseLogoUrl:async r=>{let n=[`franchises/${r}/logo.png`,`franchises/${r}/logo.jpg`];for(let i of n){let{data:s,error:o}=await j.storage.from(R0).createSignedUrl(i,A0);if(!o&&s?.signedUrl)return t({logoUrl:s.signedUrl}),console.log("logoUrl",s.signedUrl),s.signedUrl;console.log("error",o)}return t({logoUrl:null}),null},initialize:async()=>{let r=H.getState().franchiseId,{data:n,error:i}=await j.from("franchise_branding").select("*").eq("franchise_id",r).single();if(i){kl<=3&&console.error("[BRANDING STORE] Error fetching franchise branding:",i);return}if(!n){kl<=3&&console.error("[BRANDING STORE] No franchise branding found for franchise:",r);return}kl<=1&&console.log("[BRANDING STORE] Fetched franchise branding:",n),t({branding:Hm(n)})}})),{name:"branding",storage:I0(()=>rr()),skipHydration:tr,partialize:t=>({branding:t.branding})})),El=D0;import{create as N0}from"zustand";import{devtools as L0}from"zustand/middleware";import{immer as j0}from"zustand/middleware/immer";var $0=N0()(L0(j0(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 jt("/recommendations",{method:"POST",body:JSON.stringify(e)});if(!r.ok){let i=await r.json().catch(()=>null);throw new Error(i?.error??`Server error: ${r.status}`)}let n=await r.json();t(i=>{i.recommendations=n.recommendations??[],i.strategy=e.strategy??"top_items",i.isLoading=!1,i.lastFetchedAt=new Date})}catch(r){let n=r?.message??"Failed to fetch recommendations";t(i=>{i.error=n,i.isLoading=!1})}},setStrategy:e=>{t(r=>{r.strategy=e})},clear:()=>{t(e=>{e.recommendations=[],e.error=null,e.lastFetchedAt=null})}})),{name:"RecommendationStore"})),Ot=$0;function Wm(){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 zm(t){if(!t)return;let e=new URLSearchParams(t),r=e.get("utm_source")||void 0,n=e.get("utm_medium")||void 0,i=e.get("utm_campaign")||void 0;if(!(!r&&!n&&!i))return{source:r,medium:n,campaign:i}}var Km=()=>Promise.resolve();function Gm(t){Km=t}function Pt(){ar(()=>{Km().catch(console.error)},[])}var Jm=()=>typeof window>"u"?"/":window.location.pathname;function Ym(t){Jm=t}function bM(){let t=nr(r=>r.stack);return{current:t[t.length-1]??null,isOpen:t.length>0,depth:t.length,open:(r,n,i)=>nr.getState().openModal({type:r,props:n,displayStyle:i}),close:nr.getState().close,back:nr.getState().goBack,setWorkingData:nr.getState().setWorkingData,getWorkingData:nr.getState().getWorkingData}}function wM(){Pt();let t=J.getState(),e=J(l=>l.workingOrder),r=J(l=>l.selectedTip),{subtotal:n,discount:i,tax:s,serviceFee:o,total:a}=am(),c=Me(()=>e.items.reduce((l,u)=>l+u.quantity,0),[e.items]);return{items:e.items,itemCount:c,isEmpty:c===0,customer:e.customer,promoCode:e.promo_code,tip:r,subtotal:n,discount:i,tax:s,serviceFee:o,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:l=>Rn(l),getOrder:()=>J.getState().workingOrder,resolveShortUrl:l=>t.setCartFromURL(l,ke.getState().token)}}function vM(t){Pt();let e=H(c=>c.locations),r=H(c=>c.franchises),n=H(c=>c.selectedLocation),i=H(c=>c.setSelectedLocation),s=H(c=>c.getIsCurrentLocationOpen),o=Me(()=>e.filter(c=>r.some(l=>l.franchise_id===c.franchise_id)),[e,r]),a=!!t?.promptLocationSelection&&!n&&o.length>0;return{availableLocations:o,currentLocation:n,setLocation:i,getIsCurrentLocationOpen:s,needsLocationSelection:a}}function M0(){Pt();let t=Tt(n=>n.items),e=Tt(n=>n.categories);return{items:Me(()=>t.filter(n=>!e.find(s=>s.category_id===n.category_id)?.is_catering),[t,e]),allItems:t,categories:e}}function U0(t,e,r,n){let i=t.getState();n(i)&&r(i)(e)}function SM(t){U0(Tt,t,e=>e.hydrate,e=>!e.items?.length)}function xM(t,e,r){Pt();let n=r!=null,{allItems:i}=M0(),s=Me(()=>i.find(v=>v.base_item_id===t),[i,t]),[o,a]=or(e?.item_id??null),[c,l]=or(()=>{let v={};for(let U of e?.selections??[])v[U.rule_id]=U.selections.map(N=>In(`${N.type}:${N.id}`,N.portion));return v}),[u,d]=or(()=>{let v={};for(let U of e?.components??[])v[In(String(U.id),U.portion)]=U.quantity_servings;return v}),[h,f]=or(e?.quantity??1),m=sr(v=>f(U=>Math.max(1,typeof v=="function"?v(U):v)),[]),[g,y]=or(e?.comments??""),p=s?.variants.find(v=>v.item_id===o)??s?.variants[0],_=p?.portion_scheme??null,b=sr(v=>{a(v.item_id),l({}),d({})},[]),w=Me(()=>(p?.rules??s?.rules??[]).filter(v=>v.rule_id!=null),[p,s]),D=sr((v,U,N,Y=1/0)=>{l(G=>{let V=G[v]??[],ue=In(U,N),ae=V.findIndex(de=>ut(de).baseKey===U);return ae!==-1?{...G,[v]:V[ae]===ue?V.filter(de=>de!==ue):V.map((de,mt)=>mt===ae?ue:de)}:Y===1?{...G,[v]:[ue]}:Xc(V)+ea(N)>Y?G:{...G,[v]:[...V,ue]}})},[]),S=sr(v=>{l(U=>{let N={};for(let[Y,G]of Object.entries(U))N[Number(Y)]=G.flatMap(V=>{let{baseKey:ue,portion:ae}=ut(V);if(!ae)return[V];let de=_f(ae,v);return de?[In(ue,de[0])]:[]});return N})},[]),C=sr((v,U)=>{l(N=>({...N,[v]:(N[v]??[]).filter(Y=>ut(Y).baseKey!==U)}))},[]),K=Me(()=>w.map(v=>{let U=v.rule_id,N=c[U]??[],Y=ff(v),G=new Map(Y.map(V=>[V.key,V]));return{rule:v,ruleId:U,keys:N,defs:Y,byKey:G,charged:yf(N,V=>G.get(V)?.basePrice??0,v.included_quantity??0)}}),[w,c]),M=Me(()=>K.map(({rule:v,ruleId:U,keys:N,defs:Y,charged:G})=>{let V=v.max_selection??1/0,ue=Xc(N),ae=ue>=V;return{...v,rule_id:U,max:V,selectedCount:ue,portionable:!!_&&!!v.is_portionable,subtext:vf(v),satisfied:ue>=v.min_selection&&ue<=V,message:()=>ue<v.min_selection?`Choose at least ${v.min_selection} option${v.min_selection>1?"s":""}`:ue>V?`Choose no more than ${V} option${V>1?"s":""}`:null,options:Y.map(({basePrice:de,...mt})=>{let pt=N.find(Np=>ut(Np).baseKey===mt.key),Hr=pt?ut(pt).portion:null;return{...mt,key:pt??mt.key,portion:Hr,coveredSections:Hr?[$t(Hr).index]:[],coveredWhole:!!pt&&!Hr,upcharge:pt?G.get(pt):de,selected:!!pt,disabled:ae&&!pt&&V!==1,toggle:()=>D(U,mt.key,null,V)}})}}),[K,_,D]),Fe=Me(()=>K.map(({rule:v,ruleId:U,keys:N,byKey:Y,charged:G})=>({rule_id:U,group_name:v.group_name,selections:N.flatMap(V=>{let{baseKey:ue,portion:ae}=ut(V),de=Y.get(ue);return de?[{id:de.id,type:de.type,quantity:1,upcharge:G.get(V)??0,name:de.name,portion:ae}]:[]})})).filter(v=>v.selections.length>0),[K]),le=Me(()=>!s||!p?null:{item_id:p.item_id,base_item_id:s.base_item_id,category_id:s.category_id,name:p.name,quantity:h,price:p.price,components:(p.components??[]).flatMap(v=>gf(String(v.id),u,v.servings_per_item??1).map(({portion:U,value:N})=>({...v,portion:U,quantity_servings:N}))),selections:Fe,comments:g},[s,p,h,u,Fe,g]),tt=M.find(v=>!v.satisfied)??null,Kt=!!le&&!tt,ht=sr(()=>!le||M.some(v=>!v.satisfied)?null:(n?J.getState().updateItem(le,r):J.getState().addItem(le),le),[le,M,n,r]),Vr=le?Rn(le):0,ft=!!p?.display_price&&p.display_price<p.price;return{item:s,variant:p,variants:s?.variants??[],setVariant:b,ruleGroups:M,unmetRule:tt,canSubmit:Kt,submit:ht,portionScheme:_,placeOption:D,clearOption:C,recutSelections:S,quantity:h,setQuantity:m,comments:g,setComments:y,setComponentServings:(v,U,N=null)=>d(Y=>{let G={...Y};if(!N)for(let V of Object.keys(G))ut(V).baseKey===String(v)&&delete G[V];return G[In(String(v),N)]=Math.max(0,U),G}),price:Vr,salePrice:ft&&le?Rn({...le,display_price:p.display_price},!0):void 0,isEditMode:n,draft:le}}function kM(){Pt();let t=H(p=>p.selectedLocation),e=me(p=>p.activePromotions),r=J(p=>p.workingOrder),n=J(p=>p.selectedPromotion),i=r.promo_code,[s,o]=or(null),[a,c]=or(!1),l=Vt(null),u=Me(()=>r.items.reduce((p,_)=>p+(_.discount_amount??0),0),[r.items]),d=Me(()=>An({order:r}),[r]),h=Me(()=>{if(!n)return u;try{return Mt(n,r,new Date)}catch{return 0}},[u,n,r]),f=Me(()=>{if(n||u<=0)return null;let p=new Map;for(let b of r.items)!b.applied_promo_id||!b.discount_amount||p.set(b.applied_promo_id,(p.get(b.applied_promo_id)??0)+b.discount_amount);let _=Array.from(p.entries()).sort((b,w)=>w[1]-b[1])[0]?.[0];return e.find(b=>b.id===_)??null},[e,u,n,r.items]),m=n??f;ar(()=>{if(!t?.franchise_id)return;let p=!1;return c(!0),me.getState().getActivePromotions(t.franchise_id,t.location_id).finally(()=>{p||c(!1)}),()=>{p=!0}},[t?.franchise_id,t?.location_id]),ar(()=>{if(!i){o(null);return}if(n&&h>0){o(null);return}if(n?.min_purchase_amount&&d<n.min_purchase_amount){o(`Minimum purchase of $${(n.min_purchase_amount/100).toFixed(2)} required`);return}n&&o("Promotion not applicable")},[d,h,i,n]);let g=sr(async p=>{let _=p.trim();if(_){if(!t?.franchise_id||!t?.location_id){o("Please select a location first");return}c(!0),o(null);try{let b=await me.getState().getPromotionByCode(_,t.franchise_id);if(!b){J.getState().removeOrderPromotion(),o("Invalid promotion code");return}J.getState().applyOrderPromotion(b)}catch{o("Unable to apply promotion")}finally{c(!1)}}},[t?.franchise_id,t?.location_id]);ar(()=>{J.getState().workingOrder.promo_code||J.getState().checkBestPromo()},[e]),ar(()=>{if(typeof window>"u")return;let _=new URLSearchParams(window.location.search).get("promo");!_||_===i||l.current===_||(l.current=_,g(_))},[g,i,t?.location_id]);let y=sr(()=>{if(o(null),l.current=null,J.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:i??"",setPromoCode:p=>{p?g(p):y()},appliedPromo:m,discountAmount:h,error:s,loading:a,applyPromo:g,removePromo:y,activePromotions:e}}function EM(){Pt();let t=Re(l=>l.clientSecret),e=Re(l=>l.intentType),r=Re(l=>l.isLoading),n=Re(l=>l.error),i=Re(l=>l.stripe),s=Re(l=>l.finalAmount),o=J(l=>l.workingOrder),a=t?{clientSecret:t,defaultValues:{billingDetails:{name:(o.customer.first_name??"")+" "+(o.customer.last_name??""),email:o.customer.email,phone:o.customer.phone}}}:null,c=Re.getState().confirmPayment;return{clientSecret:t,intentType:e,stripe:i,elementOptions:a,total:s,isLoading:r,error:n,isReady:!!(t&&i),startCheckout:Re.getState().beginCheckout,resetCheckout:Re.getState().reset,submitPayment:c,paymentElementOptions:{layout:"accordion",fields:{billingDetails:{name:"never",email:"never",phone:"never",address:"auto"}}},getReturnStatus:Re.getState().getReturnStatus,getReturnUrl:ke.getState().getSiteUrl}}function TM(){Pt();let t=Tt(r=>r.franchiseCateringConfig),e=Tt(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 OM(){Pt();let t=Ot(s=>s.recommendations),e=Ot(s=>s.isLoading),r=Ot(s=>s.error),n=Ot(s=>s.strategy),i=Ot(s=>s.lastFetchedAt);return{recommendations:t,isLoading:e,error:r,strategy:n,lastFetchedAt:i,refresh:s=>Ot.getState().fetchRecommendations(s),setStrategy:s=>Ot.getState().setStrategy(s),clear:()=>Ot.getState().clear()}}var ya=null,Tl=null,Xm={};function Ol(){return Tl||(Tl=dm({source:"restaurant_site",getContext:()=>Xm})),Tl}function F0(){Pt();let t=ke(g=>g.consentGiven),e=ke(g=>g.anonymousId),r=ke(g=>g.config),n=H(g=>g.franchiseId),i=Jm(),s=Vt(null);s.current||(s.current=Symbol("zorgo-tracking"));let[o,a]=or(!1),c=Vt(null),l=Vt(Date.now()),u=Vt(Date.now()),d=Vt(0),h=Vt(!1),f=Vt(!1),m=Vt(typeof window>"u"?void 0:zm(window.location.search));ar(()=>(ya===null&&(ya=s.current,a(!0)),()=>{ya===s.current&&(ya=null)}),[]),ar(()=>{if(!o)return;if(!t){h.current=!1;return}let g=Wm(),y=typeof document<"u"&&document.referrer||void 0,p=r.franchiseId??n;Xm={session_id:g,anonymous_id:e||null,franchise_id:p!=null?Number(p):null,location_id:r.locationId!=null?Number(r.locationId):null};let _=Ol();h.current||(h.current=!0,f.current=!1,_.info($r.session_started,{landing_page:i,referrer:y,utm:m.current}),d.current=1,u.current=Date.now());let b=()=>{f.current||(f.current=!0,c.current&&_.info($r.page_exited,{path:c.current,duration_ms:Date.now()-l.current}),_.info($r.session_ended,{duration_ms:Date.now()-u.current,pages_visited:d.current}))},w=()=>{document.visibilityState==="hidden"&&b()};return window.addEventListener("beforeunload",b),document.addEventListener("visibilitychange",w),()=>{window.removeEventListener("beforeunload",b),document.removeEventListener("visibilitychange",w)}},[o,t,e,n]),ar(()=>{if(!(!o||!t||!h.current)){if(c.current&&c.current!==i&&Ol().info($r.page_exited,{path:c.current,duration_ms:Date.now()-l.current}),c.current!==i){let g=c.current===null;Ol().info($r.page_viewed,{path:i,referrer:typeof document<"u"&&document.referrer||void 0,utm:g?m.current:void 0}),g||(d.current+=1)}c.current=i,l.current=Date.now()}},[i,t,o])}function PM(){Pt(),F0();let t=J(s=>s.workingOrder.customer),e=J.getState().setCustomer,r=ke(s=>s.consentGiven),n=ke(s=>s.consentAnswered),i=ke(s=>s.anonymousId);return{customer:t,consentGiven:r,setCustomer:e,consentAnswered:n,setConsent:ke.getState().setConsent,anonymousId:i}}function Zm(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,n)=>{let i=document.querySelector('script[src^="https://maps.googleapis.com/maps/api/js"]');if(i){i.addEventListener("load",()=>r(),{once:!0}),i.addEventListener("error",()=>n(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=()=>n(new Error("Failed to load Google Maps")),document.head.appendChild(s)})}var _a=null;async function q0(){try{let t=await fetch("/api/zorgo-token");if(!t.ok)return;let{token:e}=await t.json();return e}catch{return}}function Qm(){return typeof window>"u"?Promise.resolve():_a||(_a=(async()=>{om();let t,e=new Promise(n=>t=n);mf(async()=>ke.getState().token??await e),await Promise.all([H,Tt,J,El].map(n=>n.persist.rehydrate())),J.setState(n=>({workingOrder:{...n.workingOrder,method_id:2,type_id:2}}));let r=await q0();if(t(r??null),!r)throw new Error("Zorgo: missing token. Ensure app/api/zorgo-token exists and ZORGO_SITE_SECRET is set.");ke.getState().initialize({token:r}),B0(),await H.getState().initialize({token:r})})(),_a)}function B0(){let t=i=>{i&&Re.getState().start()},e=async i=>{let s=H.getState().franchiseId;s&&(await me.getState().getActivePromotions(s,i,"website").catch(console.error),J.getState().checkBestPromo())},r=async i=>{i&&(await e(H.getState().selectedLocation?.location_id),Tt.getState().start({franchiseId:i,platform:"website",visibilityMode:"runtime"}))},n={fireImmediately:!0};H.subscribe(i=>i.franchiseId,r,n),H.subscribe(i=>i.selectedLocation?.stripe_account_id,t,n),H.subscribe(i=>i.selectedLocation?.location_id,(i,s)=>{i&&J.getState().setLocationId(i),i!==s&&e(i)},n)}import{createStore as V0}from"zustand";import{devtools as H0}from"zustand/middleware";import{immer as W0}from"zustand/middleware/immer";import{createContext as z0,useContext as K0}from"react";var Pl=z0(null);function Ze(){let t=K0(Pl);if(!t)throw new Error("Must be used inside DynamicFormShell");return t}function Cl({onSubmit:t}){return V0()(H0(W0((e,r)=>({values:{},fieldConfigs:{},fieldErrors:{},status:"idle",registerField:(n,i)=>(e(s=>{s.fieldConfigs[n]=i,n in s.values||(s.values[n]=i.defaultValue??"")}),()=>{e(s=>{delete s.fieldConfigs[n],delete s.fieldErrors[n]})}),setValue:(n,i)=>{e(s=>{s.values[n]=i})},clearError:n=>{e(i=>{delete i.fieldErrors[n],i.status="idle"})},validateField:n=>{let i=r().fieldConfigs[n];if(!i)return null;let s=r().values[n],o=i.required&&!s?"Required.":i.validate(s);return e(a=>{o?a.fieldErrors[n]=o:delete a.fieldErrors[n]}),o??null},setFieldError:(n,i)=>{r().fieldConfigs[n]&&e(o=>{o.fieldErrors[n]=i})},validateAll:()=>{let n={};return Object.keys(r().fieldConfigs).forEach(i=>{let s=r().validateField(i);s&&(n[i]=s)}),n},handleSubmit:async n=>{n.preventDefault();let i=r().validateAll();if(Object.keys(i).length>0){e(s=>{s.fieldErrors=i,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 G0,useRef as J0}from"react";import{jsx as ep}from"react/jsx-runtime";function tp({className:t,onSubmit:e,children:r}){let n=J0(e);n.current=e;let i=G0(()=>Cl({onSubmit:(...s)=>n.current(...s)}),[]);return ep(Pl.Provider,{value:i,children:ep("form",{onSubmit:i.getState().handleSubmit,className:t,children:r})})}import{useRef as eS}from"react";import{z as va}from"zod";import{useStore as Y0}from"zustand";function ba(){let t=Ze(),e=Y0(t,r=>r.status);return{status:e,isIdle:e==="idle",isSubmitting:e==="sending",isSubmitted:e==="sent",isError:e==="error"}}import{useStore as X0}from"zustand";function Z0(t,e){return t.required&&(e==null||e==="")?"Required.":t.validate(e)}function wa(){let t=Ze();return X0(t,e=>Object.entries(e.fieldConfigs).every(([r,n])=>Z0(n,e.values[r])===null))}import{useStore as Q0}from"zustand";function Ae(){let t=Ze();return Q0(t,e=>e.values)}import{jsx as rp,jsxs as rS}from"react/jsx-runtime";var tS=va.object({label:va.string().default("Submit"),loadingLabel:va.string().default("Submitting..."),className:va.string().default("")});function np(t){let{labelFn:e,...r}=t,{label:n,loadingLabel:i,className:s}=tS.parse(r),o=wa(),{isSubmitting:a,isSubmitted:c}=ba(),l=Ae(),u=Ze(),d=eS(null),h=!o||a||c,f=e?e(l):n;function m(){u.getState().validateAll(),setTimeout(()=>{d.current?.form?.querySelector("[data-field-error]")?.scrollIntoView({behavior:"smooth",block:"center"})},50)}return rS("div",{style:{position:"relative"},children:[rp("button",{ref:d,type:"submit",disabled:h,className:s,children:a?i:f}),h&&rp("div",{onClick:m,style:{position:"absolute",inset:0,cursor:"pointer"}})]})}import{useStore as ip}from"zustand";function ne(t){let e=Ze(),r=ip(e,c=>c.values[t]),n=ip(e,c=>c.fieldErrors[t])??null;return{value:r,error:n,setValue:c=>e.getState().setValue(t,c),clearError:()=>e.getState().clearError(t),validate:()=>e.getState().validateField(t),setError:c=>e.getState().setFieldError(t,c)}}import{jsx as nS}from"react/jsx-runtime";function ye({name:t,className:e}){let{error:r}=ne(t);return r?nS("span",{"data-field-error":t,className:e,children:r}):null}import{jsx as sp,jsxs as iS}from"react/jsx-runtime";function op({className:t,title:e,titleClassName:r,subtitle:n,subtitleClassName:i}){return iS("div",{className:t,children:[sp("h1",{className:r,children:e}),sp("p",{className:i,children:n})]})}import{useMemo as ap}from"react";import{jsx as Ht,jsxs as Al}from"react/jsx-runtime";function sS(t,e){return e.flatMap(r=>{let n=t[`rule_${r.ruleId}`]??[];return r.options.filter(i=>n.includes(i.value)&&i.upcharge>0).map(i=>({id:`rule_${r.ruleId}_${i.value}`,name:i.label,priceCents:i.upcharge}))})}function Il({label:t,value:e,isTotal:r,isDiscount:n}){return r?Ht("div",{className:"flex items-center justify-between pt-3 mt-1 border-t-2 border-zestia-red-500",children:Ht("span",{className:"font-extrabold text-end text-zestia-red-500 text-xl",children:e})}):n?Al("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[Ht("span",{className:"text-xs text-emerald-600 font-medium",children:t}),Ht("span",{className:"text-xs font-semibold text-emerald-600",children:e})]}):Al("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[Ht("span",{className:"text-xs text-stone-500",children:t}),Ht("span",{className:"text-xs font-semibold text-stone-700",children:e})]})}function Rl(t){return`$${(t/100).toFixed(2)}`}function cp({items:t,ruleGroups:e=[],guestCountFieldId:r="guestCount",className:n}){let i=Ae(),{value:s}=ne(r),o=Number(s)||0,a=me(m=>m.allPromotions),c=[...t,...sS(i,e)],l=c.reduce((m,g)=>m+g.priceCents,0),u=ap(()=>{let m=t.find(g=>g.isBase);if(m?.active_promo_id)return a.find(g=>g.id===m.active_promo_id&&g.min_purchase_quantity)},[t,a]),d=ap(()=>!u||o<=0?l:Math.round(Zc(l,o,u.discount_value/100,u.min_purchase_quantity)),[u,o,l]),h=d*o,f=l>0&&d<l?((l-d)/l*100).toFixed(1):null;return Al("div",{className:n,children:[c.map(m=>Ht(Il,{label:m.name,value:`${Rl(m.priceCents)}/person`},m.id)),f&&Ht(Il,{isDiscount:!0,label:`Bulk discount (${f}% off)`,value:`-${Rl(l-d)}/person`}),Ht(Il,{isTotal:!0,label:"Per-Person Cost",value:`${Rl(d)}/person`})]})}import{jsx as oS}from"react/jsx-runtime";function lp({label:t,className:e}){return oS("h2",{className:e,children:t})}import{jsx as aS}from"react/jsx-runtime";function up({children:t,className:e}){return aS("p",{className:e,children:t})}import{useState as cS,useEffect as lS}from"react";function Sa(t){let e={};for(let[r,n]of Object.entries(t))Array.isArray(n)&&n.every(i=>typeof i=="string")?e[r]=n.length===1?n[0]:n.length===0?void 0:n:e[r]=n;return e}import{Fragment as uS,jsx as dS}from"react/jsx-runtime";function dp({whenFormVal:t,whenFunction:e,whenMediaQuery:r,children:n}){let i=Ae(),[s,o]=cS(()=>r&&typeof window<"u"?window.matchMedia(r).matches:!1);return lS(()=>{if(!r)return;let c=window.matchMedia(r);o(c.matches);let l=u=>o(u.matches);return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[r]),(t?t(Sa(i)):!1)||(e?e():!1)||(r?s:!1)?dS(uS,{children:n}):null}import{z as L}from"zod";var ee=L.object({inputType:L.enum(["text","number","date","time"]).default("text"),fieldId:L.string(),label:L.string().optional(),placeholder:L.string().optional(),autoCompleteType:L.string().optional(),requiredText:L.string().default("Required."),required:L.boolean().default(!0),showLabel:L.boolean().default(!0),showError:L.boolean().default(!0),disabled:L.boolean().default(!1),fieldClassName:L.string().default("flex-1"),containerClassName:L.string().default("flex flex-col"),fieldLabelClassName:L.string().default("flex-1"),fieldErrorClassName:L.string().default("flex-1"),fieldAsteriskClassName:L.string().default("text-red-500"),initialValue:L.unknown().optional()}),$U=ee.extend({min:L.number().optional(),max:L.number().optional(),step:L.number().default(1)}),MU=ee.extend({min:L.string().optional(),max:L.string().default("23:59")}),$n=ee.extend({maxLength:L.number().default(256),validate:L.any(),sanitize:L.any(),min:L.string().optional(),max:L.string().optional()}),hp=ee.extend({minSelections:L.number().default(1),maxSelections:L.union([L.number(),L.literal(1/0)]).default(1),tooFewText:L.string().optional(),tooManyText:L.string().optional(),options:L.array(L.object({label:L.string(),value:L.string(),sublabel:L.string().optional(),description:L.string().optional(),disabled:L.boolean().optional().default(!1)})).min(1),optionClassName:L.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:L.string().default("border-blue-500 bg-blue-50"),optionLabelClassName:L.string().default("text-sm font-semibold text-stone-600"),optionActiveLabelClassName:L.string().default("text-sm font-semibold text-blue-500"),optionSublabelClassName:L.string().default("text-sm text-stone-400 shrink-0 ml-auto"),inputClassName:L.string().default("w-4 h-4 shrink-0 accent-blue-500")});import{jsx as hS,jsxs as fS}from"react/jsx-runtime";function Qe({children:t,required:e,className:r,asteriskClassName:n}){return fS("label",{className:r,children:[t,e&&hS("span",{className:n,children:"*"})]})}import{useEffect as fp,useRef as mS}from"react";function et({name:t,required:e=!1,validate:r,initialValue:n}){let i=Ze(),s=mS(r);fp(()=>{s.current=r},[r]),fp(()=>i.getState().registerField(t,{required:e,validate:o=>s.current?.(o)??null,defaultValue:n}),[])}import{jsx as Dl,jsxs as _S}from"react/jsx-runtime";var pS=/^[\x20-\x7E]*$/;function gS(t,e){return t.replace(/[^\x20-\x7E]/g,"").slice(0,e)}function yS(t,e,r,n){return i=>i.trim().length?n?n(i):i.length>e?`Must be ${e} characters or fewer.`:pS.test(i)?null:"Only standard characters are allowed.":t?r:null}function Ee(t){let{inputRef:e}=t,{fieldId:r,label:n,placeholder:i,initialValue:s,required:o,showLabel:a,showError:c,autoCompleteType:l,fieldClassName:u,containerClassName:d,fieldLabelClassName:h,fieldErrorClassName:f,fieldAsteriskClassName:m,requiredText:g,disabled:y,maxLength:p,validate:_,sanitize:b,inputType:w,min:D,max:S}=$n.parse(t),C=b??(ht=>gS(ht,p)),K=yS(o,p,g,_);et({name:r,required:o,validate:K,initialValue:s});let{value:M,setValue:Fe,error:le,clearError:tt,validate:Kt}=ne(r);return _S("div",{className:d,children:[a&&Dl(Qe,{required:o,className:h,asteriskClassName:m,children:n}),Dl("input",{type:w,ref:e,name:r,autoComplete:l,placeholder:i,value:M??"",onChange:ht=>{Fe(C(ht.target.value)),tt()},onBlur:Kt,"data-error":!!le||void 0,className:u,disabled:y,maxLength:p,min:D,max:S}),c&&Dl(ye,{name:r,className:f})]})}import{z as Nl}from"zod";import{jsx as SS}from"react/jsx-runtime";function bS(t){let e=t.replace(/\D/g,""),r=/^\d{10}$/.test(e),n=/^1\d{10}$/.test(e);return r||n?null:"Please enter a valid 10-digit phone number."}function wS(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 vS=ee.extend({fieldId:Nl.string().default("phone"),placeholder:Nl.string().default("(586) 313-2480"),label:Nl.string().default("Phone number")});function mp(t){let e=vS.parse(t);return SS(Ee,{...e,validate:bS,sanitize:wS})}import{z as xa}from"zod";import{jsx as ES}from"react/jsx-runtime";function xS(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())?null:"Please enter a valid email address."}var kS=ee.extend({fieldId:xa.string().default("email"),placeholder:xa.string().default("Email"),label:xa.string().default("Email"),autoCompleteType:xa.string().default("email")});function pp(t){let e=kS.parse(t);return ES(Ee,{...e,validate:xS})}import{jsx as Fr,jsxs as Ll}from"react/jsx-runtime";function gp(t){let{fieldId:e,label:r,required:n,showLabel:i,showError:s,containerClassName:o,fieldLabelClassName:a,fieldErrorClassName:c,fieldAsteriskClassName:l,requiredText:u,disabled:d,options:h,minSelections:f,maxSelections:m,initialValue:g,tooFewText:y,tooManyText:p,optionClassName:_,optionActiveClassName:b,optionLabelClassName:w,optionActiveLabelClassName:D,optionSublabelClassName:S,inputClassName:C}=hp.parse(t),K=m===1,M=K&&f===0;function Fe(N){return n&&N.length===0?u:N.length<f?y??`Please select at least ${f}.`:N.length>m?p??`Please select at most ${m}.`:null}et({name:e,required:n,initialValue:g??[],validate:Fe});let{value:le,error:tt,setValue:Kt,setError:ht,validate:Vr}=ne(e),ft=le??[];function v(N){let Y=K?ft.includes(N)&&M?[]:[N]:ft.includes(N)?ft.filter(G=>G!==N):[...ft,N];if(Y.length>m){ht(p??`Please select at most ${m}.`);return}Kt(Y),Vr()}function U(N){N.currentTarget.contains(N.relatedTarget)||Vr()}return Ll("div",{className:o,children:[i&&Fr(Qe,{required:n,className:a,asteriskClassName:l,children:r}),Fr("div",{className:"space-y-2",onBlur:U,tabIndex:-1,"data-error":!!tt||void 0,"aria-invalid":!!tt||void 0,children:h.map(N=>{let Y=ft.includes(N.value),G=d||N.disabled;return Ll("label",{className:`flex items-center gap-3 ${_} ${Y?b:""} ${G?"opacity-50 cursor-not-allowed":""}`,children:[Fr("input",{type:M?"checkbox":K?"radio":"checkbox",name:e,checked:Y,disabled:G,onChange:()=>v(N.value),className:C}),Ll("div",{className:"flex-1 min-w-0",children:[Fr("span",{className:Y?D:w,children:N.label}),N.description&&Fr("p",{className:"text-xs text-stone-400 mt-0.5 leading-snug",children:N.description})]}),N.sublabel&&Fr("span",{className:S,children:N.sublabel})]},N.value)})}),s&&Fr(ye,{name:e,className:c})]})}import{useEffect as TS}from"react";function jl({locationInputRef:t,isApplyingAutocompleteRef:e,setEventLocation:r,onCoordsResolved:n}){TS(()=>{let i=window;function s(){if(!t.current||!i.google)return;let o=new i.google.maps.places.Autocomplete(t.current,{types:["establishment","geocode"],componentRestrictions:{country:"us"},fields:["formatted_address","name","geometry"]});o.addListener("place_changed",()=>{let a=o.getPlace(),c=a.formatted_address?.trim()??"",l=a.name?.trim()??"",u=l.toLowerCase(),d=c.toLowerCase(),h=l&&c&&!d.startsWith(u)?`${l}, ${c}`:c||l;e.current=!0,t.current&&(t.current.value=h),r(h),a.geometry?.location&&n?.({lat:a.geometry.location.lat(),lng:a.geometry.location.lng()}),requestAnimationFrame(()=>{e.current=!1})})}i.google?s():window.addEventListener("google-maps-loaded",s,{once:!0})},[e,t,r,n])}import{useRef as yp}from"react";import{useEffect as OS}from"react";function $l(){return OS(()=>{let t=process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;t&&Zm(t).then(()=>window.dispatchEvent(new Event("google-maps-loaded"))).catch(()=>{})},[]),null}import{z as Ml}from"zod";import{Fragment as CS,jsx as _p,jsxs as IS}from"react/jsx-runtime";var PS=$n.extend({fieldId:Ml.string().default("eventLocation"),label:Ml.string().default("Event location"),placeholder:Ml.string().default("Search for a venue or enter an address\u2026")});function bp(t){let e=yp(null),r=yp(!1),n=PS.parse(t),{setValue:i,clearError:s}=ne(n.fieldId);function o(a){return a.replace(/<[^>]*>/g,"").trimStart().slice(0,255)}return jl({locationInputRef:e,isApplyingAutocompleteRef:r,setEventLocation:a=>{i(o(a)),s()}}),IS(CS,{children:[_p($l,{}),_p(Ee,{...n,inputRef:e})]})}import{useEffect as RS,useRef as AS}from"react";import{z as Ue}from"zod";import{jsx as jS}from"react/jsx-runtime";var DS="yyyy-MM-dd",Ul="HH:mm",NS=ee.extend({fieldId:Ue.string().default("time"),label:Ue.string().default("Start time"),autoCompleteType:Ue.string().default("off"),inputType:Ue.literal("time").default("time"),minTime:Ue.string().optional(),maxTime:Ue.string().optional(),closedSpans:Ue.array(Ue.object({from:Ue.string(),to:Ue.string()})).optional(),minimumNoticeHours:Ue.number().nullable().optional(),dateFieldId:Ue.string().default("date"),timezone:Ue.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone)});function Ct(t){return Le(t,Ul,new Date)}function wp(t){return Ke(Ct(t),"h:mm a")}function LS(t){return t.replace(/[^\d:]/g,"").slice(0,5)}function qr(t){let{minTime:e,maxTime:r,closedSpans:n,minimumNoticeHours:i,dateFieldId:s,timezone:o,...a}=NS.parse(t),l=Ae()[s],{value:u,validate:d}=ne(a.fieldId),h=AS(!0);RS(()=>{if(h.current){h.current=!1;return}u&&d()},[l,i,e,r]);function f(g){if(!/^\d{2}:\d{2}$/.test(g)||!Lr(Ct(g)))return"Please enter a valid time.";if(e&&Ie(Ct(g),Ct(e)))return`Please choose a time after ${wp(e)}.`;if(r&&kt(Ct(g),Ct(r)))return`Please choose a time before ${wp(r)}.`;if(n?.some(y=>!Ie(Ct(g),Ct(y.from))&&!kt(Ct(g),Ct(y.to))))return"This time is unavailable.";if(i&&l){let y=Le(`${l} ${g}`,`${DS} ${Ul}`,new Date);if(!Lr(y))return"Please enter a valid date and time.";let p=cl(y,o),_=ef(Sn(new Date,i));if(Ie(p,_)){let b=Bi(_,o),w=Ke(b,"MMM d 'at' h:mm a");return`Please select a time at least ${i} hours from now (after ${w}).`}}return null}let m=a.initialValue??(i?Ke(Dh(Sn(new Date,i),5),Ul):void 0);return jS(Ee,{...a,initialValue:m,validate:f,sanitize:LS})}import{z as Wt}from"zod";import{jsx as FS}from"react/jsx-runtime";var cr="yyyy-MM-dd";function $S(t,e,r,n){let i=Le(t,cr,new Date);return!Lr(i)||Ke(i,cr)!==t?"Please enter a valid date.":e&&Ie(i,Le(e,cr,new Date))?`Please choose ${e} or later.`:r&&kt(i,Le(r,cr,new Date))?`Please choose ${r} or earlier.`:n?.includes(t)?"This date is unavailable. Please choose another.":null}function MS(t){return t.replace(/[^\d-]/g,"").slice(0,10)}var US=ee.extend({fieldId:Wt.string().default("date"),label:Wt.string().default("Event date"),autoCompleteType:Wt.string().default("off"),inputType:Wt.literal("date").default("date"),minimumNoticeHours:Wt.number().nullable().optional(),minDate:Wt.date().optional(),maxDate:Wt.date().optional(),unavailableDates:Wt.array(Wt.date()).optional()});function Mn(t){let{minDate:e,maxDate:r,unavailableDates:n,minimumNoticeHours:i,...s}=US.parse(t),o=e??(i?lt(Sn(new Date,i)):lt(new Date)),a=Ke(o,cr),c=r?Ke(r,cr):void 0,l=n?.map(h=>Ke(h,cr));function u(h){return $S(h,a,c,l)}let d=s.initialValue??(i?Ke(lt(Sn(new Date,i)),cr):a);return FS(Ee,{...s,initialValue:d,min:a,max:c,validate:u,sanitize:MS})}import{z as lr}from"zod";import{jsx as HS}from"react/jsx-runtime";function qS(t){return t.replace(/[^0-9]/g,"").slice(0,255)}var BS=ee.extend({fieldId:lr.string().default("discreteNumber"),placeholder:lr.string().default("10"),label:lr.string().default("Number of guests"),min:lr.number().default(10),max:lr.number().default(5e3),minErrorText:lr.string().optional(),maxErrorText:lr.string().optional(),step:lr.number().default(1)});function VS(t,e,r,n){return i=>{let s=Number(i);return Number.isNaN(s)?"Please enter a valid number.":s<t?r??`Must be at least ${t}.`:s>e?n??`Must be ${e} or fewer.`:null}}function vp(t){let e=BS.parse(t),{min:r,max:n,minErrorText:i,maxErrorText:s,...o}=e;return HS(Ee,{...o,validate:VS(r,n,i,s),sanitize:qS})}import{z as ka}from"zod";import{jsx as Fl,jsxs as zS}from"react/jsx-runtime";var WS=ee.extend({min:ka.number().default(0),max:ka.number().default(100),step:ka.number().default(1),onChange:ka.any().optional()});function Sp(t){let{fieldId:e,label:r,min:n,max:i,step:s,required:o,showLabel:a,showError:c,fieldClassName:l,containerClassName:u,fieldLabelClassName:d,fieldAsteriskClassName:h,fieldErrorClassName:f,initialValue:m,requiredText:g,disabled:y,onChange:p}=WS.parse(t);function _(K){return o&&K==null?g:K<n?`Must be at least ${n}.`:K>i?`Must be ${i} or fewer.`:null}et({name:e,required:o,validate:_,initialValue:m??n});let{value:b,setValue:w,error:D,clearError:S,validate:C}=ne(e);return zS("div",{className:u,children:[a&&Fl(Qe,{required:o,className:d,asteriskClassName:h,children:r}),Fl("input",{type:"range",min:n,max:i,step:s,value:b??n,disabled:y,onChange:K=>{let M=Number(K.target.value);w(M),S(),p?.(M)},onBlur:C,"data-error":!!D||void 0,className:l}),c&&Fl(ye,{name:e,className:f})]})}import{z as xp}from"zod";import{jsx as ql,jsxs as kp}from"react/jsx-runtime";var KS=ee.extend({checkboxClassName:xp.string().default("mt-0.5 h-5 w-5 shrink-0 rounded"),labelClassName:xp.string().default("pt-0.5 text-sm leading-snug")});function Ep({children:t,...e}){let{fieldId:r,required:n,requiredText:i,showError:s,disabled:o,containerClassName:a,fieldErrorClassName:c,checkboxClassName:l,labelClassName:u,initialValue:d}=KS.parse(e);et({name:r,required:!1,validate:n?g=>g?null:i:void 0,initialValue:d??!1});let{value:h,setValue:f,validate:m}=ne(r);return kp("div",{className:a,children:[kp("div",{className:"flex items-start gap-3 px-1 py-2 min-h-[44px]",children:[ql("input",{type:"checkbox",id:r,checked:h??!1,onChange:g=>{f(g.target.checked),n&&m()},disabled:o,className:l}),ql("label",{htmlFor:r,className:u,children:t})]}),s&&ql(ye,{name:r,className:c})]})}import{jsx as Tp}from"react/jsx-runtime";function Op({name:t,label:e="Quantity",initalVal:r=0,showLabel:n=!0,showError:i=!0,showIncrement:s=!0,showDecrement:o=!0}){return Tp("div",{children:Tp(Qe,{required:!0,children:e})})}import{z as Br}from"zod";import{jsx as Ea,jsxs as Pp}from"react/jsx-runtime";var GS=$n.extend({fieldId:Br.string().default("nameFields"),outerClassName:Br.string().default("flex flex-col md:flex-row w-full gap-4"),firstNamePlaceholder:Br.string().default("First name"),lastNamePlaceholder:Br.string().default("Last name"),firstNameInitialValue:Br.string().default(""),lastNameInitialValue:Br.string().default(""),childClassName:Br.string().default("flex flex-col w-full md:flex-1 md:min-w-0")});function JS({className:t}){let{error:e}=ne("firstName"),{error:r}=ne("lastName"),n=e??r;return n?Ea("span",{className:t,children:n}):null}function Cp(t){let e=GS.parse({...t}),{outerClassName:r,firstNamePlaceholder:n,lastNamePlaceholder:i,firstNameInitialValue:s,lastNameInitialValue:o,childClassName:a,...c}=e;return Pp("div",{className:"flex flex-col w-full gap-1",children:[Pp("div",{className:r,children:[Ea(Ee,{...c,fieldId:"firstName",label:"First name",placeholder:n,initialValue:s,autoCompleteType:"given-name",containerClassName:a,showError:!1}),Ea(Ee,{...c,fieldId:"lastName",label:"Last name",placeholder:i,initialValue:o,autoCompleteType:"family-name",containerClassName:a,showError:!1})]}),Ea(JS,{className:c.fieldErrorClassName})]})}import{z as _e}from"zod";import{jsx as Ta,jsxs as Ip}from"react/jsx-runtime";var YS=ee.extend({fieldId:_e.string().default("dateTime"),outerClassName:_e.string().default("flex flex-col md:flex-row w-full gap-4"),childClassName:_e.string().default("flex flex-col w-full md:flex-1 md:min-w-0"),dateLabel:_e.string().default("Event date"),dateFieldId:_e.string().default("date"),minDate:_e.date().optional(),maxDate:_e.date().optional(),unavailableDates:_e.array(_e.date()).optional(),minimumNoticeHours:_e.number().nullable().optional(),timeLabel:_e.string().default("Start time"),timeFieldId:_e.string().default("time"),closedSpans:_e.array(_e.object({from:_e.string(),to:_e.string()})).optional(),timezone:_e.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:_e.string().optional(),timeInitialValue:_e.string().optional()});function Rp(t){let{minTime:e,maxTime:r,timeBounds:n,...i}=t,{fieldId:s,outerClassName:o,childClassName:a,inputType:c,dateLabel:l,dateFieldId:u,minDate:d,maxDate:h,unavailableDates:f,minimumNoticeHours:m,timeLabel:g,timeFieldId:y,closedSpans:p,timezone:_,dateInitialValue:b,timeInitialValue:w,...D}=YS.parse(i),S=Sa(Ae()),C=n?n(S):void 0,K=C?.min??(typeof e=="function"?e(S):e),M=C?.max??(typeof r=="function"?r(S):r);return Ip("div",{className:"flex flex-col w-full gap-1",children:[Ip("div",{className:o,children:[Ta(Mn,{...D,inputType:"date",fieldId:u,label:l,minDate:d,maxDate:h,unavailableDates:f,minimumNoticeHours:m,containerClassName:a,showError:!1,initialValue:b??D.initialValue}),Ta(qr,{...D,inputType:"time",fieldId:y,label:g,minTime:K,maxTime:M,closedSpans:p,minimumNoticeHours:m,dateFieldId:u,timezone:_,containerClassName:a,showError:!1,initialValue:w??D.initialValue})]}),Ta(ye,{name:u,className:D.fieldErrorClassName}),Ta(ye,{name:y,className:D.fieldErrorClassName})]})}import{z as ce}from"zod";import{jsx as Un,jsxs as Bl}from"react/jsx-runtime";var XS=ee.extend({fieldId:ce.string().default("dateTimeRange"),dateLabel:ce.string().default("Event date"),dateFieldId:ce.string().default("date"),minDate:ce.date().optional(),maxDate:ce.date().optional(),unavailableDates:ce.array(ce.date()).optional(),minimumNoticeHours:ce.number().nullable().optional(),startTimeLabel:ce.string().default("Start time"),startTimeFieldId:ce.string().default("startTime"),endTimeLabel:ce.string().default("End time"),endTimeFieldId:ce.string().default("endTime"),closedSpans:ce.array(ce.object({from:ce.string(),to:ce.string()})).optional(),timezone:ce.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:ce.string().optional(),startTimeInitialValue:ce.string().optional(),endTimeInitialValue:ce.string().optional()});function Ap(t){let{fieldId:e,inputType:r,dateLabel:n,dateFieldId:i,minDate:s,maxDate:o,unavailableDates:a,minimumNoticeHours:c,startTimeLabel:l,startTimeFieldId:u,endTimeLabel:d,endTimeFieldId:h,closedSpans:f,timezone:m,dateInitialValue:g,startTimeInitialValue:y,endTimeInitialValue:p,..._}=XS.parse(t),w=Ae()[u];return Bl("div",{className:"flex flex-col w-full gap-1",children:[Bl("div",{className:"flex flex-col md:flex-row w-full gap-4",children:[Un(Mn,{..._,inputType:"date",fieldId:i,label:n,minDate:s,maxDate:o,unavailableDates:a,minimumNoticeHours:c,containerClassName:"flex flex-col w-full md:flex-1 md:min-w-0",showError:!1,initialValue:g??_.initialValue}),Bl("div",{className:"flex flex-row gap-4 md:contents",children:[Un(qr,{..._,inputType:"time",fieldId:u,label:l,closedSpans:f,minimumNoticeHours:c,dateFieldId:i,timezone:m,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:y??_.initialValue}),Un(qr,{..._,inputType:"time",fieldId:h,label:d,minTime:w,closedSpans:f,dateFieldId:i,timezone:m,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:p??_.initialValue})]})]}),Un(ye,{name:i,className:_.fieldErrorClassName}),Un(ye,{name:u,className:_.fieldErrorClassName}),Un(ye,{name:h,className:_.fieldErrorClassName})]})}import{z as zt}from"zod";import{useRef as Oa,useEffect as Pa}from"react";import{jsx as Fn,jsxs as Ca}from"react/jsx-runtime";var ZS=ee.extend({fieldId:zt.string().default("guestCount"),label:zt.string().default("Number of guests"),placeholder:zt.string().default("10"),min:zt.number().default(10),max:zt.number().default(5e3),step:zt.number().default(1),minErrorText:zt.string().optional(),maxErrorText:zt.string().optional(),sliderClassName:zt.string().default("flex-[3]")});function Dp(t){let{fieldId:e,label:r,placeholder:n,min:i,max:s,step:o,required:a,showLabel:c,showError:l,fieldClassName:u,containerClassName:d,fieldLabelClassName:h,fieldAsteriskClassName:f,fieldErrorClassName:m,initialValue:g,requiredText:y,minErrorText:p,maxErrorText:_,disabled:b,sliderClassName:w}=ZS.parse(t);function D(v){if(!v?.trim())return a?y:null;let U=Number(v);return Number.isNaN(U)?"Please enter a valid number.":U<i?p??`Must be at least ${i}.`:U>s?_??`Must be ${s} or fewer.`:null}et({name:e,required:a,validate:D,initialValue:g??String(i)});let{value:S,setValue:C,error:K,clearError:M,validate:Fe}=ne(e),le=Oa(C),tt=Oa(M),Kt=Oa(Fe);Pa(()=>{le.current=C},[C]),Pa(()=>{tt.current=M},[M]),Pa(()=>{Kt.current=Fe},[Fe]);let ht=Number(S)||i,Vr=Math.max(0,Math.min(100,(ht-i)/(s-i)*100)),ft=Oa(null);return Pa(()=>{let v=ft.current;if(!v)return;let U=0,N=0;function Y(ae){let{left:de,width:mt}=v.getBoundingClientRect(),pt=Math.max(0,Math.min(1,(ae-de)/mt)),Hr=i+(s-i)*pt;return String(Math.max(i,Math.min(s,Math.round(Hr/o)*o)))}function G(ae){U=ae.changedTouches[0].clientX,N=ae.changedTouches[0].clientY,le.current(Y(U)),tt.current()}function V(ae){let de=Math.abs(ae.changedTouches[0].clientX-U),mt=Math.abs(ae.changedTouches[0].clientY-N);de>mt&&ae.preventDefault(),le.current(Y(ae.changedTouches[0].clientX)),tt.current()}function ue(){Kt.current()}return v.addEventListener("touchstart",G,{passive:!0}),v.addEventListener("touchmove",V,{passive:!1}),v.addEventListener("touchend",ue,{passive:!0}),()=>{v.removeEventListener("touchstart",G),v.removeEventListener("touchmove",V),v.removeEventListener("touchend",ue)}},[]),Ca("div",{className:d,children:[c&&Fn(Qe,{required:a,className:h,asteriskClassName:f,children:r}),Ca("div",{className:"flex items-center gap-4",children:[Ca("div",{className:`flex flex-[6] flex-col ${w}`,children:[Fn("input",{ref:ft,type:"range",min:i,max:s,step:o,value:ht,disabled:b,onChange:v=>{C(v.target.value),M()},onBlur:Fe,className:`w-full ${w}`,style:{"--slider-fill":`${Vr}%`}}),Ca("div",{className:"flex justify-between text-xs text-stone-400 mt-2 px-0.5",children:[Fn("span",{children:i}),Fn("span",{children:s})]})]}),Fn("input",{type:"text",inputMode:"numeric",placeholder:n,value:S??"",disabled:b,onChange:v=>{C(v.target.value.replace(/[^0-9]/g,"").slice(0,5)),M()},onBlur:Fe,"data-error":!!K||void 0,className:`flex-1 text-center ${u}`})]}),l&&Fn(ye,{name:e,className:m})]})}Gm(Qm);Ym(QS);export{Ep as CheckboxField,gp as ClickableField,dp as ConditionalRenderer,Mn as DateField,Rp as DateTime,Ap as DateTimeRange,up as DisclaimerText,vp as DiscreteNumberField,tp as DynamicFormShell,pp as EmailField,ye as FieldError,Qe as FieldLabel,Dp as GuestCountField,op as Header,Op as IncrementField,bp as LocationField,Cp as NameFields,mp as PhoneField,zc as Platforms,cp as PricePreview,lp as SectionLabel,Sp as SliderField,np as SubmitButton,Ee as TextField,qr as TimeField,hN as divisionsFor,mN as groupItemPortions,$t as parsePortion,ut as parsePortionKey,Gw as portionGlyph,In as portionKey,fN as portionLabel,gf as portionRows,ea as portionWeight,pN as radialSectionPath,_f as remapPortion,Ww as sectionLabel,Xc as selectionWeight,Gm as setZorgoBoot,Ym as setZorgoPathnameHook,dN as splitUpcharge,wM as useCart,TM as useCateringConfig,PM as useCustomer,ne as useField,ba as useFormStatus,wa as useFormValidity,Ae as useFormValues,SM as useHydrateMenu,U0 as useHydrateStore,xM as useItemCustomization,vM as useLocation,M0 as useMenu,bM as useModal,EM as usePayment,kM as usePromotions,OM as useRecommendations,et as useRegisterField,yf as weightedUpcharges};
157
+ `)&&(r=r.slice(0,-1))),super.equals(e,r,o)}},n$=new rc;function oc(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 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};
153
159
  /*! Bundled license information:
154
160
 
155
161
  cookie/index.js: