flatblox-tui 0.2.9 → 0.2.11

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 (3) hide show
  1. package/README.md +8 -3
  2. package/dist/index.js +40 -40
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3,31 +3,31 @@
3
3
  process.env.FLATBLOX_SUPABASE_URL ||= "https://ldxdyymfagplpxxsqmgs.supabase.co";
4
4
  process.env.FLATBLOX_SUPABASE_PUBLISHABLE_KEY ||= "sb_publishable_mFx2R11m1O-XJCA1hZ85bA_bAOXyq9J";
5
5
  process.env.FLATBLOX_DASHBOARD_URL ||= "https://flatblox.com/dashboard/";
6
- var Fd=Object.create;var{getPrototypeOf:Gd,defineProperty:xa,getOwnPropertyNames:Ud}=Object;var Hd=Object.prototype.hasOwnProperty;function jd(e){return this[e]}var Kd,Wd,Yd=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var i=t?Kd??=new WeakMap:Wd??=new WeakMap,s=i.get(e);if(s)return s}r=e!=null?Fd(Gd(e)):{};let o=t||!e||!e.__esModule?xa(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Ud(e))if(!Hd.call(o,a))xa(o,a,{get:jd.bind(e,a),enumerable:!0})}if(n)i.set(e,o);return o};var Qd=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Yc=Qd(function(hx,ji){var pc,bc,yc,wc,vc,_c,Cc,xc,Ec,Sc,Ic,kc,Rc,Ui,To,Tc,Bc,Oc,Xr,Pc,Dc,Nc,Mc,Lc,Fc,Gc,Uc,Hc,Hi,jc,Kc,Wc;(function(e){var t=typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:{};if(typeof define==="function"&&define.amd)define("tslib",["exports"],function(n){e(r(t,r(n)))});else if(typeof ji==="object"&&typeof hx==="object")e(r(t,r(hx)));else e(r(t));function r(n,i){if(n!==t)if(typeof Object.create==="function")Object.defineProperty(n,"__esModule",{value:!0});else n.__esModule=!0;return function(s,o){return n[s]=i?i(s,o):o}}})(function(e){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,o){s.__proto__=o}||function(s,o){for(var a in o)if(Object.prototype.hasOwnProperty.call(o,a))s[a]=o[a]};pc=function(s,o){if(typeof o!=="function"&&o!==null)throw TypeError("Class extends value "+String(o)+" is not a constructor or null");t(s,o);function a(){this.constructor=s}s.prototype=o===null?Object.create(o):(a.prototype=o.prototype,new a)},bc=Object.assign||function(s){for(var o,a=1,l=arguments.length;a<l;a++){o=arguments[a];for(var c in o)if(Object.prototype.hasOwnProperty.call(o,c))s[c]=o[c]}return s},yc=function(s,o){var a={};for(var l in s)if(Object.prototype.hasOwnProperty.call(s,l)&&o.indexOf(l)<0)a[l]=s[l];if(s!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var c=0,l=Object.getOwnPropertySymbols(s);c<l.length;c++)if(o.indexOf(l[c])<0&&Object.prototype.propertyIsEnumerable.call(s,l[c]))a[l[c]]=s[l[c]]}return a},wc=function(s,o,a,l){var c=arguments.length,u=c<3?o:l===null?l=Object.getOwnPropertyDescriptor(o,a):l,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")u=Reflect.decorate(s,o,a,l);else for(var A=s.length-1;A>=0;A--)if(d=s[A])u=(c<3?d(u):c>3?d(o,a,u):d(o,a))||u;return c>3&&u&&Object.defineProperty(o,a,u),u},vc=function(s,o){return function(a,l){o(a,l,s)}},_c=function(s,o,a,l,c,u){function d(w){if(w!==void 0&&typeof w!=="function")throw TypeError("Function expected");return w}var A=l.kind,f=A==="getter"?"get":A==="setter"?"set":"value",g=!o&&s?l.static?s:s.prototype:null,m=o||(g?Object.getOwnPropertyDescriptor(g,l.name):{}),p,v=!1;for(var y=a.length-1;y>=0;y--){var E={};for(var _ in l)E[_]=_==="access"?{}:l[_];for(var _ in l.access)E.access[_]=l.access[_];E.addInitializer=function(w){if(v)throw TypeError("Cannot add initializers after decoration has completed");u.push(d(w||null))};var b=(0,a[y])(A==="accessor"?{get:m.get,set:m.set}:m[f],E);if(A==="accessor"){if(b===void 0)continue;if(b===null||typeof b!=="object")throw TypeError("Object expected");if(p=d(b.get))m.get=p;if(p=d(b.set))m.set=p;if(p=d(b.init))c.unshift(p)}else if(p=d(b))if(A==="field")c.unshift(p);else m[f]=p}if(g)Object.defineProperty(g,l.name,m);v=!0},Cc=function(s,o,a){var l=arguments.length>2;for(var c=0;c<o.length;c++)a=l?o[c].call(s,a):o[c].call(s);return l?a:void 0},xc=function(s){return typeof s==="symbol"?s:"".concat(s)},Ec=function(s,o,a){if(typeof o==="symbol")o=o.description?"[".concat(o.description,"]"):"";return Object.defineProperty(s,"name",{configurable:!0,value:a?"".concat(a," ",o):o})},Sc=function(s,o){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(s,o)},Ic=function(s,o,a,l){function c(u){return u instanceof a?u:new a(function(d){d(u)})}return new(a||(a=Promise))(function(u,d){function A(m){try{g(l.next(m))}catch(p){d(p)}}function f(m){try{g(l.throw(m))}catch(p){d(p)}}function g(m){m.done?u(m.value):c(m.value).then(A,f)}g((l=l.apply(s,o||[])).next())})},kc=function(s,o){var a={label:0,sent:function(){if(u[0]&1)throw u[1];return u[1]},trys:[],ops:[]},l,c,u,d=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return d.next=A(0),d.throw=A(1),d.return=A(2),typeof Symbol==="function"&&(d[Symbol.iterator]=function(){return this}),d;function A(g){return function(m){return f([g,m])}}function f(g){if(l)throw TypeError("Generator is already executing.");while(d&&(d=0,g[0]&&(a=0)),a)try{if(l=1,c&&(u=g[0]&2?c.return:g[0]?c.throw||((u=c.return)&&u.call(c),0):c.next)&&!(u=u.call(c,g[1])).done)return u;if(c=0,u)g=[g[0]&2,u.value];switch(g[0]){case 0:case 1:u=g;break;case 4:return a.label++,{value:g[1],done:!1};case 5:a.label++,c=g[1],g=[0];continue;case 7:g=a.ops.pop(),a.trys.pop();continue;default:if((u=a.trys,!(u=u.length>0&&u[u.length-1]))&&(g[0]===6||g[0]===2)){a=0;continue}if(g[0]===3&&(!u||g[1]>u[0]&&g[1]<u[3])){a.label=g[1];break}if(g[0]===6&&a.label<u[1]){a.label=u[1],u=g;break}if(u&&a.label<u[2]){a.label=u[2],a.ops.push(g);break}if(u[2])a.ops.pop();a.trys.pop();continue}g=o.call(s,a)}catch(m){g=[6,m],c=0}finally{l=u=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Rc=function(s,o){for(var a in s)if(a!=="default"&&!Object.prototype.hasOwnProperty.call(o,a))Hi(o,s,a)},Hi=Object.create?function(s,o,a,l){if(l===void 0)l=a;var c=Object.getOwnPropertyDescriptor(o,a);if(!c||("get"in c?!o.__esModule:c.writable||c.configurable))c={enumerable:!0,get:function(){return o[a]}};Object.defineProperty(s,l,c)}:function(s,o,a,l){if(l===void 0)l=a;s[l]=o[a]},Ui=function(s){var o=typeof Symbol==="function"&&Symbol.iterator,a=o&&s[o],l=0;if(a)return a.call(s);if(s&&typeof s.length==="number")return{next:function(){if(s&&l>=s.length)s=void 0;return{value:s&&s[l++],done:!s}}};throw TypeError(o?"Object is not iterable.":"Symbol.iterator is not defined.")},To=function(s,o){var a=typeof Symbol==="function"&&s[Symbol.iterator];if(!a)return s;var l=a.call(s),c,u=[],d;try{while((o===void 0||o-- >0)&&!(c=l.next()).done)u.push(c.value)}catch(A){d={error:A}}finally{try{if(c&&!c.done&&(a=l.return))a.call(l)}finally{if(d)throw d.error}}return u},Tc=function(){for(var s=[],o=0;o<arguments.length;o++)s=s.concat(To(arguments[o]));return s},Bc=function(){for(var s=0,o=0,a=arguments.length;o<a;o++)s+=arguments[o].length;for(var l=Array(s),c=0,o=0;o<a;o++)for(var u=arguments[o],d=0,A=u.length;d<A;d++,c++)l[c]=u[d];return l},Oc=function(s,o,a){if(a||arguments.length===2){for(var l=0,c=o.length,u;l<c;l++)if(u||!(l in o)){if(!u)u=Array.prototype.slice.call(o,0,l);u[l]=o[l]}}return s.concat(u||Array.prototype.slice.call(o))},Xr=function(s){return this instanceof Xr?(this.v=s,this):new Xr(s)},Pc=function(s,o,a){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var l=a.apply(s,o||[]),c,u=[];return c=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),A("next"),A("throw"),A("return",d),c[Symbol.asyncIterator]=function(){return this},c;function d(y){return function(E){return Promise.resolve(E).then(y,p)}}function A(y,E){if(l[y]){if(c[y]=function(_){return new Promise(function(b,w){u.push([y,_,b,w])>1||f(y,_)})},E)c[y]=E(c[y])}}function f(y,E){try{g(l[y](E))}catch(_){v(u[0][3],_)}}function g(y){y.value instanceof Xr?Promise.resolve(y.value.v).then(m,p):v(u[0][2],y)}function m(y){f("next",y)}function p(y){f("throw",y)}function v(y,E){if(y(E),u.shift(),u.length)f(u[0][0],u[0][1])}},Dc=function(s){var o,a;return o={},l("next"),l("throw",function(c){throw c}),l("return"),o[Symbol.iterator]=function(){return this},o;function l(c,u){o[c]=s[c]?function(d){return(a=!a)?{value:Xr(s[c](d)),done:!1}:u?u(d):d}:u}},Nc=function(s){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var o=s[Symbol.asyncIterator],a;return o?o.call(s):(s=typeof Ui==="function"?Ui(s):s[Symbol.iterator](),a={},l("next"),l("throw"),l("return"),a[Symbol.asyncIterator]=function(){return this},a);function l(u){a[u]=s[u]&&function(d){return new Promise(function(A,f){d=s[u](d),c(A,f,d.done,d.value)})}}function c(u,d,A,f){Promise.resolve(f).then(function(g){u({value:g,done:A})},d)}},Mc=function(s,o){if(Object.defineProperty)Object.defineProperty(s,"raw",{value:o});else s.raw=o;return s};var r=Object.create?function(s,o){Object.defineProperty(s,"default",{enumerable:!0,value:o})}:function(s,o){s.default=o},n=function(s){return n=Object.getOwnPropertyNames||function(o){var a=[];for(var l in o)if(Object.prototype.hasOwnProperty.call(o,l))a[a.length]=l;return a},n(s)};Lc=function(s){if(s&&s.__esModule)return s;var o={};if(s!=null){for(var a=n(s),l=0;l<a.length;l++)if(a[l]!=="default")Hi(o,s,a[l])}return r(o,s),o},Fc=function(s){return s&&s.__esModule?s:{default:s}},Gc=function(s,o,a,l){if(a==="a"&&!l)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?s!==o||!l:!o.has(s))throw TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?l:a==="a"?l.call(s):l?l.value:o.get(s)},Uc=function(s,o,a,l,c){if(l==="m")throw TypeError("Private method is not writable");if(l==="a"&&!c)throw TypeError("Private accessor was defined without a setter");if(typeof o==="function"?s!==o||!c:!o.has(s))throw TypeError("Cannot write private member to an object whose class did not declare it");return l==="a"?c.call(s,a):c?c.value=a:o.set(s,a),a},Hc=function(s,o){if(o===null||typeof o!=="object"&&typeof o!=="function")throw TypeError("Cannot use 'in' operator on non-object");return typeof s==="function"?o===s:s.has(o)},jc=function(s,o,a){if(o!==null&&o!==void 0){if(typeof o!=="object"&&typeof o!=="function")throw TypeError("Object expected.");var l,c;if(a){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");l=o[Symbol.asyncDispose]}if(l===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(l=o[Symbol.dispose],a)c=l}if(typeof l!=="function")throw TypeError("Object not disposable.");if(c)l=function(){try{c.call(this)}catch(u){return Promise.reject(u)}};s.stack.push({value:o,dispose:l,async:a})}else if(a)s.stack.push({async:!0});return o};var i=typeof SuppressedError==="function"?SuppressedError:function(s,o,a){var l=Error(a);return l.name="SuppressedError",l.error=s,l.suppressed=o,l};Kc=function(s){function o(u){s.error=s.hasError?new i(u,s.error,"An error was suppressed during disposal."):u,s.hasError=!0}var a,l=0;function c(){while(a=s.stack.pop())try{if(!a.async&&l===1)return l=0,s.stack.push(a),Promise.resolve().then(c);if(a.dispose){var u=a.dispose.call(a.value);if(a.async)return l|=2,Promise.resolve(u).then(c,function(d){return o(d),c()})}else l|=1}catch(d){o(d)}if(l===1)return s.hasError?Promise.reject(s.error):Promise.resolve();if(s.hasError)throw s.error}return c()},Wc=function(s,o){if(typeof s==="string"&&/^\.\.?\//.test(s))return s.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(a,l,c,u,d){return l?o?".jsx":".js":c&&(!u||!d)?a:c+u+"."+d.toLowerCase()+"js"});return s},e("__extends",pc),e("__assign",bc),e("__rest",yc),e("__decorate",wc),e("__param",vc),e("__esDecorate",_c),e("__runInitializers",Cc),e("__propKey",xc),e("__setFunctionName",Ec),e("__metadata",Sc),e("__awaiter",Ic),e("__generator",kc),e("__exportStar",Rc),e("__createBinding",Hi),e("__values",Ui),e("__read",To),e("__spread",Tc),e("__spreadArrays",Bc),e("__spreadArray",Oc),e("__await",Xr),e("__asyncGenerator",Pc),e("__asyncDelegator",Dc),e("__asyncValues",Nc),e("__makeTemplateObject",Mc),e("__importStar",Lc),e("__importDefault",Fc),e("__classPrivateFieldGet",Gc),e("__classPrivateFieldSet",Uc),e("__classPrivateFieldIn",Hc),e("__addDisposableResource",jc),e("__disposeResources",Kc),e("__rewriteRelativeImportExtension",Wc)})});import{CliRenderer as yh,createCliRenderer as wh,engine as vh}from"@opentui/core";import{createTestRenderer as eb}from"@opentui/core/testing";import{ASCIIFontRenderable as _h,BoxRenderable as Ch,CodeRenderable as xh,DiffRenderable as Eh,ImageRenderable as Sh,InputRenderable as Ih,LineNumberRenderable as kh,MarkdownRenderable as Rh,ScrollBoxRenderable as Th,SelectRenderable as Bh,TabSelectRenderable as Oh,TextareaRenderable as Ph,TextAttributes as Fs,TextNodeRenderable as Dh,TextRenderable as Nh}from"@opentui/core";import{engine as nb,Timeline as ib}from"@opentui/core";var ze={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Ea(this.context.count)},getNextContextId(){return Ea(this.context.count++)}};function Ea(e){let t=String(e),r=t.length-1;return ze.context.id+(r?String.fromCharCode(96+r):"")+t}function Rs(e){ze.context=e}function Jd(){return{...ze.context,id:ze.getNextContextId(),count:0}}var Vd=!1,$d=(e,t)=>e===t,Ts=Symbol("solid-proxy"),Zd=typeof Proxy==="function",Xd=Symbol("solid-track"),D0=Symbol("solid-dev-component"),Ai={equals:$d},Sa=null,Ba=La,bt=1,fn=2,Oa={owned:null,cleanups:null,context:null,owner:null};var le=null,D=null,mn=null,Dr=null,ve=null,Ue=null,tt=null,gi=0;function fr(e,t){let r=ve,n=le,i=e.length===0,s=t===void 0?n:t,o=i?Oa:{owned:null,cleanups:null,context:s?s.context:null,owner:s},a=i?e:()=>e(()=>yt(()=>rr(o)));le=o,ve=null;try{return Kt(a,!0)}finally{ve=r,le=n}}function j(e,t){t=t?Object.assign({},Ai,t):Ai;let r={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0},n=(i)=>{if(typeof i==="function")if(D&&D.running&&D.sources.has(r))i=i(r.tValue);else i=i(r.value);return Ma(r,i)};return[Na.bind(r),n]}function kt(e,t,r){let n=Ps(e,t,!1,bt);if(mn&&D&&D.running)Ue.push(n);else bn(n)}function mi(e,t,r){Ba=th;let n=Ps(e,t,!1,bt),i=Bs&&pn(Bs);if(i)n.suspense=i;if(!r||!r.render)n.user=!0;tt?tt.push(n):bn(n)}function K(e,t,r){r=r?Object.assign({},Ai,r):Ai;let n=Ps(e,t,!0,0);if(n.observers=null,n.observerSlots=null,n.comparator=r.equals||void 0,mn&&D&&D.running)n.tState=bt,Ue.push(n);else bn(n);return Na.bind(n)}function yt(e){if(!Dr&&ve===null)return e();let t=ve;ve=null;try{if(Dr)return Dr.untrack(e);return e()}finally{ve=t}}function gr(e){mi(()=>yt(e))}function ot(e){if(le===null);else if(le.cleanups===null)le.cleanups=[e];else le.cleanups.push(e);return e}function zd(e){if(D&&D.running)return e(),D.done;let t=ve,r=le;return Promise.resolve().then(()=>{ve=t,le=r;let n;if(mn||Bs)n=D||(D={sources:new Set,effects:[],promises:new Set,disposed:new Set,queue:new Set,running:!0}),n.done||(n.done=new Promise((i)=>n.resolve=i)),n.running=!0;return Kt(e,!1),ve=le=null,n?n.done:void 0})}var[N0,Ia]=j(!1);function Pa(e,t){let r=Symbol("context");return{id:r,Provider:nh(r),defaultValue:e}}function pn(e){let t;return le&&le.context&&(t=le.context[e.id])!==void 0?t:e.defaultValue}function Da(e){let t=K(e),r=K(()=>Os(t()));return r.toArray=()=>{let n=r();return Array.isArray(n)?n:n!=null?[n]:[]},r}var Bs;function Na(){let e=D&&D.running;if(this.sources&&(e?this.tState:this.state))if((e?this.tState:this.state)===bt)bn(this);else{let t=Ue;Ue=null,Kt(()=>fi(this),!1),Ue=t}if(ve){let t=this.observers?this.observers.length:0;if(!ve.sources)ve.sources=[this],ve.sourceSlots=[t];else ve.sources.push(this),ve.sourceSlots.push(t);if(!this.observers)this.observers=[ve],this.observerSlots=[ve.sources.length-1];else this.observers.push(ve),this.observerSlots.push(ve.sources.length-1)}if(e&&D.sources.has(this))return this.tValue;return this.value}function Ma(e,t,r){let n=D&&D.running&&D.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(n,t)){if(D){let i=D.running;if(i||!r&&D.sources.has(e))D.sources.add(e),e.tValue=t;if(!i)e.value=t}else e.value=t;if(e.observers&&e.observers.length)Kt(()=>{for(let i=0;i<e.observers.length;i+=1){let s=e.observers[i],o=D&&D.running;if(o&&D.disposed.has(s))continue;if(o?!s.tState:!s.state){if(s.pure)Ue.push(s);else tt.push(s);if(s.observers)Fa(s)}if(!o)s.state=bt;else s.tState=bt}if(Ue.length>1e6)throw Ue=[],Error()},!1)}return t}function bn(e){if(!e.fn)return;rr(e);let t=gi;if(ka(e,D&&D.running&&D.sources.has(e)?e.tValue:e.value,t),D&&!D.running&&D.sources.has(e))queueMicrotask(()=>{Kt(()=>{D&&(D.running=!0),ve=le=e,ka(e,e.tValue,t),ve=le=null},!1)})}function ka(e,t,r){let n,i=le,s=ve;ve=le=e;try{n=e.fn(t)}catch(o){if(e.pure)if(D&&D.running)e.tState=bt,e.tOwned&&e.tOwned.forEach(rr),e.tOwned=void 0;else e.state=bt,e.owned&&e.owned.forEach(rr),e.owned=null;return e.updatedAt=r+1,Ds(o)}finally{ve=s,le=i}if(!e.updatedAt||e.updatedAt<=r){if(e.updatedAt!=null&&"observers"in e)Ma(e,n,!0);else if(D&&D.running&&e.pure){if(!D.sources.has(e))e.value=n;D.sources.add(e),e.tValue=n}else e.value=n;e.updatedAt=r}}function Ps(e,t,r,n=bt,i){let s={fn:e,state:n,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:le,context:le?le.context:null,pure:r};if(D&&D.running)s.state=0,s.tState=n;if(le===null);else if(le!==Oa)if(D&&D.running&&le.pure)if(!le.tOwned)le.tOwned=[s];else le.tOwned.push(s);else if(!le.owned)le.owned=[s];else le.owned.push(s);if(Dr&&s.fn){let o=s.fn,[a,l]=j(void 0,{equals:!1}),c=Dr.factory(o,l);ot(()=>c.dispose());let u,d=()=>zd(l).then(()=>{if(u)u.dispose(),u=void 0});s.fn=(A)=>{if(a(),D&&D.running){if(!u)u=Dr.factory(o,d);return u.track(A)}return c.track(A)}}return s}function gn(e){let t=D&&D.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===fn)return fi(e);if(e.suspense&&yt(e.suspense.inFallback))return e.suspense.effects.push(e);let r=[e];while((e=e.owner)&&(!e.updatedAt||e.updatedAt<gi)){if(t&&D.disposed.has(e))return;if(t?e.tState:e.state)r.push(e)}for(let n=r.length-1;n>=0;n--){if(e=r[n],t){let i=e,s=r[n+1];while((i=i.owner)&&i!==s)if(D.disposed.has(i))return}if((t?e.tState:e.state)===bt)bn(e);else if((t?e.tState:e.state)===fn){let i=Ue;Ue=null,Kt(()=>fi(e,r[0]),!1),Ue=i}}}function Kt(e,t){if(Ue)return e();let r=!1;if(!t)Ue=[];if(tt)r=!0;else tt=[];gi++;try{let n=e();return qd(r),n}catch(n){if(!r)tt=null;Ue=null,Ds(n)}}function qd(e){if(Ue){if(mn&&D&&D.running)eh(Ue);else La(Ue);Ue=null}if(e)return;let t;if(D){if(!D.promises.size&&!D.queue.size){let{sources:n,disposed:i}=D;tt.push.apply(tt,D.effects),t=D.resolve;for(let s of tt)"tState"in s&&(s.state=s.tState),delete s.tState;D=null,Kt(()=>{for(let s of i)rr(s);for(let s of n){if(s.value=s.tValue,s.owned)for(let o=0,a=s.owned.length;o<a;o++)rr(s.owned[o]);if(s.tOwned)s.owned=s.tOwned;delete s.tValue,delete s.tOwned,s.tState=0}Ia(!1)},!1)}else if(D.running){D.running=!1,D.effects.push.apply(D.effects,tt),tt=null,Ia(!0);return}}let r=tt;if(tt=null,r.length)Kt(()=>Ba(r),!1);if(t)t()}function La(e){for(let t=0;t<e.length;t++)gn(e[t])}function eh(e){for(let t=0;t<e.length;t++){let r=e[t],n=D.queue;if(!n.has(r))n.add(r),mn(()=>{n.delete(r),Kt(()=>{D.running=!0,gn(r)},!1),D&&(D.running=!1)})}}function th(e){let t,r=0;for(t=0;t<e.length;t++){let n=e[t];if(!n.user)gn(n);else e[r++]=n}if(ze.context){if(ze.count){ze.effects||(ze.effects=[]),ze.effects.push(...e.slice(0,r));return}Rs()}if(ze.effects&&(ze.done||!ze.count))e=[...ze.effects,...e],r+=ze.effects.length,delete ze.effects;for(t=0;t<r;t++)gn(e[t])}function fi(e,t){let r=D&&D.running;if(r)e.tState=0;else e.state=0;for(let n=0;n<e.sources.length;n+=1){let i=e.sources[n];if(i.sources){let s=r?i.tState:i.state;if(s===bt){if(i!==t&&(!i.updatedAt||i.updatedAt<gi))gn(i)}else if(s===fn)fi(i,t)}}}function Fa(e){let t=D&&D.running;for(let r=0;r<e.observers.length;r+=1){let n=e.observers[r];if(t?!n.tState:!n.state){if(t)n.tState=fn;else n.state=fn;if(n.pure)Ue.push(n);else tt.push(n);n.observers&&Fa(n)}}}function rr(e){let t;if(e.sources)while(e.sources.length){let r=e.sources.pop(),n=e.sourceSlots.pop(),i=r.observers;if(i&&i.length){let s=i.pop(),o=r.observerSlots.pop();if(n<i.length)s.sourceSlots[o]=n,i[n]=s,r.observerSlots[n]=o}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)rr(e.tOwned[t]);delete e.tOwned}if(D&&D.running&&e.pure)Ga(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)rr(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}if(D&&D.running)e.tState=0;else e.state=0}function Ga(e,t){if(!t)e.tState=0,D.disposed.add(e);if(e.owned)for(let r=0;r<e.owned.length;r++)Ga(e.owned[r])}function rh(e){if(e instanceof Error)return e;return Error(typeof e==="string"?e:"Unknown error",{cause:e})}function Ra(e,t,r){try{for(let n of t)n(e)}catch(n){Ds(n,r&&r.owner||null)}}function Ds(e,t=le){let r=Sa&&t&&t.context&&t.context[Sa],n=rh(e);if(!r)throw n;if(tt)tt.push({fn(){Ra(n,r,t)},state:bt});else Ra(n,r,t)}function Os(e){if(typeof e==="function"&&!e.length)return Os(e());if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++){let n=Os(e[r]);Array.isArray(n)?t.push.apply(t,n):t.push(n)}return t}return e}function nh(e,t){return function(n){let i;return kt(()=>i=yt(()=>(le.context={...le.context,[e]:n.value},Da(()=>n.children))),void 0),i}}var ih=Symbol("fallback");function Ta(e){for(let t=0;t<e.length;t++)e[t]()}function sh(e,t,r={}){let n=[],i=[],s=[],o=0,a=t.length>1?[]:null;return ot(()=>Ta(s)),()=>{let l=e()||[],c=l.length,u,d;return l[Xd],yt(()=>{let f,g,m,p,v,y,E,_,b;if(c===0){if(o!==0)Ta(s),s=[],n=[],i=[],o=0,a&&(a=[]);if(r.fallback)n=[ih],i[0]=fr((w)=>(s[0]=w,r.fallback())),o=1}else if(o===0){i=Array(c);for(d=0;d<c;d++)n[d]=l[d],i[d]=fr(A);o=c}else{m=Array(c),p=Array(c),a&&(v=Array(c));for(y=0,E=Math.min(o,c);y<E&&n[y]===l[y];y++);for(E=o-1,_=c-1;E>=y&&_>=y&&n[E]===l[_];E--,_--)m[_]=i[E],p[_]=s[E],a&&(v[_]=a[E]);f=new Map,g=Array(_+1);for(d=_;d>=y;d--)b=l[d],u=f.get(b),g[d]=u===void 0?-1:u,f.set(b,d);for(u=y;u<=E;u++)if(b=n[u],d=f.get(b),d!==void 0&&d!==-1)m[d]=i[u],p[d]=s[u],a&&(v[d]=a[u]),d=g[d],f.set(b,d);else s[u]();for(d=y;d<c;d++)if(d in m){if(i[d]=m[d],s[d]=p[d],a)a[d]=v[d],a[d](d)}else i[d]=fr(A);i=i.slice(0,o=c),n=l.slice(0)}return i});function A(f){if(s[d]=f,a){let[g,m]=j(d);return a[d]=m,t(l[d],g)}return t(l[d])}}}var oh=!1;function Ua(e,t){if(oh){if(ze.context){let r=ze.context;Rs(Jd());let n=yt(()=>e(t||{}));return Rs(r),n}}return yt(()=>e(t||{}))}function hi(){return!0}var ah={get(e,t,r){if(t===Ts)return r;return e.get(t)},has(e,t){if(t===Ts)return!0;return e.has(t)},set:hi,deleteProperty:hi,getOwnPropertyDescriptor(e,t){return{configurable:!0,enumerable:!0,get(){return e.get(t)},set:hi,deleteProperty:hi}},ownKeys(e){return e.keys()}};function ks(e){return!(e=typeof e==="function"?e():e)?{}:e}function lh(){for(let e=0,t=this.length;e<t;++e){let r=this[e]();if(r!==void 0)return r}}function pi(...e){let t=!1;for(let o=0;o<e.length;o++){let a=e[o];t=t||!!a&&Ts in a,e[o]=typeof a==="function"?(t=!0,K(a)):a}if(Zd&&t)return new Proxy({get(o){for(let a=e.length-1;a>=0;a--){let l=ks(e[a])[o];if(l!==void 0)return l}},has(o){for(let a=e.length-1;a>=0;a--)if(o in ks(e[a]))return!0;return!1},keys(){let o=[];for(let a=0;a<e.length;a++)o.push(...Object.keys(ks(e[a])));return[...new Set(o)]}},ah);let r={},n=Object.create(null);for(let o=e.length-1;o>=0;o--){let a=e[o];if(!a)continue;let l=Object.getOwnPropertyNames(a);for(let c=l.length-1;c>=0;c--){let u=l[c];if(u==="__proto__"||u==="constructor")continue;let d=Object.getOwnPropertyDescriptor(a,u);if(!n[u])n[u]=d.get?{enumerable:!0,configurable:!0,get:lh.bind(r[u]=[d.get.bind(a)])}:d.value!==void 0?d:void 0;else{let A=r[u];if(A){if(d.get)A.push(d.get.bind(a));else if(d.value!==void 0)A.push(()=>d.value)}}}}let i={},s=Object.keys(n);for(let o=s.length-1;o>=0;o--){let a=s[o],l=n[a];if(l&&l.get)Object.defineProperty(i,a,l);else i[a]=l?l.value:void 0}return i}var ch=(e)=>`Stale read from <${e}>.`;function wt(e){let t="fallback"in e&&{fallback:()=>e.fallback};return K(sh(()=>e.each,e.children,t||void 0))}function ke(e){let t=e.keyed,r=K(()=>e.when,void 0,void 0),n=t?r:K(r,void 0,{equals:(i,s)=>!i===!s});return K(()=>{let i=n();if(i){let s=e.children;return typeof s==="function"&&s.length>0?yt(()=>s(t?i:()=>{if(!yt(n))throw ch("Show");return r()})):s}return e.fallback},void 0,void 0)}import{BaseRenderable as ol,createTextAttributes as Gh,ImageRenderable as $a,InputRenderable as Gs,InputRenderableEvents as wn,isTextNodeRenderable as Ws,isEditBufferRenderable as Uh,parseColor as Za,Renderable as Hh,RootTextNodeRenderable as jh,ScrollBoxRenderable as Kh,SelectRenderable as Xa,SelectRenderableEvents as Us,TabSelectRenderable as za,TabSelectRenderableEvents as Hs,TextNodeRenderable as Wh,TextRenderable as al}from"@opentui/core";var Ns,uh=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),Ha=(Ns=String.fromCodePoint)!==null&&Ns!==void 0?Ns:(e)=>{let t="";if(e>65535)e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|e&1023;return t+=String.fromCharCode(e),t};function ja(e){var t;if(e>=55296&&e<=57343||e>1114111)return 65533;return(t=uh.get(e))!==null&&t!==void 0?t:e}function Ka(e){let t=typeof atob==="function"?atob(e):typeof Buffer.from==="function"?Buffer.from(e,"base64").toString("binary"):new Buffer(e,"base64").toString("binary"),r=t.length&-2,n=new Uint16Array(r/2);for(let i=0,s=0;i<r;i+=2){let o=t.charCodeAt(i),a=t.charCodeAt(i+1);n[s++]=o|a<<8}return n}var Wa=Ka("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBK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FqbiYvKC8AoA0gagAAoAwg");var rt;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(rt||(rt={}));var Ee;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"})(Ee||(Ee={}));var Ya=32;function Ms(e){return e>=Ee.ZERO&&e<=Ee.NINE}function dh(e){return e>=Ee.UPPER_A&&e<=Ee.UPPER_F||e>=Ee.LOWER_A&&e<=Ee.LOWER_F}function hh(e){return e>=Ee.UPPER_A&&e<=Ee.UPPER_Z||e>=Ee.LOWER_A&&e<=Ee.LOWER_Z||Ms(e)}function Ah(e){return e===Ee.EQUALS||hh(e)}var Je;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(Je||(Je={}));var Wt;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Wt||(Wt={}));class Ls{constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r,this.state=Je.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=Wt.Strict,this.runConsumed=0}startEntity(e){this.decodeMode=e,this.state=Je.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case Je.EntityStart:{if(e.charCodeAt(t)===Ee.NUM)return this.state=Je.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=Je.NamedEntity,this.stateNamedEntity(e,t)}case Je.NumericStart:return this.stateNumericStart(e,t);case Je.NumericDecimal:return this.stateNumericDecimal(e,t);case Je.NumericHex:return this.stateNumericHex(e,t);case Je.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|Ya)===Ee.LOWER_X)return this.state=Je.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=Je.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){while(t<e.length){let r=e.charCodeAt(t);if(Ms(r)||dh(r)){let n=r<=Ee.NINE?r-Ee.ZERO:(r|Ya)-Ee.LOWER_A+10;this.result=this.result*16+n,this.consumed++,t++}else return this.emitNumericEntity(r,3)}return-1}stateNumericDecimal(e,t){while(t<e.length){let r=e.charCodeAt(t);if(Ms(r))this.result=this.result*10+(r-Ee.ZERO),this.consumed++,t++;else return this.emitNumericEntity(r,2)}return-1}emitNumericEntity(e,t){var r;if(this.consumed<=t)return(r=this.errors)===null||r===void 0||r.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===Ee.SEMI)this.consumed+=1;else if(this.decodeMode===Wt.Strict)return 0;if(this.emitCodePoint(ja(this.result),this.consumed),this.errors){if(e!==Ee.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}stateNamedEntity(e,t){let{decodeTree:r}=this,n=r[this.treeIndex],i=(n&rt.VALUE_LENGTH)>>14;while(t<e.length){if(i===0&&(n&rt.FLAG13)!==0){let o=(n&rt.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let a=n&rt.JUMP_TABLE;if(e.charCodeAt(t)!==a)return this.result===0?0:this.emitNotTerminatedNamedEntity();t++,this.excess++,this.runConsumed++}while(this.runConsumed<o){if(t>=e.length)return-1;let a=this.runConsumed-1,l=r[this.treeIndex+1+(a>>1)],c=a%2===0?l&255:l>>8&255;if(e.charCodeAt(t)!==c)return this.runConsumed=0,this.result===0?0:this.emitNotTerminatedNamedEntity();t++,this.excess++,this.runConsumed++}this.runConsumed=0,this.treeIndex+=1+(o>>1),n=r[this.treeIndex],i=(n&rt.VALUE_LENGTH)>>14}if(t>=e.length)break;let s=e.charCodeAt(t);if(s===Ee.SEMI&&i!==0&&(n&rt.FLAG13)!==0)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=gh(r,n,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return this.result===0||this.decodeMode===Wt.Attribute&&(i===0||Ah(s))?0:this.emitNotTerminatedNamedEntity();if(n=r[this.treeIndex],i=(n&rt.VALUE_LENGTH)>>14,i!==0){if(s===Ee.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.decodeMode!==Wt.Strict&&(n&rt.FLAG13)===0)this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0}t++,this.excess++}return-1}emitNotTerminatedNamedEntity(){var e;let{result:t,decodeTree:r}=this,n=(r[t]&rt.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,n,this.consumed),(e=this.errors)===null||e===void 0||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){let{decodeTree:n}=this;if(this.emitCodePoint(t===1?n[e]&~(rt.VALUE_LENGTH|rt.FLAG13):n[e+1],r),t===3)this.emitCodePoint(n[e+2],r);return r}end(){var e;switch(this.state){case Je.NamedEntity:return this.result!==0&&(this.decodeMode!==Wt.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Je.NumericDecimal:return this.emitNumericEntity(0,2);case Je.NumericHex:return this.emitNumericEntity(0,3);case Je.NumericStart:return(e=this.errors)===null||e===void 0||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Je.EntityStart:return 0}}}function fh(e){let t="",r=new Ls(e,(n)=>t+=Ha(n));return function(i,s){let o=0,a=0;while((a=i.indexOf("&",a))>=0){t+=i.slice(o,a),r.startEntity(s);let c=r.write(i,a+1);if(c<0){o=a+r.end();break}o=a+c,a=c===0?o+1:o}let l=t+i.slice(o);return t="",l}}function gh(e,t,r,n){let i=(t&rt.BRANCH_LENGTH)>>7,s=t&rt.JUMP_TABLE;if(i===0)return s!==0&&n===s?r:-1;if(s){let c=n-s;return c<0||c>=i?-1:e[r+c]-1}let o=i+1>>1,a=0,l=i-1;while(a<=l){let c=a+l>>>1,u=c>>1,A=e[r+u]>>(c&1)*8&255;if(A<n)a=c+1;else if(A>n)l=c-1;else return e[r+o+c]}return-1}var mh=fh(Wa);function yn(e){return mh(e,Wt.Strict)}var Qa;(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(Qa||(Qa={}));var Ja;(function(e){e[e.UTF8=0]="UTF8",e[e.ASCII=1]="ASCII",e[e.Extensive=2]="Extensive",e[e.Attribute=3]="Attribute",e[e.Text=4]="Text"})(Ja||(Ja={}));import{BaseRenderable as zh,isTextNodeRenderable as qh,TextNodeRenderable as eA,TextRenderable as tA,Yoga as ll}from"@opentui/core";import{BoxRenderable as pb,RootRenderable as bb}from"@opentui/core";import{TimeToFirstDrawRenderable as nA}from"@opentui/core";import{createSlotRegistry as _b}from"@opentui/core";class vn extends Dh{_ctx;constructor(e,t){super(t);this._ctx=e}}class yi extends vn{constructor(e,t){super(null,e);if(t==="b"||t==="strong")this.attributes=(this.attributes||0)|Fs.BOLD;else if(t==="i"||t==="em")this.attributes=(this.attributes||0)|Fs.ITALIC;else if(t==="u")this.attributes=(this.attributes||0)|Fs.UNDERLINE}}class js extends yi{constructor(e){super(e,"b")}}class Ks extends yi{constructor(e){super(e,"i")}}class rl extends yi{constructor(e){super(e,"u")}}class nl extends vn{constructor(e,t){super(null,t);this.add()}add(){return super.add(`
7
- `)}}class il extends vn{constructor(e,t){let r={...t,link:{url:t.href}};super(null,r)}}var Mh={box:Ch,text:Nh,input:Ih,select:Bh,textarea:Ph,ascii_font:_h,tab_select:Oh,scrollbox:Th,code:xh,diff:Eh,line_number:kh,markdown:Rh,image:Sh,span:vn,strong:js,b:js,em:Ks,i:Ks,u:rl,br:nl,a:il},sl={...Mh};function Yt(e){Object.assign(sl,e)}function Lh(){return sl}var Vs=Pa(),ht=()=>{let e=pn(Vs);if(!e)throw Error("No renderer found");return e},Fh=(e)=>{let t=ht();gr(()=>{t.on("resize",e)}),ot(()=>{t.off("resize",e)})},Lr=()=>{let e=ht(),[t,r]=j({width:e.width,height:e.height});return Fh((i,s)=>{r({width:i,height:s})}),t},Fr=(e,t)=>{let n=ht().keyInput;gr(()=>{if(n.on("keypress",e),t?.release)n.on("keyrelease",e)}),ot(()=>{if(n.off("keypress",e),t?.release)n.off("keyrelease",e)})};var Yh=(e)=>K(()=>e());function Qh({createElement:e,createTextNode:t,createDynamicTextNode:r,createSlotNode:n,isTextNode:i,replaceText:s,insertNode:o,removeNode:a,setProperty:l,getParentNode:c,getFirstChild:u,getNextSibling:d}){function A(_,b,w,C){if(w!==void 0&&!C)C=[];if(typeof b!=="function")return f(_,b,C,w);kt((O)=>f(_,b(),O,w),C)}function f(_,b,w,C,O){while(typeof w==="function")w=w();if(b===w)return w;let N=typeof b,P=C!==void 0;if(N==="string"||N==="number"){if(N==="number")b=b.toString();if(P){let R=w[0];if(R&&i(R))s(R,b);else R=r(b);w=p(_,w,C,R)}else if(w!==""&&typeof w==="string")s(u(_),w=b);else p(_,w,C,r(b)),w=b}else if(b==null||N==="boolean")w=p(_,w,C);else if(N==="function")return kt(()=>{let R=b();while(typeof R==="function")R=R();w=f(_,R,w,C)}),()=>w;else if(Array.isArray(b)){let R=[];if(g(R,b,O))return kt(()=>w=f(_,R,w,C,!0)),()=>w;if(R.length===0){let U=p(_,w,C);if(P)return w=U}else if(Array.isArray(w))if(w.length===0)v(_,R,C);else m(_,w,R);else if(w==null||w==="")v(_,R);else m(_,P&&w||[u(_)],R);w=R}else{if(Array.isArray(w)){if(P)return w=p(_,w,C,b);p(_,w,null,b)}else if(w==null||w===""||!u(_))o(_,b);else y(_,b,u(_));w=b}return w}function g(_,b,w){let C=!1;for(let O=0,N=b.length;O<N;O++){let P=b[O],R;if(P==null||P===!0||P===!1);else if(Array.isArray(P))C=g(_,P)||C;else if((R=typeof P)==="string"||R==="number")_.push(r(P));else if(R==="function")if(w){while(typeof P==="function")P=P();C=g(_,Array.isArray(P)?P:[P])||C}else _.push(P),C=!0;else _.push(P)}return C}function m(_,b,w){let C=w.length,O=b.length,N=C,P=0,R=0,U=d(b[O-1]),X=null;while(P<O||R<N){if(b[P]===w[R]){P++,R++;continue}while(b[O-1]===w[N-1])O--,N--;if(O===P){let V=N<C?R?d(w[R-1]):w[N-R]:U;while(R<N)o(_,w[R++],V)}else if(N===R)while(P<O){if(!X||!X.has(b[P]))a(_,b[P]);P++}else if(b[P]===w[N-1]&&w[R]===b[O-1]){let V=d(b[--O]);o(_,w[R++],d(b[P++])),o(_,w[--N],V),b[O]=w[N]}else{if(!X){X=new Map;let te=R;while(te<N)X.set(w[te],te++)}let V=X.get(b[P]);if(V!=null)if(R<V&&V<N){let te=P,ge=1,z;while(++te<O&&te<N){if((z=X.get(b[te]))==null||z!==V+ge)break;ge++}if(ge>V-R){let Me=b[P];while(R<V)o(_,w[R++],Me)}else y(_,w[R++],b[P++])}else P++;else a(_,b[P++])}}}function p(_,b,w,C){if(w===void 0){let N;while(N=u(_))a(_,N);return C&&o(_,C),C??""}let O=C||n();if(b.length){let N=!1;for(let P=b.length-1;P>=0;P--){let R=b[P];if(O!==R){let U=c(R)===_;if(!N&&!P)U?y(_,O,R):o(_,O,w);else U&&a(_,R)}else N=!0}}else o(_,O,w);return[O]}function v(_,b,w){for(let C=0,O=b.length;C<O;C++)o(_,b[C],w)}function y(_,b,w){o(_,b,w),a(_,w)}function E(_,b,w={},C){if(b||(b={}),!C)kt(()=>w.children=f(_,b.children,w.children));return kt(()=>b.ref&&b.ref(_)),kt(()=>{for(let O in b){if(O==="children"||O==="ref")continue;let N=b[O];if(N===w[O])continue;l(_,O,N,w[O]),w[O]=N}}),w}return{render(_,b){let w;return fr((C)=>{w=C,A(b,_())}),w},insert:A,spread(_,b,w){if(typeof b==="function")kt((C)=>E(_,b(),C,w));else E(_,b,void 0,w)},createElement:e,createTextNode:t,insertNode:o,setProp(_,b,w,C){return l(_,b,w,C),w},mergeProps:pi,effect:kt,memo:Yh,createComponent:Ua,use(_,b,w){return yt(()=>_(b,w))}}}function Jh(e){let t=Qh(e);return t.mergeProps=pi,t}var bi=new Map;function $s(e){if(!bi.has(e))bi.set(e,0);let t=bi.get(e)+1;return bi.set(e,t),`${e}-${t}`}var Ve=(...e)=>{if(process.env.DEBUG)console.log("[Reconciler]",...e)};class Nr extends Wh{static fromString(e,t={}){let r=new Nr(t);return r.add(e),r}}var He=(e)=>{if(!e)return;return e.id},Ys=(e)=>{let t;if(e instanceof al)t=e.getTextChildren();else t=e.getChildren();return t};function Vh(e,t,r){if(Ve("Inserting node:",He(t),"into parent:",He(e),"with anchor:",He(r),t instanceof Nr),t instanceof Mr)t.parent=e,t=t.getSlotChild(e);if(r&&r instanceof Mr)r=r.getSlotChild(e);if(Ws(t)){if(!(e instanceof al)&&!Ws(e))throw Error(`Orphan text error: "${t.toChunks().map((s)=>s.text).join("")}" must have a <text> as a parent: ${e.id} above ${t.id}`)}if(!(e instanceof ol))throw console.error("[INSERT]","Tried to mount a non base renderable"),Error("Tried to mount a non base renderable");if(!r){e.add(t);return}let n=Ys(e),i=n.indexOf(r);if(i===-1)Ve("[INSERT]","Could not find anchor",He(e),He(r),"[children]",...n.map((s)=>s.id));e.add(t,i)}function $h(e,t){Ve("Removing node:",He(t),"from parent:",He(e));let r;if(t instanceof Mr){r=t;let n=r.getSlotChildForRemoval(e);if(!n){if(r.parent===e)r.parent=null;return}t=n}e.remove(t),r?.didRemoveSlotChild(e,t),process.nextTick(()=>{if(t instanceof ol&&!t.parent){t.destroyRecursively();return}})}function qa(e,t){Ve("Creating text node:",e);let r=$s("text-node");if(typeof e==="number")e=e.toString();return Nr.fromString(t?yn(e):e,{id:r})}function Zh(){let e=$s("slot-node");return Ve("Creating slot node",e),new Mr(e)}function el(e){Ve("Getting parent of node:",He(e));let t=e.parent??void 0;if(t instanceof jh)t=t.textParent??void 0;let r=t?.parent?.parent?.parent;if(r instanceof Kh&&r.content===t)t=r;return t}var{render:Xh,effect:de,memo:lt,createComponent:Q,createElement:S,createTextNode:Re,insertNode:k,insert:L,spread:hb,setProp:h,mergeProps:Ab,use:fb}=Jh({createElement(e){Ve("Creating element:",e);let t=$s(e),r=pn(Vs);if(!r)throw Error("No renderer found");let n=Lh();if(!n[e])throw Error(`[Reconciler] Unknown component type: ${e}`);let i=new n[e](r,{id:t});if(i instanceof $a)ot(()=>{i.source=void 0});return Ve("Element created with id:",t),i},createTextNode:(e)=>qa(e,!0),createDynamicTextNode:(e)=>qa(e,!1),createSlotNode:Zh,replaceText(e,t){if(Ve("Replacing text:",t,"in node:",He(e)),!(e instanceof Nr))return;e.replace(t,0)},setProperty(e,t,r,n){if(t.startsWith("on:")){let i=t.slice(3);if(r)e.on(i,r);if(n)e.off(i,n);return}if(Ws(e)){if(t==="href"){e.link={url:r};return}if(t==="style"){e.attributes|=Gh(r),e.fg=r.fg?Za(r.fg):e.fg,e.bg=r.bg?Za(r.bg):e.bg;return}return}switch(t){case"id":Ve("Id mapped",e.id,"=",r),e[t]=r;break;case"focused":if(!(e instanceof Hh))return;if(r)e.focus();else e.blur();break;case"onChange":let i=void 0;if(e instanceof Xa)i=Us.SELECTION_CHANGED;else if(e instanceof za)i=Hs.SELECTION_CHANGED;else if(e instanceof Gs)i=wn.CHANGE;if(!i)break;if(r)e.on(i,r);if(n)e.off(i,n);break;case"onInput":if(e instanceof Gs){if(r)e.on(wn.INPUT,r);if(n)e.off(wn.INPUT,n)}break;case"onSubmit":if(e instanceof Gs){if(r)e.on(wn.ENTER,r);if(n)e.off(wn.ENTER,n)}else e[t]=r;break;case"onSelect":if(e instanceof Xa){if(r)e.on(Us.ITEM_SELECTED,r);if(n)e.off(Us.ITEM_SELECTED,n)}else if(e instanceof za){if(r)e.on(Hs.ITEM_SELECTED,r);if(n)e.off(Hs.ITEM_SELECTED,n)}break;case"style":let s=r??{},o=n??{};if(Uh(e)&&o.selectionOccupancy&&!s.selectionOccupancy)e.selectionOccupancy=void 0;if(e instanceof $a)for(let a in o){if(Object.prototype.hasOwnProperty.call(s,a))continue;if(a!=="fit"&&a!=="protocol")continue;e[a]=void 0}for(let a in s){let l=s[a];if(l===o[a])continue;e[a]=l}break;case"text":case"content":{let a=typeof r==="string"?r:Array.isArray(r)?r.join(""):`${r}`;e[t]=a;break}default:e[t]=r}},isTextNode(e){return e instanceof Nr},insertNode:Vh,removeNode:$h,getParentNode:el,getFirstChild(e){Ve("Getting first child of node:",He(e));let t=Ys(e)[0];if(!t){Ve("No first child found for node:",He(e));return}return Ve("First child found:",He(t),"for node:",He(e)),t},getNextSibling(e){Ve("Getting next sibling of node:",He(e));let t=el(e);if(!t){Ve("No parent found for node:",He(e));return}if(e instanceof Mr){let s=e.getSlotChildForRemoval(t);if(s)e=s}let r=Ys(t),n=r.indexOf(e);if(n===-1||n===r.length-1){Ve("No next sibling found for node:",He(e));return}let i=r[n+1];if(!i){Ve("Next sibling is null for node:",He(e));return}return Ve("Next sibling found:",He(i),"for node:",He(e)),i}});function tl(e){return e?.getLayoutNode?.()?.constructor}function rA(e){return e?.create?.()??ll.default.Node.create()}class Zs extends zh{constructor(e){super({id:e})}add(e,t){throw Error("Can't add children on an Slot renderable")}getChildren(){return[]}remove(e){}insertBefore(e,t){throw Error("Can't add children on an Slot renderable")}getRenderable(e){return}getChildrenCount(){return 0}requestRender(){}findDescendantById(e){return}}class Qs extends eA{slotParent;destroyed=!1;constructor(e,t){super({id:e});this._visible=!1,this.slotParent=t}detachFromSlot(){this.slotParent=void 0}disposeWithoutSlotCascade(){if(this.destroyed)return;this.destroyed=!0,this.detachFromSlot()}destroy(){if(this.destroyed)return;this.destroyed=!0;let e=this.slotParent;this.slotParent=void 0,e?.destroy(),super.destroy()}}class Js extends Zs{yogaNode;slotParent;destroyed=!1;yogaNodeConstructor;yogaNodeFreed=!1;constructor(e,t,r){super(e);this._visible=!1,this.slotParent=t,this.yogaNodeConstructor=tl(r),this.yogaNode=rA(this.yogaNodeConstructor),this.yogaNode.setDisplay(ll.Display.None)}getLayoutNode(){return this.yogaNode}updateFromLayout(){}updateLayout(){}onRemove(){}isCompatibleWith(e){return this.yogaNodeConstructor===tl(e)}detachFromSlot(){this.slotParent=void 0}freeYogaNode(){if(this.yogaNodeFreed)return;this.yogaNodeFreed=!0;try{this.yogaNode.free()}catch{}}disposeWithoutSlotCascade(){if(this.destroyed)return;this.destroyed=!0,this.detachFromSlot(),this.freeYogaNode()}destroy(){if(this.destroyed)return;this.destroyed=!0;let e=this.slotParent;this.slotParent=void 0,this.freeYogaNode(),e?.destroy()}}class Mr extends Zs{destroyed=!1;layoutNodesByParent=new Map;textNodesByParent=new Map;layoutNodeCount=0;textNodeCount=0;constructor(e){super(e);this._visible=!1}get layoutNode(){return this.getCurrentSlotChild(this.layoutNodesByParent)}get textNode(){return this.getCurrentSlotChild(this.textNodesByParent)}isTextSlotParent(e){return qh(e)||e instanceof tA}getCurrentSlotChild(e){for(let t of e.values())if(t.parent)return t;return e.values().next().value}getTextNodeForParent(e){let t=this.textNodesByParent.get(e);if(t)return t;for(let[r,n]of this.textNodesByParent){if(n.parent!==e)continue;return this.textNodesByParent.delete(r),this.textNodesByParent.set(e,n),n}}getLayoutNodeForParent(e){let t=this.layoutNodesByParent.get(e);if(t)return t;for(let[r,n]of this.layoutNodesByParent){if(n.parent!==e)continue;return this.layoutNodesByParent.delete(r),this.layoutNodesByParent.set(e,n),n}}takeReusableTextNode(e){for(let[t,r]of this.textNodesByParent){if(r.parent)continue;return this.textNodesByParent.delete(t),this.textNodesByParent.set(e,r),r}}takeReusableLayoutNode(e){for(let[t,r]of this.layoutNodesByParent){if(r.parent)continue;if(!r.isCompatibleWith(e))continue;return this.layoutNodesByParent.delete(t),this.layoutNodesByParent.set(e,r),r}}disposeDetachedTextNodes(){for(let[e,t]of this.textNodesByParent){if(t.parent)continue;this.textNodesByParent.delete(e),t.disposeWithoutSlotCascade()}}disposeDetachedIncompatibleLayoutNodes(e){for(let[t,r]of this.layoutNodesByParent){if(r.parent||r.isCompatibleWith(e))continue;this.layoutNodesByParent.delete(t),r.disposeWithoutSlotCascade()}}getAttachedSlotParent(e){for(let t of this.textNodesByParent.values())if(t!==e&&t.parent)return t.parent;for(let t of this.layoutNodesByParent.values())if(t!==e&&t.parent)return t.parent;return null}hasOtherAttachedSlotChildren(e){return this.getAttachedSlotParent(e)!==null}getSlotChild(e){if(this.isTextSlotParent(e)){let i=this.getTextNodeForParent(e);if(i)return i;let s=this.takeReusableTextNode(e);if(s)return s;this.disposeDetachedIncompatibleLayoutNodes(e);let o=new Qs(`slot-text-${this.id}-${++this.textNodeCount}`,this);return this.textNodesByParent.set(e,o),o}let t=this.getLayoutNodeForParent(e);if(t)return t;let r=this.takeReusableLayoutNode(e);if(r)return r;this.disposeDetachedTextNodes(),this.disposeDetachedIncompatibleLayoutNodes(e);let n=new Js(`slot-layout-${this.id}-${++this.layoutNodeCount}`,this,e);return this.layoutNodesByParent.set(e,n),n}getSlotChildForRemoval(e){if(this.isTextSlotParent(e))return this.getTextNodeForParent(e);return this.getLayoutNodeForParent(e)}didRemoveSlotChild(e,t){let r=this.hasOtherAttachedSlotChildren(t);if(r&&t instanceof Qs&&this.getTextNodeForParent(e)===t)this.textNodesByParent.delete(e),t.disposeWithoutSlotCascade();if(r&&t instanceof Js&&this.getLayoutNodeForParent(e)===t)this.layoutNodesByParent.delete(e),t.disposeWithoutSlotCascade();if(this.parent===e)this.parent=this.getAttachedSlotParent(t)}destroy(){if(this.destroyed)return;this.destroyed=!0;let e=new Set(this.layoutNodesByParent.values());this.layoutNodesByParent.clear();for(let r of e)r.destroy();let t=new Set(this.textNodesByParent.values());this.textNodesByParent.clear();for(let r of t)r.destroy()}}Yt({time_to_first_draw:nA});var iA=(e,t)=>{let r,n=!1,i=!1,s=!0,o=!1,a=e.destroy.bind(e),l=()=>{if(i)return;if(!r){n=!0;return}i=!0,r()};e.once("destroy",l),e.destroy=()=>{if(s){o=!0;return}a()};try{r=Xh(()=>Q(Vs.Provider,{get value(){return e},get children(){return Q(t,{})}}),e.root)}finally{s=!1,e.destroy=a}if(n)l();if(o)a()},Xs=async(e,t={})=>{let r=t instanceof yh?t:await wh({...t,onDestroy:()=>{t.onDestroy?.()}});vh.attach(r),iA(r,e)};var cl={tier0:32,tier1:64,tier2:64};import{basename as Wg,dirname as Gi}from"path";var Gr=1;function At(e){if(typeof e!=="number"||!Number.isFinite(e))return 1;return Math.max(1,Math.min(8,Math.round(e)))}function _n(e,t){let r=At(e);return{primary:r,mirrored:t?r-1:0}}var zs=64;var kb=zs*zs;var Tb=new RegExp(["asshole","bastard","bitch","bullshit","cunt","dildo","faggot","fuck","goddamn","jackass","jerkoff","kike","nigga","nigger","penis","porn","prick","pussy","retard","scumbag","shit","slut","tits","twat","vagina","whore","wanker"].join("|"));var qs={version:1,linkedRoles:{leftLegFoot:"leftLeg",rightLegFoot:"rightLeg",leftArmFoot:"leftArm",rightArmFoot:"rightArm",leftSleeve:"leftArm",rightSleeve:"rightArm"},clips:{idle:{duration:2.4,loop:!0,model:{positionY:[[0,0.004],[0.25,0.008],[0.5,0.004],[0.75,0],[1,0.004]]},roles:{leftArm:{positionZ:[[0,0],[0.25,0.006],[0.5,0],[0.75,-0.006],[1,0]]},rightArm:{positionZ:[[0,0],[0.25,-0.006],[0.5,0],[0.75,0.006],[1,0]]}}},walk:{duration:0.9,loop:!0,model:{positionY:[[0,0.015],[0.25,0.06],[0.5,0.015],[0.75,0.06],[1,0.015]]},roles:{leftLeg:{positionZ:[[0,0],[0.25,0.055],[0.5,0],[0.75,-0.055],[1,0]]},rightLeg:{positionZ:[[0,0],[0.25,-0.055],[0.5,0],[0.75,0.055],[1,0]]},leftArm:{positionZ:[[0,0],[0.25,-0.055],[0.5,0],[0.75,0.055],[1,0]]},rightArm:{positionZ:[[0,0],[0.25,0.055],[0.5,0],[0.75,-0.055],[1,0]]}}},jump:{duration:0.78,loop:!1,model:{positionY:[[0,0],[0.76,0],[0.9,-0.055],[0.98,0],[1,0]],rotationX:[[0,0],[0.2,0.04],[0.58,0.14],[0.82,0.09],[1,0]]},roles:{leftLeg:{positionY:[[0,0],[0.18,-0.008],[0.48,0.035],[0.72,0.026],[0.88,-0.006],[1,0]]},rightLeg:{positionY:[[0,0],[0.18,-0.007],[0.48,0.032],[0.72,0.024],[0.88,-0.007],[1,0]]},leftArm:{positionZ:[[0,0],[0.25,-0.025],[0.58,0.05],[0.82,0.02],[1,0]],rotationX:[[0,0],[0.25,-0.3],[0.58,0.55],[0.82,0.25],[1,0]],rotationZ:[[0,0],[0.25,0.06],[0.58,0.09],[0.82,0.035],[1,0]]},rightArm:{positionZ:[[0,0],[0.25,0.03],[0.58,-0.045],[0.82,-0.018],[1,0]],rotationX:[[0,0],[0.25,0.35],[0.58,-0.5],[0.82,-0.22],[1,0]],rotationZ:[[0,0],[0.25,-0.07],[0.58,-0.08],[0.82,-0.035],[1,0]]}}},frontFlip:{duration:0.8,loop:!1,model:{rotationX:[[0,0],[0.08,0.25],[0.2,1.15],[0.35,2.35],[0.5,3.1416],[0.65,3.93],[0.8,5.13],[0.92,6.03],[1,6.2832]],positionY:[[0,0],[0.08,0.017],[0.2,0.326],[0.35,0.937],[0.5,1.1],[0.65,0.935],[0.8,0.327],[0.92,0.017],[1,0]],positionZ:[[0,0],[0.08,-0.136],[0.2,-0.502],[0.35,-0.391],[0.5,0],[0.65,0.393],[0.8,0.503],[0.92,0.138],[1,0]]},roles:{leftArm:{rotationX:[[0,0],[0.15,-1.25],[0.5,0.85],[0.85,0.25],[1,0]]},rightArm:{rotationX:[[0,0],[0.15,-1.15],[0.5,0.8],[0.85,0.22],[1,0]]},leftLeg:{positionY:[[0,0],[0.3,0.05],[0.55,0.075],[0.85,0.01],[1,0]]},rightLeg:{positionY:[[0,0],[0.3,0.048],[0.55,0.07],[0.85,0.012],[1,0]]}}},run:{duration:0.55,loop:!0,model:{positionY:[[0,0.02],[0.25,0.085],[0.5,0.02],[0.75,0.085],[1,0.02]]},roles:{leftLeg:{positionY:[[0,0],[0.25,0.035],[0.5,0],[0.75,0],[1,0]],positionZ:[[0,0],[0.25,0.085],[0.5,0],[0.75,-0.085],[1,0]],rotationX:[[0,0],[0.25,-0.34],[0.5,0],[0.75,0.34],[1,0]]},rightLeg:{positionY:[[0,0],[0.25,0],[0.5,0],[0.75,0.035],[1,0]],positionZ:[[0,0],[0.25,-0.085],[0.5,0],[0.75,0.085],[1,0]],rotationX:[[0,0],[0.25,0.34],[0.5,0],[0.75,-0.34],[1,0]]},leftArm:{positionY:[[0,0],[0.25,0],[0.5,0],[0.75,0.03],[1,0]],positionZ:[[0,0],[0.25,-0.072],[0.5,0],[0.75,0.072],[1,0]],rotationX:[[0,0],[0.25,0.3],[0.5,0],[0.75,-0.3],[1,0]]},rightArm:{positionY:[[0,0],[0.25,0.03],[0.5,0],[0.75,0],[1,0]],positionZ:[[0,0],[0.25,0.072],[0.5,0],[0.75,-0.072],[1,0]],rotationX:[[0,0],[0.25,-0.3],[0.5,0],[0.75,0.3],[1,0]]}}},swim:{duration:1.2,loop:!0,model:{positionY:[[0,0.018],[0.25,0.04],[0.5,0.018],[0.75,0],[1,0.018]],rotationX:[[0,0.1],[0.25,0.14],[0.5,0.1],[0.75,0.06],[1,0.1]]},roles:{leftArm:{positionY:[[0,0.045],[0.25,0.02],[0.5,0],[0.75,0.018],[1,0.045]],positionZ:[[0,0],[0.25,-0.055],[0.5,0],[0.75,0.04],[1,0]],rotationX:[[0,-0.9],[0.25,-0.15],[0.5,0.75],[0.75,0.15],[1,-0.9]],rotationZ:[[0,0.18],[0.25,0.34],[0.5,0.18],[0.75,0.08],[1,0.18]]},rightArm:{positionY:[[0,0],[0.25,0.018],[0.5,0.045],[0.75,0.02],[1,0]],positionZ:[[0,0],[0.25,0.04],[0.5,0],[0.75,-0.055],[1,0]],rotationX:[[0,0.75],[0.25,0.15],[0.5,-0.9],[0.75,-0.15],[1,0.75]],rotationZ:[[0,-0.18],[0.25,-0.08],[0.5,-0.18],[0.75,-0.34],[1,-0.18]]},leftLeg:{positionY:[[0,0.018],[0.25,0.035],[0.5,0],[0.75,0.012],[1,0.018]],positionZ:[[0,-0.045],[0.25,0],[0.5,0.045],[0.75,0],[1,-0.045]],rotationX:[[0,0.24],[0.25,0],[0.5,-0.24],[0.75,0],[1,0.24]]},rightLeg:{positionY:[[0,0],[0.25,0.012],[0.5,0.018],[0.75,0.035],[1,0]],positionZ:[[0,0.045],[0.25,0],[0.5,-0.045],[0.75,0],[1,0.045]],rotationX:[[0,-0.24],[0.25,0],[0.5,0.24],[0.75,0],[1,-0.24]]}}},horseWalk:{duration:0.9,loop:!0,model:{positionY:[[0,0.008],[0.125,0.016],[0.25,0.008],[0.375,0.016],[0.5,0.008],[0.625,0.016],[0.75,0.008],[0.875,0.016],[1,0.008]],rotationX:[[0,0],[0.125,0.012],[0.25,0],[0.375,-0.012],[0.5,0],[0.625,0.012],[0.75,0],[0.875,-0.012],[1,0]]},roles:{leftLeg:{positionY:[[0,0],[0.125,0],[0.25,0],[0.375,0],[0.5,0],[0.625,0.025],[0.75,0.055],[0.875,0.035],[1,0]],positionZ:[[0,0.025],[0.125,0.012],[0.25,-0.008],[0.375,-0.022],[0.5,-0.03],[0.625,-0.012],[0.75,0.012],[0.875,0.025],[1,0.025]],rotationX:[[0,-0.3],[0.125,-0.16],[0.25,0.03],[0.375,0.2],[0.5,0.28],[0.625,0.12],[0.75,-0.1],[0.875,-0.26],[1,-0.3]]},leftArm:{positionY:[[0,0.055],[0.125,0.035],[0.25,0],[0.375,0],[0.5,0],[0.625,0],[0.75,0],[0.875,0.025],[1,0.055]],positionZ:[[0,0.012],[0.125,0.025],[0.25,0.025],[0.375,0.012],[0.5,-0.008],[0.625,-0.022],[0.75,-0.03],[0.875,-0.012],[1,0.012]],rotationX:[[0,-0.1],[0.125,-0.26],[0.25,-0.3],[0.375,-0.16],[0.5,0.03],[0.625,0.2],[0.75,0.28],[0.875,0.12],[1,-0.1]]},rightLeg:{positionY:[[0,0],[0.125,0.025],[0.25,0.055],[0.375,0.035],[0.5,0],[0.625,0],[0.75,0],[0.875,0],[1,0]],positionZ:[[0,-0.03],[0.125,-0.012],[0.25,0.012],[0.375,0.025],[0.5,0.025],[0.625,0.012],[0.75,-0.008],[0.875,-0.022],[1,-0.03]],rotationX:[[0,0.28],[0.125,0.12],[0.25,-0.1],[0.375,-0.26],[0.5,-0.3],[0.625,-0.16],[0.75,0.03],[0.875,0.2],[1,0.28]]},rightArm:{positionY:[[0,0],[0.125,0],[0.25,0],[0.375,0.025],[0.5,0.055],[0.625,0.035],[0.75,0],[0.875,0],[1,0]],positionZ:[[0,-0.008],[0.125,-0.022],[0.25,-0.03],[0.375,-0.012],[0.5,0.012],[0.625,0.025],[0.75,0.025],[0.875,0.012],[1,-0.008]],rotationX:[[0,0.03],[0.125,0.2],[0.25,0.28],[0.375,0.12],[0.5,-0.1],[0.625,-0.26],[0.75,-0.3],[0.875,-0.16],[1,0.03]]}}},horseRun:{duration:0.55,loop:!0,model:{positionY:[[0,0.087361],[0.125,0.094508],[0.25,0.078511],[0.375,0.048743],[0.5,0.022639],[0.625,0.015492],[0.75,0.031489],[0.875,0.061257],[1,0.087361]],rotationX:[[0,0.013907],[0.125,-0.038677],[0.25,-0.068605],[0.375,-0.058344],[0.5,-0.013907],[0.625,0.038677],[0.75,0.068605],[0.875,0.058344],[1,0.013907]]},roles:{leftArm:{positionY:[[0,0],[0.125,0.060104],[0.25,0.085],[0.375,0.060104],[0.5,0],[0.625,0],[0.75,0],[0.875,0],[1,0]],positionZ:[[0,0],[0.125,0.120208],[0.25,0.17],[0.375,0.120208],[0.5,0],[0.625,-0.120208],[0.75,-0.17],[0.875,-0.120208],[1,0]],rotationX:[[0,0],[0.125,-0.240416],[0.25,-0.34],[0.375,-0.240416],[0.5,0],[0.625,0.240416],[0.75,0.34],[0.875,0.240416],[1,0]]},rightArm:{positionY:[[0,0],[0.125,0.027977],[0.25,0.076538],[0.375,0.080264],[0.5,0.036972],[0.625,0],[0.75,0],[0.875,0],[1,0]],positionZ:[[0,-0.073944],[0.125,0.055955],[0.25,0.153076],[0.375,0.160527],[0.5,0.073944],[0.625,-0.055955],[0.75,-0.153076],[0.875,-0.160527],[1,-0.073944]],rotationX:[[0,0.147888],[0.125,-0.111909],[0.25,-0.306152],[0.375,-0.321055],[0.5,-0.147888],[0.625,0.111909],[0.75,0.306152],[0.875,0.321055],[1,0.147888]]},leftLeg:{positionY:[[0,0.033275],[0.125,0],[0.25,0],[0.375,0],[0.5,0],[0.625,0.02518],[0.75,0.068884],[0.875,0.072237],[1,0.033275]],positionZ:[[0,0.077641],[0.125,-0.058752],[0.25,-0.16073],[0.375,-0.168554],[0.5,-0.077641],[0.625,0.058752],[0.75,0.16073],[0.875,0.168554],[1,0.077641]],rotationX:[[0,-0.125705],[0.125,0.095123],[0.25,0.260229],[0.375,0.272897],[0.5,0.125705],[0.625,-0.095123],[0.75,-0.260229],[0.875,-0.272897],[1,-0.125705]]},rightLeg:{positionY:[[0,0],[0.125,0],[0.25,0],[0.375,0],[0.5,0],[0.625,0.054094],[0.75,0.0765],[0.875,0.054094],[1,0]],positionZ:[[0,0],[0.125,-0.126219],[0.25,-0.1785],[0.375,-0.126219],[0.5,0],[0.625,0.126219],[0.75,0.1785],[0.875,0.126219],[1,0]],rotationX:[[0,0],[0.125,0.204354],[0.25,0.289],[0.375,0.204354],[0.5,0],[0.625,-0.204354],[0.75,-0.289],[0.875,-0.204354],[1,0]]}}},wave:{duration:2,loop:!1,model:{positionY:[[0,0],[1,0]]},roles:{leftArm:{positionY:[[0,0],[0.5,-0.08],[1,0]],rotationX:[[0,0],[0.5,-1.5],[1,0]]}}},look:{duration:4.9,loop:!1,model:{rotationY:[[0,0],[0.125,0.07],[0.25,0],[0.375,-0.16],[0.5,0],[0.625,0.16],[0.75,0],[0.875,-0.07],[1,0]]},roles:{leftArm:{positionZ:[[0,0],[0.125,0.012],[0.25,0],[0.375,-0.025],[0.5,0],[0.625,0.025],[0.75,0],[0.875,-0.012],[1,0]]},rightArm:{positionZ:[[0,0],[0.125,-0.012],[0.25,0],[0.375,0.025],[0.5,0],[0.625,-0.025],[0.75,0],[0.875,0.012],[1,0]]}}},sit:{duration:6.2,loop:!1,model:{positionY:[[0,0],[0.25,-0.042426],[0.5,-0.06],[0.75,-0.042426],[1,0]]},roles:{leftLeg:{positionY:[[0,0],[0.25,-0.024749],[0.5,-0.035],[0.75,-0.024749],[1,0]],positionZ:[[0,0],[0.25,0.070711],[0.5,0.1],[0.75,0.070711],[1,0]]},rightLeg:{positionY:[[0,0],[0.25,-0.024749],[0.5,-0.035],[0.75,-0.024749],[1,0]],positionZ:[[0,0],[0.25,0.070711],[0.5,0.1],[0.75,0.070711],[1,0]]},leftArm:{positionZ:[[0,0],[0.25,-0.021213],[0.5,-0.03],[0.75,-0.021213],[1,0]]},rightArm:{positionZ:[[0,0],[0.25,-0.021213],[0.5,-0.03],[0.75,-0.021213],[1,0]]}}}}};var aA=["positionX","positionY","positionZ","rotationX","rotationY","rotationZ","scaleX","scaleY","scaleZ"];var lA=new Set(aA);function Ur(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function ul(e,t){if(!Ur(e))return[`${t} must be an object`];let r=[];for(let[n,i]of Object.entries(e)){if(!lA.has(n)){r.push(`${t} uses unknown property ${n}`);continue}if(!Array.isArray(i)||i.length<2){r.push(`${t}.${n} must contain at least two keyframes`);continue}let s=-1;for(let[o,a]of i.entries()){if(!Array.isArray(a)||a.length!==2||!a.every((c)=>typeof c==="number"&&Number.isFinite(c))){r.push(`${t}.${n}[${o}] is invalid`);continue}let l=a[0];if(l<0||l>1||l<=s)r.push(`${t}.${n} keyframe times must increase from 0 to 1`);s=l}if(i[0]?.[0]!==0||i.at(-1)?.[0]!==1)r.push(`${t}.${n} must start at 0 and end at 1`)}return r}function hl(e){if(!Ur(e))return["Animation catalog must be an object"];let t=[];if(e.version!==1)t.push("Animation catalog version must be 1");if(!Ur(e.linkedRoles))t.push("Animation catalog linkedRoles must be an object");else if(Object.values(e.linkedRoles).some((r)=>typeof r!=="string"))t.push("Animation catalog linked roles must target role names");if(!Ur(e.clips))return t.push("Animation catalog clips must be an object"),t;for(let[r,n]of Object.entries(e.clips)){let i=`Clip ${r}`;if(!Ur(n)){t.push(`${i} must be an object`);continue}if(typeof n.duration!=="number"||!Number.isFinite(n.duration)||n.duration<=0)t.push(`${i} must have a positive duration`);if(typeof n.loop!=="boolean")t.push(`${i} must declare whether it loops`);if(n.model===void 0)t.push(`${i} must include a model animation track`);else t.push(...ul(n.model,`${i}.model`));if(n.roles!==void 0)if(!Ur(n.roles))t.push(`${i}.roles must be an object`);else for(let[s,o]of Object.entries(n.roles))t.push(...ul(o,`${i}.roles.${s}`))}return t}var dl=hl(qs);if(dl.length>0)throw Error(`Invalid character animation catalog:
8
- ${dl.join(`
9
- `)}`);var cA=qs,uA=["jump","frontFlip","horseWalk","swim"],dA=Object.keys(cA.clips).filter((e)=>!uA.includes(e));var fl=["top","side","bottom"],gl=["left","right","bottom","top","back","front"],ml=["humanoid","female","pig","robot","dog","cat","horse","bird","octopus"],wi=["leftLeg","rightLeg","leftArm","rightArm","leftLegFoot","rightLegFoot","leftArmFoot","rightArmFoot","leftSleeve","rightSleeve"],pl=["leftWing","rightWing","carried","muzzle"];var jb=new Set(ml),Kb=new Set([...wi,...pl]),Wb=new Set(fl),Yb=new Set(gl),Qb=["cree","per"].join(""),Cn=["H","oof"].join(""),Jb=new Map([[`leftLeg${Cn}`,"leftLegFoot"],[`rightLeg${Cn}`,"rightLegFoot"],[`leftArm${Cn}`,"leftArmFoot"],[`rightArm${Cn}`,"rightArmFoot"]]),Vb=["horse",Cn].join("");var fA=Math.PI*2;var zb=new Set(wi);var bl={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],transparent:[0,0,0,0],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]};function yl(e){let t=new Set;for(let r of e)for(let n of r)if(n.active&&n.color)t.add(n.color);return t}function eo(e,t){let r=yl(t);return e.filter((n)=>r.has(n))}var mA=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,pA=/^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)(deg|grad|rad|turn)?$/i,_i=(e,t,r)=>Math.max(t,Math.min(r,e));function Ci(e){let t=e.trim(),r=t.endsWith("%"),n=r?t.slice(0,-1):t;if(!mA.test(n))return null;let i=Number(n);return Number.isFinite(i)?{value:i,percentage:r}:null}function vl(e){if(e===null)return 1;let t=Ci(e);if(!t)return null;return _i(t.percentage?t.value/100:t.value,0,1)}function _l(e,t){let r=/^([a-z]+)\(\s*(.*?)\s*\)$/i.exec(e.trim());if(!r||!t.includes(r[1].toLowerCase()))return null;let n=r[2];if(n.includes(",")){let a=n.split("/");if(a.length>2)return null;let l=a[0].split(",").map((c)=>c.trim());if(l.some((c)=>!c))return null;if(a.length===2){let c=a[1].trim();return l.length===3&&c?{channels:l,alpha:c}:null}return l.length===3||l.length===4?{channels:l.slice(0,3),alpha:l[3]??null}:null}let i=n.split("/");if(i.length>2)return null;let s=i[0].trim().split(/\s+/),o=i.length===2?i[1].trim():null;return s.length===3&&(i.length===1||o)?{channels:s,alpha:o}:null}function bA(e){let t=pA.exec(e.trim());if(!t)return null;let r=Number(t[1]);if(!Number.isFinite(r))return null;switch(t[2]?.toLowerCase()){case"grad":return r*0.9;case"rad":return r*180/Math.PI;case"turn":return r*360;default:return r}}function xn(e){let t=_l(e,["hsl","hsla"]);if(!t)return null;let r=bA(t.channels[0]),n=Ci(t.channels[1]),i=Ci(t.channels[2]),s=vl(t.alpha);if(r===null||!n||!i||s===null)return null;return[r,_i(n.value,0,100),_i(i.value,0,100),s]}function Cl(e,t,r){let n=t/100,i=r/100,s=(1-Math.abs(2*i-1))*n,o=(e%360+360)%360/60,a=s*(1-Math.abs(o%2-1)),l=0,c=0,u=0;if(o<1)[l,c,u]=[s,a,0];else if(o<2)[l,c,u]=[a,s,0];else if(o<3)[l,c,u]=[0,s,a];else if(o<4)[l,c,u]=[0,a,s];else if(o<5)[l,c,u]=[a,0,s];else[l,c,u]=[s,0,a];let d=i-s/2;return{r:Math.round((l+d)*255),g:Math.round((c+d)*255),b:Math.round((u+d)*255)}}function xl({r:e,g:t,b:r}){let n=e/255,i=t/255,s=r/255,o=Math.max(n,i,s),a=Math.min(n,i,s),l=o-a,c=(o+a)/2;if(l===0)return{h:0,s:0,l:c*100};let u;if(o===n)u=((i-s)/l+(i<s?6:0))*60;else if(o===i)u=((s-n)/l+2)*60;else u=((n-i)/l+4)*60;return{h:u,s:l/(1-Math.abs(2*c-1))*100,l:c*100}}function En({r:e,g:t,b:r}){let n=(i)=>Math.round(Math.max(0,Math.min(255,i))).toString(16).padStart(2,"0");return`#${n(e)}${n(t)}${n(r)}`}var wl=(e,t)=>{let r=Math.max(-100,Math.min(100,t))/100;return r>=0?e+(100-e)*r:e*(1+r)};var vi=(e)=>{let t=Math.round(e*1000)/1000;return String(Object.is(t,-0)?0:t)};function to(e,t,r){if(t===0&&r===0)return e;let n=xn(e),i=n?null:Jt(e);if(!n&&!i)return e;let s=n?{h:n[0],s:n[1],l:n[2]}:xl(i),o=s.s===0?0:wl(s.s,t),a=wl(s.l,r),l=n?.[3]??i?.a??1;return`hsla(${vi(s.h)}, ${vi(o)}%, ${vi(a)}%, ${vi(l)})`}function ct(e){return typeof e==="number"&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function Sn(e,t,r){let n=ct(t),i=ct(r);if(n===0&&i===0)return e;return e.map((s)=>to(s,n,i))}function Qt(e,t,r){if(t===0&&r===0)return e;let n=new Map,i=(s)=>{let o=n.get(s);if(o===void 0)o=to(s,t,r),n.set(s,o);return o};return e.map((s)=>s.map((o)=>({...o,color:o.color===null?null:i(o.color)})))}function yA(e){let t=/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.exec(e.trim());if(!t)return null;let r=t[1],n=r.length<=4?[...r].map((i)=>i+i).join(""):r;return{r:Number.parseInt(n.slice(0,2),16),g:Number.parseInt(n.slice(2,4),16),b:Number.parseInt(n.slice(4,6),16),a:n.length===8?Number.parseInt(n.slice(6,8),16)/255:1}}function wA(e){let t=_l(e,["rgb","rgba"]);if(!t)return null;let r=t.channels.map(Ci),n=vl(t.alpha);if(r.some((l)=>l===null)||n===null)return null;let[i,s,o]=r,a=(l)=>_i(l.percentage?l.value/100*255:l.value,0,255);return{r:a(i),g:a(s),b:a(o),a:n}}function Jt(e){let t=e.trim(),r=yA(t);if(r)return r;let n=xn(t);if(n)return{...Cl(n[0],n[1],n[2]),a:n[3]};let i=wA(t);if(i)return i;let s=bl[t.toLowerCase()];if(!s)return null;return{r:s[0],g:s[1],b:s[2],a:s[3]??1}}function nr(e){let t=Jt(e);return t?{r:t.r,g:t.g,b:t.b}:null}var xi=1;var ro=30;function In(e){return e.trim().slice(0,30)}var kn=0.16,no=0.1;var Hr=0.15,io=0.12;var mr=0.25;var Ei=[-1,1];function pr(...e){let t=Math.max(0,Math.min(...e));return Math.max(0.22,t*0.5)}var Te=64,so=Te*Te;var oo=64,Sl=512,Ey=Sl*Sl,EA=128,Rl=65535,SA=20,IA=/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i,kA=/^[a-z]+$/i,RA=/^(?:rgb|rgba|hsl|hsla)\([\d\s.,%+\-/e]*(?:(?:deg|grad|rad|turn)[\d\s.,%+\-/e]*)?\)$/i;function Tl(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function jr(e,t,r){return Number.isInteger(e)&&Number(e)>=t&&Number(e)<=r}function vt(e){if(typeof e!=="string"||e.length===0||e.length>EA)return!1;return IA.test(e)||kA.test(e)||RA.test(e)}function TA(e){return Tl(e)&&e.v===2}function Il(e,t){return e===void 0||Array.isArray(e)&&e.length<=t&&e.every((r)=>jr(r,0,t-1))}function kl(e,t,r){return e===void 0||Array.isArray(e)&&e.length===t&&e.every((n)=>jr(n,0,r))}function BA(e,t,r){let{w:n,h:i,palette:s,cells:o,activeNoColor:a,tiles:l,depths:c,mirrorZ:u}=e;if(!jr(n,0,t)||!jr(i,0,t))return!1;let d=n*i;return d<=r&&Array.isArray(s)&&s.length<=d&&s.every(vt)&&Array.isArray(o)&&o.length===d&&o.every((A)=>jr(A,0,s.length))&&Il(a,d)&&kl(l,d,Rl+1)&&kl(c,d,SA)&&Il(u,d)}function OA(e){if(!Tl(e)||typeof e.active!=="boolean")return!1;if(e.color!==null&&!vt(e.color))return!1;if(e.tileIndex!==void 0&&e.tileIndex!==null&&!jr(e.tileIndex,0,Rl))return!1;if(e.depth!==void 0&&e.depth!==null&&!Number.isFinite(e.depth))return!1;return e.mirrorZ===void 0||e.mirrorZ===null||typeof e.mirrorZ==="boolean"}function PA(e){if(e.length>Te)return null;let t=0,r=[];for(let n of e){if(!Array.isArray(n)||n.length>Te)return null;if(t+=n.length,t>so||!n.every(OA))return null;r.push(n.map((i)=>({active:i.active,color:i.color,...i.tileIndex!=null?{tileIndex:i.tileIndex}:{},...At(i.depth)>Gr?{depth:At(i.depth)}:{},...i.mirrorZ?{mirrorZ:!0}:{}})))}return r}function Kr(e){let t=e.length,r=t>0?e[0].length:0,n=[],i=new Map,s=Array(r*t).fill(0),o=[],a=null,l=null,c=[];for(let d=0;d<t;d++){let A=e[d];for(let f=0;f<r;f++){let g=A?.[f],m=d*r+f;if(!g)continue;if(g.color){let v=i.get(g.color);if(v===void 0)n.push(g.color),v=n.length,i.set(g.color,v);s[m]=v}else if(g.active)o.push(m);if(g.tileIndex!=null)a??=Array(r*t).fill(0),a[m]=g.tileIndex+1;let p=At(g.depth);if(p>Gr)l??=Array(r*t).fill(0),l[m]=p;if(g.mirrorZ)c.push(m)}}let u={v:2,w:r,h:t,palette:n,cells:s};if(o.length>0)u.activeNoColor=o;if(a)u.tiles=a;if(l)u.depths=l;if(c.length>0)u.mirrorZ=c;return u}function Rn(e){if(TA(e))return BA(e,Te,so)?DA(e):[];return Array.isArray(e)?PA(e)??[]:[]}function DA(e){let{w:t,h:r,palette:n,cells:i,activeNoColor:s,tiles:o,depths:a}=e,l=s?new Set(s):null,c=e.mirrorZ?new Set(e.mirrorZ):null,u=Array(r);for(let d=0;d<r;d++){let A=Array(t);for(let f=0;f<t;f++){let g=d*t+f,m=i[g];if(m>0)A[f]={active:!0,color:n[m-1]??null};else if(l?.has(g))A[f]={active:!0,color:null};else A[f]={active:!1,color:null};let p=o?.[g];if(p)A[f].tileIndex=p-1;let v=At(a?.[g]);if(v>Gr)A[f].depth=v;if(c?.has(g))A[f].mirrorZ=!0}u[d]=A}return u}var NA={top:0,side:1,bottom:2};var MA=/^data:image\/(?:png|gif|webp);base64,[a-z\d+/=]+$/i;var LA=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}\/[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}\/[\da-f]{64}\.png$/i;function ao(e,t){return Number.isInteger(e)&&Number(e)>0&&Number(e)<=t}function FA(e){if(typeof e!=="string"||e.length===0||e.length>256)return!1;return![...e].some((t)=>{let r=t.charCodeAt(0);return r<32||r===127})}function GA(e,t){return e===void 0||Array.isArray(e)&&e.length<=t&&e.every((r)=>r===null||typeof r==="string"&&r.length<=128&&/^[a-z0-9_-]+$/i.test(r))}function lo(e){if(!e||e.v!==2&&e.v!==3)return!1;if(!FA(e.name)||!ao(e.tileSize,64)||!ao(e.cols,256)||!ao(e.rows,256))return!1;if(e.faceLayout!==void 0&&e.faceLayout!=="top-side-bottom")return!1;if(!GA(e.tileIds,e.cols*e.rows))return!1;let t=e.cols*e.tileSize*(e.faceLayout?3:1),r=e.rows*e.tileSize;return e.cols*e.tileSize<=4096&&r<=4096&&t*r<=16777216}function UA(e,t){if(typeof e!=="string"||e.length===0||e.length>4096)return null;for(let r of e){let n=r.charCodeAt(0);if(n<=32||n===127||`<>"'\\`.includes(r))return null}if(typeof t!=="string"||!LA.test(t))return null;try{let r=new URL(e);return r.protocol==="https:"&&r.hostname==="ldxdyymfagplpxxsqmgs.supabase.co"&&r.port===""&&r.username===""&&r.password===""&&r.search===""&&r.hash===""&&r.pathname===`/storage/v1/object/public/tilesets/${t}`?e:null}catch{return null}}function co(e){if(!lo(e))return null;if(e.v===2)return e.imageDataUrl.length<=16777216&&MA.test(e.imageDataUrl)?e.imageDataUrl:null;if(e.v===3)return UA(e.url,e.path);return null}function Tn(e,t,r="top"){if(!lo(e))return null;if(!Number.isInteger(t)||t<0||t>=e.cols*e.rows)return null;let n=e.faceLayout?3:1,i=e.faceLayout?NA[r]:0,s=e.cols*e.tileSize;return{sx:i*s+t%e.cols*e.tileSize,sy:Math.floor(t/e.cols)*e.tileSize,tileSize:e.tileSize,sheetW:s*n,sheetH:e.rows*e.tileSize}}function uo(e){if(!lo(e))return null;return{width:e.cols*e.tileSize*(e.faceLayout?3:1),height:e.rows*e.tileSize}}function HA(e){let t=e.length;for(let r=0;r<e.length;r+=101)t=(t<<5)-t+e.charCodeAt(r)|0;return`iso-sheet-${(t>>>0).toString(36)}`}var br={corners:[[0,0,1],[1,0,1],[1,1,1],[0,1,1]],shade:1},Bn={corners:[[0,1,1],[0,1,0],[1,1,0],[1,1,1]],shade:0.97},Wr={corners:[[1,0,1],[1,0,0],[1,1,0],[1,1,1]],shade:0.94},yr=0.5,jA=0.75,KA="rgba(0, 0, 0, 0.16)",WA=0.92,YA="#92929a";function QA(e){if(!Number.isFinite(e))return yr;return Math.max(0,Math.min(1,e))}function Bl(e,t){if(t<yr){let n=t/yr,i=e*jA;return i+(e-i)*n}let r=(t-yr)/(1-yr);return e+(1-e)*r}function ce(e){return e.toFixed(2)}function Rt(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Ol(e){return`${ce(e[0])},${ce(e[1])}`}function JA([e,t]){let r=Ol(e),n=Ol(t);return r<n?`${r} ${n}`:`${n} ${r}`}function Pl(e,t){return`<polygon points="${e.map(([n,i])=>`${ce(n)},${ce(i)}`).join(" ")}" fill="${Rt(t)}"/>`}function Dl(e,t,r){let n=t[0]-e[0],i=t[1]-e[1],s=Math.hypot(n,i)||1,o=Math.min(r,s/2)/s;return[e[0]+n*o,e[1]+i*o]}function VA(e,t){let r=e.length,n="";for(let i=0;i<r;i++){let s=e[i],o=e[(i-1+r)%r],a=e[(i+1)%r],l=Dl(s,o,t),c=Dl(s,a,t);n+=`${i===0?"M":"L"}${ce(l[0])},${ce(l[1])}`,n+=`Q${ce(s[0])},${ce(s[1])} ${ce(c[0])},${ce(c[1])}`}return`${n}Z`}function Nl(e,t,r,n){return`<path d="${e}" fill="${Rt(t)}" stroke="${Rt(r)}" stroke-width="${ce(n)}" stroke-linejoin="round"/>`}function $A(e,t){if(e.length===0)return"";return`<path d="${e.map(([n,i])=>`M${ce(n[0])},${ce(n[1])}L${ce(i[0])},${ce(i[1])}`).join("")}" fill="none" stroke="${Rt(t)}" stroke-width="1" stroke-linejoin="round" vector-effect="non-scaling-stroke"/>`}function ho(e){let{grid:t,numCols:r,numRows:n,scale:i=16,showGridLines:s=!1,sideLighting:o=yr,cellGroups:a=!1,tileset:l=null,tilesetImageId:c,embedTilesetImage:u=!0,blockStyle:d="normal"}=e,A=Number.isFinite(i)&&i>0?Math.min(i,1024):16,f=s&&d!=="jelly"?KA:void 0,g=QA(o),m=co(l),p=l&&m?l:null,v=uo(p),y=v?.width??0,E=v?.height??0,_=m&&c&&/^[a-z_][\w:.-]{0,127}$/i.test(c)?c:null,b=m?_??HA(m):"",w=u||!_,C=t.slice(0,Te),O=Math.min(Number.isInteger(n)&&n>0?n:0,C.length,Te),N=C.reduce((T,Y)=>Math.max(T,Array.isArray(Y)?Y.length:0),0),P=Math.min(Number.isInteger(r)&&r>0?r:0,N,Te),R=A,U=A/Math.sqrt(3),X=A*2/Math.sqrt(3),V=d==="jelly"?R*kn:0,te=(T)=>T?.tileIndex!=null?Tn(p,T.tileIndex):null,ge=(T)=>{if(vt(T?.color))return T.color;return te(T)?YA:null},z=(T,Y,he)=>[(T-Y)*R,(T+Y)*U-he*X],Me=(T,Y)=>{let he=t[Y]?.[T];return he?.active&&ge(he)?At(he.depth):0},Le=[];for(let T=0;T<O;T++)for(let Y=0;Y<P;Y++){let he=t[T]?.[Y],it=ge(he);if(he?.active&&it)Le.push({x:Y,y:T,color:it,tileIndex:he.tileIndex??null,depth:At(he.depth),mirrorZ:!!he.mirrorZ})}if(Le.length===0)return'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 0 0"/>';Le.sort((T,Y)=>T.x+T.y-(Y.x+Y.y)||T.depth-Y.depth);let q=[],Z=1/0,ue=-1/0,pe=1/0,M=-1/0,re=!1,ie=Bl(Wr.shade,g),oe=Bl(Bn.shade,g),qe=(T)=>T===br?T.shade:T===Wr?ie:oe,me=(T,Y)=>{if(T<Z)Z=T;if(T>ue)ue=T;if(Y<pe)pe=Y;if(Y>M)M=Y};for(let{x:T,y:Y,color:he,tileIndex:it,depth:Ct,mirrorZ:Fe}of Le){let be=xn(he),Xe=[],Lt=[],{primary:se,mirrored:di}=_n(Ct,Fe),Ft=(Ae)=>be?`hsla(${be[0]}, ${be[1]}%, ${Math.max(0,Math.min(100,be[2]*Ae))}%, ${be[3]})`:he,hr=(Ae,we=0,We=se)=>Ae.corners.map(([xe,fe,ne])=>z(T+xe,Y+fe,ne===0?we:We)),Gt=(Ae,we=0,We=se)=>{let xe=hr(Ae,we,We);if(V>0){let fe=qe(Ae),ne=Ft(fe),ae=VA(xe,V),Ge=Ae===br?Ft(Math.min(1.18,fe+0.13)):Ft(fe*WA);Xe.push(Nl(ae,ne,ne,V),Nl(ae,"none",Ge,V*0.3))}else Xe.push(Pl(xe,Ft(qe(Ae))));for(let[fe,ne]of xe)me(fe,ne)},Ut=Fe?-di:Me(T+1,Y),qt=Fe?-di:Me(T,Y+1),un=a&&!Fe?0:Ut,dn=a&&!Fe?0:qt,Ar=a||Fe||un<se,hn=a||Fe||dn<se;if(Ar)Gt(Wr,un,se);if(hn)Gt(Bn,dn,se);if(Gt(br,se,se),f){let Ae=new Set,we=(ne,ae)=>{let Ge=JA([ne,ae]);if(Ae.has(Ge))return;Ae.add(Ge),Lt.push([ne,ae])},We=(ne)=>{for(let ae=0;ae<ne.length;ae++)we(ne[ae],ne[(ae+1)%ne.length])},xe=(ne,ae)=>{let[Ge,Ye]=ne.corners.filter(([,,Pe])=>Pe===0);for(let Pe=Math.floor(ae)+1;Pe<se;Pe++)we(z(T+Ge[0],Y+Ge[1],Pe),z(T+Ye[0],Y+Ye[1],Pe))},fe=hr(br,se,se);if(we(fe[0],fe[1]),Me(T+1,Y)!==se)we(fe[1],fe[2]);if(Me(T,Y+1)!==se)we(fe[2],fe[3]);if(we(fe[3],fe[0]),Fe||Ut<se)We(hr(Wr,Ut,se)),xe(Wr,Ut);if(Fe||qt<se)We(hr(Bn,qt,se)),xe(Bn,qt)}let An=it==null?null:Tn(p,it);if(An){re=!0;let Ae=(xe,fe,ne,ae,Ge,Ye,Pe,Qe)=>{let De=Tn(p,it,xe);if(!De)return;let at=1-Qe;Xe.push(`<g transform="matrix(${fe} ${ne} ${ae} ${Ge} ${ce(Ye)} ${ce(Pe)})"><svg x="0" y="0" width="1" height="1" viewBox="${De.sx} ${De.sy} ${De.tileSize} ${De.tileSize}" preserveAspectRatio="none"><use href="#${b}" xlink:href="#${b}"/></svg>`+(at>0?`<rect x="0" y="0" width="1" height="1" fill="#000" opacity="${at.toFixed(2)}"/>`:"")+"</g>")};if(Ar){let[xe,fe]=z(T+1,Y,se);Ae("side",-R,U,0,X*(se-un),xe,fe,qe(Wr))}if(hn){let[xe,fe]=z(T,Y+1,se);Ae("side",R,U,0,X*(se-dn),xe,fe,qe(Bn))}let[we,We]=z(T,Y,se);Ae("top",R,U,-R,U,we,We,br.shade)}if(f)Xe.push($A(Lt,f));if(d!=="normal"&&!An){if(d==="lego"){let Ae=Math.SQRT2*Hr*R,we=Math.SQRT2*Hr*U,We=Ft(ie),xe=Ft(br.shade),fe=[[-1,-1],[-1,1],[1,-1],[1,1]];for(let[ne,ae]of fe){let Ge=T+0.5+ne*mr,Ye=Y+0.5+ae*mr,[Pe,Qe]=z(Ge,Ye,se),[,De]=z(Ge,Ye,se+io);me(Pe-Ae,Qe+we),me(Pe+Ae,De-we);let at='shape-rendering="geometricPrecision"';Xe.push(`<ellipse cx="${ce(Pe)}" cy="${ce(Qe)}" rx="${ce(Ae)}" ry="${ce(we)}" fill="${Rt(We)}" ${at}/>`,`<rect x="${ce(Pe-Ae)}" y="${ce(De)}" width="${ce(Ae*2)}" height="${ce(Qe-De)}" fill="${Rt(We)}" ${at}/>`,`<ellipse cx="${ce(Pe)}" cy="${ce(De)}" rx="${ce(Ae)}" ry="${ce(we)}" fill="${Rt(xe)}" ${at}/>`)}}else if(d==="voxel"){let Ae=(ne,ae,Ge,Ye,Pe,Qe)=>{let De=(at,xs)=>{for(let[Es,Ss]of at)me(Es,Ss);Xe.push(Pl(at,Ft(xs)))};De([z(ae,Ge,Qe),z(ae,Ge,Pe),z(ae,Ye,Pe),z(ae,Ye,Qe)],ie),De([z(ne,Ye,Qe),z(ne,Ye,Pe),z(ae,Ye,Pe),z(ae,Ye,Qe)],oe),De([z(ne,Ge,Qe),z(ae,Ge,Qe),z(ae,Ye,Qe),z(ne,Ye,Qe)],br.shade)},we=no,We=pr(1,1),xe=Fe||Ut<se?Ut:null,fe=Fe||qt<se?qt:null;if(Ae(T+0.5-We/2,T+0.5+We/2,Y+0.5-We/2,Y+0.5+We/2,se,se+we),xe!==null){let ne=pr(1,se-xe),ae=(se+xe)/2;Ae(T+1,T+1+we,Y+0.5-ne/2,Y+0.5+ne/2,ae-ne/2,ae+ne/2)}if(fe!==null){let ne=pr(1,se-fe),ae=(se+fe)/2;Ae(T+0.5-ne/2,T+0.5+ne/2,Y+1,Y+1+we,ae-ne/2,ae+ne/2)}}}if(a)q.push(`<g data-color="${Rt(he)}">${Xe.join("")}</g>`);else q.push(...Xe)}let Se=2+V/2,gt=Z-Se,Ze=pe-Se,et=ue-Z+Se*2,ee=M-pe+Se*2,mt=re&&p&&m&&w?`<defs><image id="${b}" href="${Rt(m)}" xlink:href="${Rt(m)}" x="0" y="0" width="${y}" height="${E}" style="image-rendering:pixelated"/></defs>`:"";return[`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="${ce(gt)} ${ce(Ze)} ${ce(et)} ${ce(ee)}" shape-rendering="crispEdges">`,mt,...q,"</svg>"].join("")}var ZA="hsla(278, 100%, 70%, 1)",XA=/hsla\(278, 100%, ([\d.]+)%, 1\)/g,On=(e)=>ho({grid:[[{active:!0,color:ZA}]],numCols:1,numRows:1,blockStyle:e,sideLighting:0.15}).replaceAll(XA,"hsl(var(--block-style-icon-hs, 278 100%) $1% / 1)"),zA=[{style:"normal",label:"Normal",icon:On("normal")},{style:"voxel",label:"Voxel",icon:On("voxel")},{style:"lego",label:"Lego",icon:On("lego")},{style:"jelly",label:"Jelly",icon:On("jelly")}];function qA(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Ao(e,t,r,n,i=1){let s=qA(t),o=`<rect x="${r}" y="${n}" width="${i}" height="${i}" fill="${s}"/>`;if(e==="normal")return o;if(e==="jelly"){let c=i*kn,u=i*0.055,d=u/2;return`<g shape-rendering="geometricPrecision">${[`<rect x="${r}" y="${n}" width="${i}" height="${i}" rx="${c}" fill="${s}"/>`,`<path d="M${r+d} ${n+i-c}V${n+c}Q${r+d} ${n+d} ${r+c} ${n+d}H${r+i-c}" fill="none" stroke="rgba(255, 255, 255, 0.22)" stroke-width="${u}" stroke-linecap="round"/>`,`<path d="M${r+i-d} ${n+c}V${n+i-c}Q${r+i-d} ${n+i-d} ${r+i-c} ${n+i-d}H${r+c}" fill="none" stroke="rgba(0, 0, 0, 0.14)" stroke-width="${u}" stroke-linecap="round"/>`].join("")}</g>`}if(e==="voxel"){let c=i*pr(1,1),u=r+(i-c)/2,d=n+(i-c)/2,A=i*0.045,f=i*0.035;return[o,`<rect x="${u+A}" y="${d+A}" width="${c}" height="${c}" fill="rgba(0, 0, 0, 0.22)"/>`,`<rect x="${u}" y="${d}" width="${c}" height="${c}" fill="${s}"/>`,`<path d="M${u} ${d+c}V${d}H${u+c}" fill="none" stroke="rgba(255, 255, 255, 0.26)" stroke-width="${f}"/>`,`<path d="M${u+c} ${d}V${d+c}H${u}" fill="none" stroke="rgba(0, 0, 0, 0.12)" stroke-width="${f}"/>`].join("")}let a=i*Hr,l=(c)=>Ei.flatMap((u)=>Ei.map((d)=>{let A=r+i*(0.5+u*mr+c),f=n+i*(0.5+d*mr+c);return`M${A+a} ${f}A${a} ${a} 0 1 1 ${A-a} ${f}A${a} ${a} 0 1 1 ${A+a} ${f}Z`})).join("");return`<g shape-rendering="geometricPrecision">${[o,`<path d="${l(0.04)}" fill="rgba(0, 0, 0, 0.22)"/>`,`<path d="${l(0)}" fill="${s}"/>`,`<path d="${l(0)}" fill="rgba(0, 0, 0, 0.06)" stroke="rgba(255, 255, 255, 0.12)" stroke-width="${i*0.025}"/>`].join("")}</g>`}var ut=[{name:"Classic",colors:["hsla(278, 100%, 50%, 1)","hsla(278, 100%, 16%, 1)","hsla(278, 100%, 80%, 1)","hsla(306, 100%, 50%, 1)","hsla(28, 100%, 60%, 1)","hsla(0, 80%, 60%, 1)","hsla(278, 60%, 35%, 1)","hsla(306, 100%, 80%, 1)","hsla(306, 80%, 30%, 1)","hsla(28, 100%, 80%, 1)"]},{name:"Super Mario",colors:["hsla(218, 100%, 68%, 1)","hsla(0, 85%, 55%, 1)","hsla(225, 85%, 45%, 1)","hsla(28, 100%, 80%, 1)","hsla(22, 60%, 32%, 1)","hsla(120, 70%, 40%, 1)","hsla(45, 100%, 55%, 1)","hsla(0, 0%, 100%, 1)","hsla(0, 0%, 8%, 1)","hsla(22, 45%, 22%, 1)"]},{name:"Pac-Man",colors:["hsla(60, 100%, 50%, 1)","hsla(240, 100%, 56%, 1)","hsla(0, 100%, 50%, 1)","hsla(300, 100%, 86%, 1)","hsla(180, 100%, 50%, 1)","hsla(32, 100%, 66%, 1)","hsla(0, 0%, 100%, 1)","hsla(0, 0%, 5%, 1)","hsla(240, 100%, 25%, 1)","hsla(60, 100%, 80%, 1)"]},{name:"Grayscale",colors:["hsla(0, 0%, 98%, 1)","hsla(0, 0%, 92%, 1)","hsla(0, 0%, 86%, 1)","hsla(0, 0%, 80%, 1)","hsla(0, 0%, 74%, 1)","hsla(0, 0%, 68%, 1)","hsla(0, 0%, 62%, 1)","hsla(0, 0%, 56%, 1)","hsla(0, 0%, 50%, 1)","hsla(0, 0%, 44%, 1)"]},{name:"Sunset",colors:["hsla(45, 100%, 70%, 1)","hsla(28, 100%, 60%, 1)","hsla(12, 90%, 55%, 1)","hsla(350, 80%, 55%, 1)","hsla(320, 60%, 45%, 1)","hsla(280, 45%, 25%, 1)","hsla(50, 100%, 88%, 1)","hsla(38, 100%, 78%, 1)","hsla(20, 100%, 68%, 1)","hsla(5, 85%, 45%, 1)"]},{name:"Ocean",colors:["hsla(180, 70%, 80%, 1)","hsla(190, 75%, 60%, 1)","hsla(205, 75%, 50%, 1)","hsla(215, 70%, 40%, 1)","hsla(225, 65%, 28%, 1)","hsla(235, 55%, 15%, 1)","hsla(175, 60%, 92%, 1)","hsla(185, 70%, 70%, 1)","hsla(195, 75%, 55%, 1)","hsla(200, 70%, 45%, 1)"]},{name:"Pastel",colors:["hsla(350, 100%, 88%, 1)","hsla(30, 100%, 85%, 1)","hsla(55, 85%, 82%, 1)","hsla(135, 60%, 82%, 1)","hsla(200, 75%, 85%, 1)","hsla(275, 70%, 85%, 1)","hsla(15, 100%, 86%, 1)","hsla(45, 100%, 85%, 1)","hsla(90, 55%, 82%, 1)","hsla(160, 55%, 82%, 1)"]},{name:"Gameboy",colors:["hsla(85, 60%, 85%, 1)","hsla(88, 58%, 78%, 1)","hsla(90, 56%, 72%, 1)","hsla(93, 55%, 66%, 1)","hsla(95, 55%, 60%, 1)","hsla(98, 53%, 54%, 1)","hsla(102, 52%, 48%, 1)","hsla(105, 51%, 42%, 1)","hsla(110, 50%, 35%, 1)","hsla(113, 52%, 30%, 1)"]},{name:"Neon",colors:["hsla(320, 100%, 60%, 1)","hsla(180, 100%, 55%, 1)","hsla(60, 100%, 60%, 1)","hsla(270, 100%, 65%, 1)","hsla(130, 100%, 55%, 1)","hsla(25, 100%, 55%, 1)","hsla(300, 100%, 50%, 1)","hsla(200, 100%, 60%, 1)","hsla(90, 100%, 55%, 1)","hsla(45, 100%, 55%, 1)"]},{name:"Forest",colors:["hsla(80, 35%, 75%, 1)","hsla(100, 40%, 50%, 1)","hsla(120, 45%, 30%, 1)","hsla(140, 35%, 18%, 1)","hsla(30, 40%, 35%, 1)","hsla(25, 50%, 22%, 1)","hsla(70, 40%, 88%, 1)","hsla(90, 45%, 62%, 1)","hsla(110, 45%, 40%, 1)","hsla(130, 40%, 24%, 1)"]},{name:"Candy",colors:["hsla(340, 100%, 80%, 1)","hsla(320, 90%, 65%, 1)","hsla(280, 85%, 65%, 1)","hsla(200, 90%, 70%, 1)","hsla(165, 75%, 65%, 1)","hsla(50, 100%, 70%, 1)","hsla(350, 100%, 90%, 1)","hsla(0, 90%, 70%, 1)","hsla(30, 100%, 72%, 1)","hsla(60, 90%, 75%, 1)"]},{name:"Cobalt",colors:["hsla(215, 85%, 94%, 1)","hsla(215, 85%, 86%, 1)","hsla(215, 85%, 78%, 1)","hsla(215, 85%, 70%, 1)","hsla(215, 85%, 62%, 1)","hsla(215, 85%, 54%, 1)","hsla(215, 85%, 46%, 1)","hsla(215, 85%, 40%, 1)","hsla(215, 85%, 34%, 1)","hsla(215, 85%, 28%, 1)"]},{name:"Terracotta",colors:["hsla(25, 55%, 78%, 1)","hsla(20, 65%, 55%, 1)","hsla(15, 60%, 40%, 1)","hsla(15, 50%, 25%, 1)","hsla(35, 40%, 60%, 1)","hsla(0, 25%, 12%, 1)","hsla(30, 60%, 88%, 1)","hsla(25, 60%, 68%, 1)","hsla(18, 65%, 48%, 1)","hsla(12, 55%, 32%, 1)"]},{name:"Vaporwave",colors:["hsla(330, 100%, 78%, 1)","hsla(290, 80%, 60%, 1)","hsla(200, 90%, 72%, 1)","hsla(170, 70%, 60%, 1)","hsla(40, 90%, 78%, 1)","hsla(260, 45%, 18%, 1)","hsla(320, 100%, 88%, 1)","hsla(310, 90%, 70%, 1)","hsla(280, 70%, 45%, 1)","hsla(250, 60%, 55%, 1)"]},{name:"Mint",colors:["hsla(160, 65%, 88%, 1)","hsla(165, 60%, 65%, 1)","hsla(170, 55%, 45%, 1)","hsla(175, 50%, 28%, 1)","hsla(180, 30%, 15%, 1)","hsla(55, 60%, 90%, 1)","hsla(155, 70%, 95%, 1)","hsla(160, 60%, 78%, 1)","hsla(165, 55%, 55%, 1)","hsla(170, 50%, 36%, 1)"]},{name:"Sakura",colors:["hsla(340, 100%, 93%, 1)","hsla(345, 85%, 80%, 1)","hsla(350, 70%, 65%, 1)","hsla(355, 60%, 48%, 1)","hsla(30, 40%, 32%, 1)","hsla(120, 30%, 42%, 1)","hsla(340, 100%, 97%, 1)","hsla(342, 90%, 87%, 1)","hsla(348, 80%, 72%, 1)","hsla(352, 65%, 56%, 1)"]},{name:"Desert",colors:["hsla(40, 55%, 82%, 1)","hsla(30, 50%, 65%, 1)","hsla(15, 45%, 48%, 1)","hsla(90, 30%, 45%, 1)","hsla(95, 25%, 22%, 1)","hsla(200, 40%, 72%, 1)","hsla(42, 60%, 92%, 1)","hsla(35, 55%, 74%, 1)","hsla(25, 50%, 56%, 1)","hsla(18, 45%, 38%, 1)"]},{name:"Galaxy",colors:["hsla(265, 70%, 82%, 1)","hsla(275, 75%, 55%, 1)","hsla(290, 85%, 35%, 1)","hsla(220, 70%, 40%, 1)","hsla(230, 60%, 12%, 1)","hsla(50, 90%, 82%, 1)","hsla(260, 80%, 92%, 1)","hsla(270, 75%, 68%, 1)","hsla(285, 80%, 45%, 1)","hsla(300, 85%, 28%, 1)"]},{name:"Ember",colors:["hsla(25, 100%, 95%, 1)","hsla(25, 100%, 88%, 1)","hsla(25, 100%, 80%, 1)","hsla(25, 100%, 72%, 1)","hsla(25, 100%, 65%, 1)","hsla(25, 100%, 58%, 1)","hsla(25, 100%, 50%, 1)","hsla(25, 100%, 44%, 1)","hsla(25, 100%, 38%, 1)","hsla(25, 100%, 32%, 1)"]},{name:"Watermelon",colors:["hsla(350, 85%, 80%, 1)","hsla(350, 75%, 62%, 1)","hsla(355, 65%, 45%, 1)","hsla(90, 45%, 62%, 1)","hsla(110, 50%, 30%, 1)","hsla(0, 0%, 8%, 1)","hsla(350, 90%, 90%, 1)","hsla(350, 80%, 70%, 1)","hsla(352, 70%, 55%, 1)","hsla(358, 60%, 38%, 1)"]}];var ef=16777216,tf=16;function Yr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function rf(e){if(!Array.isArray(e))return[...ut[0].colors];let t=e.slice(0,tf).flatMap((r)=>{if(typeof r==="string"&&vt(r))return[r];if(Yr(r)&&vt(r.color)&&typeof r.opacity==="number"&&Number.isFinite(r.opacity)&&r.opacity>=0&&r.opacity<=1)return[r.color];return[]});return t.length>0?t:[...ut[0].colors]}function nf(e){if(!Array.isArray(e.artboards))return 0;return Number.isInteger(e.activeArtboard)&&Number(e.activeArtboard)>=0&&Number(e.activeArtboard)<e.artboards.length?Number(e.activeArtboard):0}function sf(e){let t=Yr(e)?e:{};return{saturation:ct(t.saturation),lightness:ct(t.lightness)}}function Pn(e){if(e.length>ef)throw Error("Draft is too large");let t=JSON.parse(e);if(!Yr(t)||t.version!==1)throw Error("Not a Flatblox version-1 draft");let r=Rn(t.grid),n=t.gridSize===void 0?r.length:t.gridSize;if(!Number.isInteger(n)||Number(n)<1||Number(n)>Te||r.length!==n||!r.every((o)=>o.length===n))throw Error("Draft contains an invalid grid");let i=rf(t.palette),s=vt(t.activeColor)?t.activeColor:i[0];return{filename:typeof t.filename==="string"?In(t.filename):"untitled",grid:r,palette:i,activeColor:s,paletteColorAdjustment:sf(t.paletteColorAdjustment),draft:{data:t,activeArtboard:nf(t)}}}function of(e,t){let r=Array.isArray(t)?t:[];return e.map((n,i)=>{let s=r[i];if(!Yr(s))return{color:n,opacity:1};let o=typeof s.opacity==="number"&&Number.isFinite(s.opacity)&&s.opacity>=0&&s.opacity<=1?s.opacity:1;return{...s,color:n,opacity:o}})}function af(e,t){let r=e.draft?.data.artboards,n=Array.isArray(r)?[...r]:[],i=n.length>0?Math.min(e.draft?.activeArtboard??0,n.length-1):0;if(n.length===0)n.push(t);else{let s=n[i];n[i]=Yr(s)&&"grid"in s?{...s,grid:t}:t}return{artboards:n,activeArtboard:i}}function Dn(e){let t=e.draft?.data,r=Kr(e.grid),n=of(e.palette,t?.palette),{artboards:i,activeArtboard:s}=af(e,r),o=e.paletteColorAdjustment??{saturation:0,lightness:0},a=Yr(t?.paletteColorAdjustment)?t.paletteColorAdjustment:{};return JSON.stringify({...t,version:1,grid:r,gridSize:e.grid.length,palette:n,paletteColorAdjustment:{...a,saturation:ct(o.saturation),lightness:ct(o.lightness)},activeColor:e.activeColor,artboards:i,activeArtboard:s,filename:e.filename,savedAt:new Date().toISOString()},null,2)}function Qr(e){return e==="rectangle"||e==="circle"}function lf(e,t){let r=Math.min(e.x,t.x),n=Math.max(e.x,t.x),i=Math.min(e.y,t.y),s=Math.max(e.y,t.y),o=[];for(let a=r;a<=n;a++)if(o.push({x:a,y:i}),s!==i)o.push({x:a,y:s});for(let a=i+1;a<s;a++)if(o.push({x:r,y:a}),n!==r)o.push({x:n,y:a});return o}function cf(e,t){let r=[],n=(p,v)=>r.push({x:p,y:v}),i=Math.min(e.x,t.x),s=Math.max(e.x,t.x),o=Math.min(e.y,t.y),a=Math.max(e.y,t.y),l=s-i,c=a-o;if(l===0||c===0){for(let p=o;p<=a;p++)for(let v=i;v<=s;v++)n(v,p);return r}let u=c&1,d=4*(1-l)*c*c,A=4*(u+1)*l*l,f=d+A+u*l*l;o+=c+1>>1,a=o-u;let g=8*l*l,m=8*c*c;do{n(s,o),n(i,o),n(i,a),n(s,a);let p=2*f;if(p<=A)o++,a--,A+=g,f+=A;if(p>=d||2*f>A)i++,s--,d+=m,f+=d}while(i<=s);while(o-a<c)n(i-1,o),n(s+1,o),o++,n(i-1,a),n(s+1,a),a--;return r}function fo(e,t,r){let n=e==="circle"?cf(t,r):lf(t,r),i=new Set;return n.filter((s)=>{let o=`${s.x}:${s.y}`;if(i.has(o))return!1;return i.add(o),!0})}var Ll=16,uf=100;function Ml(e,t,r){return Math.max(t,Math.min(r,e))}function Nn(e){return e.map((t)=>t.map((r)=>({...r})))}function df(e){return Array.from({length:e},()=>Array.from({length:e},()=>({active:!1,color:null})))}function Fl(e){if(!Number.isInteger(e)||e<1||e>Te)throw Error(`Grid size must be between 1 and ${Te}`);return e}function Mn(e=Ll){let t=[...ut[0].colors];return{filename:"untitled",grid:df(Fl(e)),palette:t,activeColor:t[0],paletteColorAdjustment:{saturation:0,lightness:0}}}function Si(e,t,r,n){let i=[t];if(r)i.push({x:e-1-t.x,y:t.y});if(n)i.push({x:t.x,y:e-1-t.y});if(r&&n)i.push({x:e-1-t.x,y:e-1-t.y});return[...new Map(i.map((s)=>[`${s.x}:${s.y}`,s])).values()]}class Vt{palette;paletteColorAdjustment;cursor={x:0,y:0};tool="draw";mirrorX=!1;mirrorY=!1;activeColorIndex;currentId=0;nextId=1;savedId=0;currentFilename;savedFilename;undoStack=[];redoStack=[];currentGrid;draft;constructor(e){let t=Fl(e.grid.length);if(!e.grid.every((n)=>n.length===t))throw Error("Grid must be square");if(e.palette.length===0)throw Error("Palette is empty");this.currentFilename=e.filename||"untitled",this.savedFilename=this.currentFilename,this.palette=[...e.palette],this.paletteColorAdjustment={saturation:ct(e.paletteColorAdjustment?.saturation),lightness:ct(e.paletteColorAdjustment?.lightness)},this.draft=e.draft,this.currentGrid=Nn(e.grid);let r=this.palette.indexOf(e.activeColor);this.activeColorIndex=r>=0?r:0}get grid(){return this.currentGrid}get filename(){return this.currentFilename}get size(){return this.currentGrid.length}get activeColor(){return this.palette[this.activeColorIndex]}get selectedColorIndex(){return this.activeColorIndex}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}get dirty(){return this.currentId!==this.savedId||this.currentFilename!==this.savedFilename}get revision(){return{id:this.currentId,filename:this.currentFilename}}rename(e){let t=e.trim();if(!t||t===this.currentFilename)return!1;return this.currentFilename=t,!0}moveCursor(e,t){this.setCursor(this.cursor.x+e,this.cursor.y+t)}setCursor(e,t){this.cursor={x:Ml(Math.round(e),0,this.size-1),y:Ml(Math.round(t),0,this.size-1)}}setTool(e){this.tool=e}selectColor(e){let t=this.palette.length;this.activeColorIndex=(Math.round(e)%t+t)%t}selectNextColor(e){this.selectColor(this.activeColorIndex+e)}toggleMirrorX(){this.mirrorX=!this.mirrorX}toggleMirrorY(){this.mirrorY=!this.mirrorY}applyAtCursor(e=this.tool){return this.applyAt(this.cursor.x,this.cursor.y,e)}applyAt(e,t,r=this.tool){if(e<0||e>=this.size||t<0||t>=this.size)return!1;return this.commit(()=>r==="fill"?this.fill(e,t):this.paintMirrored(e,t,r==="erase"?null:this.activeColor))}applyShape(e,t,r){if(!Qr(e))return!1;let n=this.shapePreview(e,t,r);if(n.length===0)return!1;return this.commit(()=>{let i=!1;for(let s of n)if(this.paintMirrored(s.x,s.y,this.activeColor))i=!0;return i})}shapePreview(e,t,r){let n=(i)=>i.x>=0&&i.x<this.size&&i.y>=0&&i.y<this.size;return fo(e,t,r).filter(n)}commit(e){let t=Nn(this.currentGrid);if(!e())return!1;if(this.undoStack.push({grid:t,id:this.currentId}),this.undoStack.length>uf)this.undoStack.shift();return this.redoStack=[],this.currentId=this.nextId++,!0}undo(){let e=this.undoStack.pop();if(!e)return!1;return this.redoStack.push({grid:Nn(this.currentGrid),id:this.currentId}),this.currentGrid=e.grid,this.currentId=e.id,!0}redo(){let e=this.redoStack.pop();if(!e)return!1;return this.undoStack.push({grid:Nn(this.currentGrid),id:this.currentId}),this.currentGrid=e.grid,this.currentId=e.id,!0}markSaved(e=this.revision){if(e.id!==this.currentId||e.filename!==this.currentFilename)return!1;return this.savedId=e.id,this.savedFilename=e.filename,!0}toDocument(){return{filename:this.currentFilename,grid:Nn(this.currentGrid),palette:[...this.palette],activeColor:this.activeColor,paletteColorAdjustment:{...this.paletteColorAdjustment},...this.draft?{draft:{data:this.draft.data,activeArtboard:this.draft.activeArtboard}}:{}}}paintMirrored(e,t,r){let n=!1;for(let i of Si(this.size,{x:e,y:t},this.mirrorX,this.mirrorY)){let s=this.currentGrid[i.y][i.x],o=r!==null;if(s.active===o&&s.color===r&&s.tileIndex==null)continue;this.currentGrid[i.y][i.x]=o?{...s,active:o,color:r,tileIndex:null}:{active:o,color:r},n=!0}return n}fill(e,t){let r=this.currentGrid[t][e];if(r.active&&r.color===this.activeColor&&r.tileIndex==null)return!1;let{active:n,color:i}=r,s=r.tileIndex??null,o=[{x:e,y:t}],a=new Set,l=!1;while(o.length>0){let c=o.pop();if(c.x<0||c.x>=this.size||c.y<0||c.y>=this.size)continue;let u=c.y*this.size+c.x;if(a.has(u))continue;a.add(u);let d=this.currentGrid[c.y][c.x];if(d.active!==n||n&&(d.color!==i||(d.tileIndex??null)!==s))continue;this.currentGrid[c.y][c.x]={...d,active:!0,color:this.activeColor,tileIndex:null},l=!0,o.push({x:c.x+1,y:c.y},{x:c.x-1,y:c.y},{x:c.x,y:c.y+1},{x:c.x,y:c.y-1})}return l}}import{createConnection as hf}from"net";var Af="127.0.0.1",ff=47642,gf=3000,mf=32,pf=1048576,bf=16384,Gl=[0.57,0.57,0.6,1],Ul=new Map;function yf(e){if(!e)return[...Gl];let t=Ul.get(e);if(!t){let r=Jt(e);t=r?[r.r/255,r.g/255,r.b/255,r.a]:[...Gl],Ul.set(e,t)}return t}function wf(e){if(!e?.active)return{active:!1,color:null,depth:1,mirrorZ:!1};return{active:!0,color:yf(e.color),depth:At(e.depth),mirrorZ:!!e.mirrorZ}}function jl(e,t,r){return{x:t%r,y:Math.floor(t/r),...e}}function vf(e,t){let r=e.color===t.color||!!e.color&&!!t.color&&e.color.every((n,i)=>n===t.color?.[i]);return e.active===t.active&&r&&e.depth===t.depth&&e.mirrorZ===t.mirrorZ}function Kl(e){let{saturation:t,lightness:r}=e.paletteColorAdjustment??{saturation:0,lightness:0},n=Qt(e.grid,t,r),i=n.length,s=n[0]?.length??0;return Array.from({length:s*i},(o,a)=>wf(n[Math.floor(a/s)]?.[a%s]))}function _f(e){let t=e.grid.length,r=e.grid[0]?.length??0,n=Kl(e);return{message:{protocol:xi,type:"snapshot",columns:r,rows:t,cells:n.flatMap((i,s)=>i.active?[jl(i,s,r)]:[])},state:n}}function Cf(e,t,r){return t.flatMap((n,i)=>e[i]&&vf(e[i],n)?[]:[jl(n,i,r)])}function Hl(e){return(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string"?e.code:"")==="ECONNREFUSED"?"Blender add-on not found. Enable Flatblox Live in Blender.":"Could not connect to the Blender add-on."}class go{document;connector;socket=null;status={state:"disconnected"};listeners=new Set;connectPromise=null;resolveConnect=null;connectTimer=null;patchTimer=null;handshakeBuffer="";previousGrid=null;previousColumns=0;previousRows=0;pendingCells=new Map;constructor(e,t=hf){this.document=e,this.connector=t}getStatus(){return{...this.status}}onStatus(e){return this.listeners.add(e),()=>this.listeners.delete(e)}connect(){if(this.status.state==="connected")return Promise.resolve(this.getStatus());if(this.connectPromise)return this.connectPromise;this.disconnectSocket(),this.resetStream(),this.handshakeBuffer="",this.setStatus({state:"connecting"}),this.connectPromise=new Promise((t)=>{this.resolveConnect=t});let e;try{e=this.connector({host:Af,port:ff})}catch(t){let r={state:"error",message:Hl(t)};return this.setStatus(r),this.finishConnect(r),Promise.resolve(r)}return this.socket=e,e.setNoDelay(!0),e.on("data",(t)=>this.handleHandshake(e,t)),e.on("error",(t)=>this.fail(e,Hl(t))),e.on("close",()=>this.handleClose(e)),this.connectTimer=setTimeout(()=>{this.fail(e,"Timed out waiting for the Blender add-on.")},gf),this.connectPromise}disconnect(){this.disconnectSocket(),this.resetStream();let e={state:"disconnected"};return this.setStatus(e),this.finishConnect(e),e}sync(){if(this.status.state!=="connected"||!this.socket)return;if(!this.patchTimer)this.patchTimer=setTimeout(()=>this.flushPatch(),mf)}collectChanges(){let e=this.document(),t=e.grid.length,r=e.grid[0]?.length??0;if(!this.previousGrid||r!==this.previousColumns||t!==this.previousRows){this.sendSnapshot(e);return}let n=Kl(e);for(let i of Cf(this.previousGrid,n,r))this.pendingCells.set(i.y*r+i.x,i);this.previousGrid=n}dispose(){this.disconnect(),this.listeners.clear()}handleHandshake(e,t){if(this.socket!==e||this.status.state!=="connecting")return;if(this.handshakeBuffer+=t.toString("utf8"),Buffer.byteLength(this.handshakeBuffer)>bf){this.fail(e,"Blender sent an invalid handshake.");return}let r=this.handshakeBuffer.indexOf(`
10
- `);if(r<0)return;let n;try{n=JSON.parse(this.handshakeBuffer.slice(0,r))}catch{this.fail(e,"Blender sent an invalid handshake.");return}if(typeof n!=="object"||n===null||!("type"in n)||n.type!=="hello"||!("protocol"in n)||n.protocol!==xi){this.fail(e,"The Blender add-on uses an incompatible protocol.");return}this.clearConnectTimer(),this.handshakeBuffer="";let i={state:"connected",message:"Live in Blender"};this.setStatus(i),this.finishConnect(i),this.sendSnapshot(this.document())}handleClose(e){if(this.socket!==e)return;this.socket=null,this.clearConnectTimer(),this.resetStream();let t=this.status.state==="connecting"?{state:"error",message:"Blender closed the connection during setup."}:{state:"disconnected",message:"Blender disconnected."};this.setStatus(t),this.finishConnect(t)}sendSnapshot(e){if(this.patchTimer)clearTimeout(this.patchTimer);this.patchTimer=null,this.pendingCells.clear();let{message:t,state:r}=_f(e);if(this.previousGrid=r,this.previousColumns=t.columns,this.previousRows=t.rows,!this.send(t))this.previousGrid=null}flushPatch(){if(this.patchTimer=null,this.status.state==="connected"&&this.socket)this.collectChanges();if(this.status.state!=="connected"||this.pendingCells.size===0){this.pendingCells.clear();return}let e={protocol:xi,type:"patch",columns:this.previousColumns,rows:this.previousRows,cells:[...this.pendingCells.values()]};if(this.pendingCells.clear(),!this.send(e))this.previousGrid=null}send(e){if(!this.socket?.writable||this.status.state!=="connected")return!1;let t=Buffer.from(`${JSON.stringify(e)}
11
- `);if(t.length>pf)return!1;try{return this.socket.write(Uint8Array.from(t)),!0}catch{return!1}}fail(e,t){if(this.socket!==e)return;this.socket=null,this.clearConnectTimer(),this.resetStream(),e.destroy();let r={state:"error",message:t};this.setStatus(r),this.finishConnect(r)}disconnectSocket(){let e=this.socket;this.socket=null,this.clearConnectTimer(),e?.destroy()}resetStream(){if(this.patchTimer)clearTimeout(this.patchTimer);this.patchTimer=null,this.previousGrid=null,this.previousColumns=0,this.previousRows=0,this.pendingCells.clear()}clearConnectTimer(){if(this.connectTimer)clearTimeout(this.connectTimer);this.connectTimer=null}finishConnect(e){this.resolveConnect?.({...e}),this.resolveConnect=null,this.connectPromise=null}setStatus(e){this.status=e;for(let t of this.listeners)t({...e})}}import{NativeImage as Ql,parseColor as po}from"@opentui/core";import{parseColor as xf,Renderable as Ef,RGBA as Sf}from"@opentui/core";var mo=new WeakMap;function xt(e){let t=e.terminalWidth??e.width,r=e.terminalHeight??e.height,n=e.resolution;if(!n||t<=0||r<=0||n.width<=0||n.height<=0)return mo.get(e)??null;let i=n.width/t,s=n.height/r,o=mo.get(e);if(o&&o.width===i&&o.height===s)return o;let a=Number.isFinite(i)&&Number.isFinite(s)&&i>0&&s>0?{width:i,height:s}:null;if(a)mo.set(e,a);return a??o??null}function Ii(e){let t=xt(e);if(!t)return 2;let r=t.height/t.width;return Number.isFinite(r)&&r>=0.5&&r<=4?r:2}function ir(e){if(!e||e.image_protocol==="blocks")return!1;if(e.image_protocol==="kitty"||e.image_protocol==="sixel")return!0;if(e.multiplexer==="tmux")return!1;return Boolean(e.kitty_graphics||e.sixel)}function ki(e){return Boolean(xt(e)&&ir(e.capabilities))}var If={width:8,height:16};function kf(e,t,r,n,i,s,o="center"){let a=Math.max(1,Math.round(e*i)),l=Math.max(1,Math.round(t*s)),c=Math.min(a/r,l/n),u=Math.max(1,Math.min(a,Math.round(r*c))),d=Math.max(1,Math.min(l,Math.round(n*c)));return{pixelWidth:a,pixelHeight:l,fittedWidth:u,fittedHeight:d,left:o==="center"?Math.floor((a-u)/2):0,top:Math.floor((l-d)/2)}}class Ln extends Ef{_source=null;_background=Sf.fromInts(0,0,0);_backgroundKey="";_kernel="default";_align="center";frame=null;frameCache=null;constructor(e,t){super(e,{...t,buffered:!0});if(this._source=t.source??null,t.background)this.background=t.background;if(t.kernel)this._kernel=t.kernel;if(t.align)this._align=t.align}set source(e){let t=e??null;if(t===this._source)return;this._source=t,this.releaseFrame(),this.requestRender()}get source(){return this._source}set background(e){if(!e||e===this._backgroundKey)return;this._backgroundKey=e,this._background=xf(e),this.releaseFrame(),this.requestRender()}set kernel(e){if(!e||e===this._kernel)return;this._kernel=e,this.releaseFrame(),this.requestRender()}set align(e){if(!e||e===this._align)return;this._align=e,this.releaseFrame(),this.requestRender()}renderSelf(e){e.clear(this._background);let t=this._source;if(!t||this.width<=0||this.height<=0||!ir(this._ctx.capabilities)){this.releaseFrame();return}let r=xt(this._ctx)??If,n=kf(this.width,this.height,t.width,t.height,r.width,r.height,this._align),i=this._backgroundKey,s=this.frameCache;if(!(this.frame&&s&&s.source===t&&s.pixelWidth===n.pixelWidth&&s.pixelHeight===n.pixelHeight&&s.background===i)){let a=t.resize({width:n.fittedWidth,height:n.fittedHeight,kernel:this._kernel}),l=a.extend({left:n.left,top:n.top,right:n.pixelWidth-n.fittedWidth-n.left,bottom:n.pixelHeight-n.fittedHeight-n.top,background:this._background.toInts()});if(l!==a)a.dispose();this.releaseFrame(),this.frame=l,this.frameCache={source:t,pixelWidth:n.pixelWidth,pixelHeight:n.pixelHeight,background:i}}if(!this.frame)return;e.drawImage(this.frame,0,0,this.width,this.height,n.pixelWidth,n.pixelHeight,0,0,n.pixelWidth,n.pixelHeight,"auto")}releaseFrame(){this.frame?.dispose(),this.frame=null,this.frameCache=null}destroySelf(){this.releaseFrame(),super.destroySelf()}}var Wl=new WeakMap;function Jr(){let e=ht(),t=Wl.get(e);if(t)return t;let r=fr(()=>{let[n,i]=j(ir(e.capabilities));return e.on("capabilities",()=>i(ir(e.capabilities))),n});return Wl.set(e,r),r}Yt({fitted_image:Ln});var bo=32;function Rf(e){let[t,r,n]=po(e).toInts();return Ql.fromRgba(new Uint8Array([t,r,n,255]),1,1)}function Tf(e,t,r=bo){let n=po(e).toInts(),i=po(t).toInts(),s=new Uint8Array(r*r*4),o=r/2;for(let a=0;a<r;a++)for(let l=0;l<r;l++){let c=Math.hypot(l+0.5-o,a+0.5-o),u=Math.max(0,Math.min(1,o-c+0.5)),d=(a*r+l)*4;for(let A=0;A<3;A++)s[d+A]=Math.round(i[A]+(n[A]-i[A])*u);s[d+3]=255}return s}var Yl=new Map;function Bf(e,t){let r=`${e}|${t}`,n=Yl.get(r);if(!n)n=Tf(e,t),Yl.set(r,n);return Ql.fromRgba(n,bo,bo)}function Fn(e){let t=Jr(),r=()=>e.width??2,n=()=>e.shape??"square",i=K(()=>{let s=n()==="circle"?Bf(e.color,e.background):Rf(e.color);return ot(()=>s.dispose()),s});return Q(ke,{get when(){return t()},get fallback(){return(()=>{var s=S("text");return L(s,(()=>{var o=lt(()=>n()==="circle");return()=>o()?"\u2B24":"\u2588".repeat(r())})()),de((o)=>h(s,"fg",e.color,o)),s})()},get children(){var s=S("fitted_image");return h(s,"height",1),h(s,"align","start"),de((o)=>{var a=r(),l=i(),c=e.background,u=n()==="circle"?"default":"nearest";return a!==o.e&&(o.e=h(s,"width",a,o.e)),l!==o.t&&(o.t=h(s,"source",l,o.t)),c!==o.a&&(o.a=h(s,"background",c,o.a)),u!==o.o&&(o.o=h(s,"kernel",u,o.o)),o},{e:void 0,t:void 0,a:void 0,o:void 0}),s}})}import{existsSync as Df,statSync as Nf}from"fs";import{homedir as Mf}from"os";import{basename as Lf,join as Ff,resolve as yo}from"path";import{deflateSync as Gf}from"zlib";var $t=Math.PI/4,sr=Math.asin(1/Math.sqrt(3)),Of=1,Pf=2500000;function Jl(e,t,r,n,i={}){let{density:s=Of,maxPixels:o=Pf}=i,a=Math.max(1,Math.round(e*r*s)),l=Math.max(1,Math.round(t*n*s)),c=Math.min(1,2560/Math.max(a,l),Math.sqrt(o/(a*l)));return{width:Math.max(1,Math.round(a*c)),height:Math.max(1,Math.round(l*c))}}function Ri(e){let t=e.length,r=e.reduce((i,s)=>Math.max(i,s.length),0),n=[];for(let i=0;i<t;i+=1)for(let s=0;s<e[i].length;s+=1){let o=e[i][s];if(!o.active||!o.color)continue;let{primary:a,mirrored:l}=_n(o.depth,o.mirrorZ),c=s-(r-1)/2,u=i-(t-1)/2;if(n.push({x:c,y:a/2,z:u,height:a,color:o.color}),l>0)n.push({x:c,y:-l/2,z:u,height:l,color:o.color})}return n}function Vl(e=process.platform,t=process.arch){if(e==="linux")return t==="x64";if(e==="win32")return t==="x64";return e==="darwin"&&(t==="x64"||t==="arm64")}var Tt=["svg","obj","png"],vo=16,Uf=new Uint8Array([137,80,78,71,13,10,26,10]);function $l(e){return Tt.includes(e)}function Gn(e,t){return(e??t).replace(/\.flatblox\.json$/i,"").replace(/\.json$/i,"")}function Ti(e,t,r){let n=e.trim();if(!n)return yo(r);let i=n.startsWith("~/")?Ff(Mf(),n.slice(2)):n;if(/[\\/]$/.test(i)||Df(i)&&Nf(i).isDirectory())return yo(i,t);return yo(Gn(i,i).replace(/\.(svg|obj|mtl|png)$/i,""))}function Zl(e){return e.reduce((t,r)=>Math.max(t,r.length),0)}function Xl(e){return e.active&&!!e.color}function Hf(e){let t=e.length,r=Zl(e),n=[];for(let i=0;i<t;i++)for(let s=0;s<e[i].length;s++){let o=e[i][s];if(Xl(o))n.push(Ao("normal",o.color,s,i))}return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${r} ${t}" width="${r*vo}" height="${t*vo}" shape-rendering="crispEdges">${n.join("")}</svg>`}function jf(e,t){let r=nr(e);return`color_${r?[r.r,r.g,r.b].map((i)=>i.toString(16).padStart(2,"0")).join(""):String(t)}`}function Vr(e){return Number(e.toFixed(4)).toString()}function Kf(e,t){let r=Ri(e),n=new Map,i=[`mtllib ${t}`],s=[],o=0;for(let a of r){let l=n.get(a.color);if(!l){l=jf(a.color,n.size),n.set(a.color,l);let v=nr(a.color)??{r:255,g:255,b:255};s.push(`newmtl ${l}`,`Kd ${Vr(v.r/255)} ${Vr(v.g/255)} ${Vr(v.b/255)}`,"")}let c=a.x-0.5,u=a.x+0.5,d=a.y-a.height/2,A=a.y+a.height/2,f=a.z-0.5,g=a.z+0.5,m=[[c,d,f],[u,d,f],[u,A,f],[c,A,f],[c,d,g],[u,d,g],[u,A,g],[c,A,g]];for(let[v,y,E]of m)i.push(`v ${Vr(v)} ${Vr(y)} ${Vr(E)}`);let p=[[4,3,2,1],[5,6,7,8],[1,2,6,5],[8,7,3,4],[2,3,7,6],[1,5,8,4]];i.push(`usemtl ${l}`);for(let v of p)i.push(`f ${v.map((y)=>y+o).join(" ")}`);o+=8}return{obj:`${i.join(`
6
+ var ih=Object.create;var{getPrototypeOf:sh,defineProperty:Ha,getOwnPropertyNames:oh}=Object;var ah=Object.prototype.hasOwnProperty;function lh(e){return this[e]}var ch,uh,dh=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var i=t?ch??=new WeakMap:uh??=new WeakMap,s=i.get(e);if(s)return s}r=e!=null?ih(sh(e)):{};let o=t||!e||!e.__esModule?Ha(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of oh(e))if(!ah.call(o,a))Ha(o,a,{get:lh.bind(e,a),enumerable:!0})}if(n)i.set(e,o);return o};var hh=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var iu=hh(function(jx,is){var Tc,Oc,Bc,Pc,Dc,Mc,Nc,Lc,Fc,Gc,Uc,Hc,jc,rs,Yo,Kc,Wc,Yc,en,Qc,Jc,Vc,Zc,$c,Xc,zc,qc,eu,ns,tu,ru,nu;(function(e){var t=typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:{};if(typeof define==="function"&&define.amd)define("tslib",["exports"],function(n){e(r(t,r(n)))});else if(typeof is==="object"&&typeof jx==="object")e(r(t,r(jx)));else e(r(t));function r(n,i){if(n!==t)if(typeof Object.create==="function")Object.defineProperty(n,"__esModule",{value:!0});else n.__esModule=!0;return function(s,o){return n[s]=i?i(s,o):o}}})(function(e){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,o){s.__proto__=o}||function(s,o){for(var a in o)if(Object.prototype.hasOwnProperty.call(o,a))s[a]=o[a]};Tc=function(s,o){if(typeof o!=="function"&&o!==null)throw TypeError("Class extends value "+String(o)+" is not a constructor or null");t(s,o);function a(){this.constructor=s}s.prototype=o===null?Object.create(o):(a.prototype=o.prototype,new a)},Oc=Object.assign||function(s){for(var o,a=1,l=arguments.length;a<l;a++){o=arguments[a];for(var c in o)if(Object.prototype.hasOwnProperty.call(o,c))s[c]=o[c]}return s},Bc=function(s,o){var a={};for(var l in s)if(Object.prototype.hasOwnProperty.call(s,l)&&o.indexOf(l)<0)a[l]=s[l];if(s!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var c=0,l=Object.getOwnPropertySymbols(s);c<l.length;c++)if(o.indexOf(l[c])<0&&Object.prototype.propertyIsEnumerable.call(s,l[c]))a[l[c]]=s[l[c]]}return a},Pc=function(s,o,a,l){var c=arguments.length,u=c<3?o:l===null?l=Object.getOwnPropertyDescriptor(o,a):l,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")u=Reflect.decorate(s,o,a,l);else for(var f=s.length-1;f>=0;f--)if(d=s[f])u=(c<3?d(u):c>3?d(o,a,u):d(o,a))||u;return c>3&&u&&Object.defineProperty(o,a,u),u},Dc=function(s,o){return function(a,l){o(a,l,s)}},Mc=function(s,o,a,l,c,u){function d(v){if(v!==void 0&&typeof v!=="function")throw TypeError("Function expected");return v}var f=l.kind,g=f==="getter"?"get":f==="setter"?"set":"value",A=!o&&s?l.static?s:s.prototype:null,m=o||(A?Object.getOwnPropertyDescriptor(A,l.name):{}),b,w=!1;for(var p=a.length-1;p>=0;p--){var C={};for(var _ in l)C[_]=_==="access"?{}:l[_];for(var _ in l.access)C.access[_]=l.access[_];C.addInitializer=function(v){if(w)throw TypeError("Cannot add initializers after decoration has completed");u.push(d(v||null))};var y=(0,a[p])(f==="accessor"?{get:m.get,set:m.set}:m[g],C);if(f==="accessor"){if(y===void 0)continue;if(y===null||typeof y!=="object")throw TypeError("Object expected");if(b=d(y.get))m.get=b;if(b=d(y.set))m.set=b;if(b=d(y.init))c.unshift(b)}else if(b=d(y))if(f==="field")c.unshift(b);else m[g]=b}if(A)Object.defineProperty(A,l.name,m);w=!0},Nc=function(s,o,a){var l=arguments.length>2;for(var c=0;c<o.length;c++)a=l?o[c].call(s,a):o[c].call(s);return l?a:void 0},Lc=function(s){return typeof s==="symbol"?s:"".concat(s)},Fc=function(s,o,a){if(typeof o==="symbol")o=o.description?"[".concat(o.description,"]"):"";return Object.defineProperty(s,"name",{configurable:!0,value:a?"".concat(a," ",o):o})},Gc=function(s,o){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(s,o)},Uc=function(s,o,a,l){function c(u){return u instanceof a?u:new a(function(d){d(u)})}return new(a||(a=Promise))(function(u,d){function f(m){try{A(l.next(m))}catch(b){d(b)}}function g(m){try{A(l.throw(m))}catch(b){d(b)}}function A(m){m.done?u(m.value):c(m.value).then(f,g)}A((l=l.apply(s,o||[])).next())})},Hc=function(s,o){var a={label:0,sent:function(){if(u[0]&1)throw u[1];return u[1]},trys:[],ops:[]},l,c,u,d=Object.create((typeof Iterator==="function"?Iterator:Object).prototype);return d.next=f(0),d.throw=f(1),d.return=f(2),typeof Symbol==="function"&&(d[Symbol.iterator]=function(){return this}),d;function f(A){return function(m){return g([A,m])}}function g(A){if(l)throw TypeError("Generator is already executing.");while(d&&(d=0,A[0]&&(a=0)),a)try{if(l=1,c&&(u=A[0]&2?c.return:A[0]?c.throw||((u=c.return)&&u.call(c),0):c.next)&&!(u=u.call(c,A[1])).done)return u;if(c=0,u)A=[A[0]&2,u.value];switch(A[0]){case 0:case 1:u=A;break;case 4:return a.label++,{value:A[1],done:!1};case 5:a.label++,c=A[1],A=[0];continue;case 7:A=a.ops.pop(),a.trys.pop();continue;default:if((u=a.trys,!(u=u.length>0&&u[u.length-1]))&&(A[0]===6||A[0]===2)){a=0;continue}if(A[0]===3&&(!u||A[1]>u[0]&&A[1]<u[3])){a.label=A[1];break}if(A[0]===6&&a.label<u[1]){a.label=u[1],u=A;break}if(u&&a.label<u[2]){a.label=u[2],a.ops.push(A);break}if(u[2])a.ops.pop();a.trys.pop();continue}A=o.call(s,a)}catch(m){A=[6,m],c=0}finally{l=u=0}if(A[0]&5)throw A[1];return{value:A[0]?A[1]:void 0,done:!0}}},jc=function(s,o){for(var a in s)if(a!=="default"&&!Object.prototype.hasOwnProperty.call(o,a))ns(o,s,a)},ns=Object.create?function(s,o,a,l){if(l===void 0)l=a;var c=Object.getOwnPropertyDescriptor(o,a);if(!c||("get"in c?!o.__esModule:c.writable||c.configurable))c={enumerable:!0,get:function(){return o[a]}};Object.defineProperty(s,l,c)}:function(s,o,a,l){if(l===void 0)l=a;s[l]=o[a]},rs=function(s){var o=typeof Symbol==="function"&&Symbol.iterator,a=o&&s[o],l=0;if(a)return a.call(s);if(s&&typeof s.length==="number")return{next:function(){if(s&&l>=s.length)s=void 0;return{value:s&&s[l++],done:!s}}};throw TypeError(o?"Object is not iterable.":"Symbol.iterator is not defined.")},Yo=function(s,o){var a=typeof Symbol==="function"&&s[Symbol.iterator];if(!a)return s;var l=a.call(s),c,u=[],d;try{while((o===void 0||o-- >0)&&!(c=l.next()).done)u.push(c.value)}catch(f){d={error:f}}finally{try{if(c&&!c.done&&(a=l.return))a.call(l)}finally{if(d)throw d.error}}return u},Kc=function(){for(var s=[],o=0;o<arguments.length;o++)s=s.concat(Yo(arguments[o]));return s},Wc=function(){for(var s=0,o=0,a=arguments.length;o<a;o++)s+=arguments[o].length;for(var l=Array(s),c=0,o=0;o<a;o++)for(var u=arguments[o],d=0,f=u.length;d<f;d++,c++)l[c]=u[d];return l},Yc=function(s,o,a){if(a||arguments.length===2){for(var l=0,c=o.length,u;l<c;l++)if(u||!(l in o)){if(!u)u=Array.prototype.slice.call(o,0,l);u[l]=o[l]}}return s.concat(u||Array.prototype.slice.call(o))},en=function(s){return this instanceof en?(this.v=s,this):new en(s)},Qc=function(s,o,a){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var l=a.apply(s,o||[]),c,u=[];return c=Object.create((typeof AsyncIterator==="function"?AsyncIterator:Object).prototype),f("next"),f("throw"),f("return",d),c[Symbol.asyncIterator]=function(){return this},c;function d(p){return function(C){return Promise.resolve(C).then(p,b)}}function f(p,C){if(l[p]){if(c[p]=function(_){return new Promise(function(y,v){u.push([p,_,y,v])>1||g(p,_)})},C)c[p]=C(c[p])}}function g(p,C){try{A(l[p](C))}catch(_){w(u[0][3],_)}}function A(p){p.value instanceof en?Promise.resolve(p.value.v).then(m,b):w(u[0][2],p)}function m(p){g("next",p)}function b(p){g("throw",p)}function w(p,C){if(p(C),u.shift(),u.length)g(u[0][0],u[0][1])}},Jc=function(s){var o,a;return o={},l("next"),l("throw",function(c){throw c}),l("return"),o[Symbol.iterator]=function(){return this},o;function l(c,u){o[c]=s[c]?function(d){return(a=!a)?{value:en(s[c](d)),done:!1}:u?u(d):d}:u}},Vc=function(s){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var o=s[Symbol.asyncIterator],a;return o?o.call(s):(s=typeof rs==="function"?rs(s):s[Symbol.iterator](),a={},l("next"),l("throw"),l("return"),a[Symbol.asyncIterator]=function(){return this},a);function l(u){a[u]=s[u]&&function(d){return new Promise(function(f,g){d=s[u](d),c(f,g,d.done,d.value)})}}function c(u,d,f,g){Promise.resolve(g).then(function(A){u({value:A,done:f})},d)}},Zc=function(s,o){if(Object.defineProperty)Object.defineProperty(s,"raw",{value:o});else s.raw=o;return s};var r=Object.create?function(s,o){Object.defineProperty(s,"default",{enumerable:!0,value:o})}:function(s,o){s.default=o},n=function(s){return n=Object.getOwnPropertyNames||function(o){var a=[];for(var l in o)if(Object.prototype.hasOwnProperty.call(o,l))a[a.length]=l;return a},n(s)};$c=function(s){if(s&&s.__esModule)return s;var o={};if(s!=null){for(var a=n(s),l=0;l<a.length;l++)if(a[l]!=="default")ns(o,s,a[l])}return r(o,s),o},Xc=function(s){return s&&s.__esModule?s:{default:s}},zc=function(s,o,a,l){if(a==="a"&&!l)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?s!==o||!l:!o.has(s))throw TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?l:a==="a"?l.call(s):l?l.value:o.get(s)},qc=function(s,o,a,l,c){if(l==="m")throw TypeError("Private method is not writable");if(l==="a"&&!c)throw TypeError("Private accessor was defined without a setter");if(typeof o==="function"?s!==o||!c:!o.has(s))throw TypeError("Cannot write private member to an object whose class did not declare it");return l==="a"?c.call(s,a):c?c.value=a:o.set(s,a),a},eu=function(s,o){if(o===null||typeof o!=="object"&&typeof o!=="function")throw TypeError("Cannot use 'in' operator on non-object");return typeof s==="function"?o===s:s.has(o)},tu=function(s,o,a){if(o!==null&&o!==void 0){if(typeof o!=="object"&&typeof o!=="function")throw TypeError("Object expected.");var l,c;if(a){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");l=o[Symbol.asyncDispose]}if(l===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(l=o[Symbol.dispose],a)c=l}if(typeof l!=="function")throw TypeError("Object not disposable.");if(c)l=function(){try{c.call(this)}catch(u){return Promise.reject(u)}};s.stack.push({value:o,dispose:l,async:a})}else if(a)s.stack.push({async:!0});return o};var i=typeof SuppressedError==="function"?SuppressedError:function(s,o,a){var l=Error(a);return l.name="SuppressedError",l.error=s,l.suppressed=o,l};ru=function(s){function o(u){s.error=s.hasError?new i(u,s.error,"An error was suppressed during disposal."):u,s.hasError=!0}var a,l=0;function c(){while(a=s.stack.pop())try{if(!a.async&&l===1)return l=0,s.stack.push(a),Promise.resolve().then(c);if(a.dispose){var u=a.dispose.call(a.value);if(a.async)return l|=2,Promise.resolve(u).then(c,function(d){return o(d),c()})}else l|=1}catch(d){o(d)}if(l===1)return s.hasError?Promise.reject(s.error):Promise.resolve();if(s.hasError)throw s.error}return c()},nu=function(s,o){if(typeof s==="string"&&/^\.\.?\//.test(s))return s.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(a,l,c,u,d){return l?o?".jsx":".js":c&&(!u||!d)?a:c+u+"."+d.toLowerCase()+"js"});return s},e("__extends",Tc),e("__assign",Oc),e("__rest",Bc),e("__decorate",Pc),e("__param",Dc),e("__esDecorate",Mc),e("__runInitializers",Nc),e("__propKey",Lc),e("__setFunctionName",Fc),e("__metadata",Gc),e("__awaiter",Uc),e("__generator",Hc),e("__exportStar",jc),e("__createBinding",ns),e("__values",rs),e("__read",Yo),e("__spread",Kc),e("__spreadArrays",Wc),e("__spreadArray",Yc),e("__await",en),e("__asyncGenerator",Qc),e("__asyncDelegator",Jc),e("__asyncValues",Vc),e("__makeTemplateObject",Zc),e("__importStar",$c),e("__importDefault",Xc),e("__classPrivateFieldGet",zc),e("__classPrivateFieldSet",qc),e("__classPrivateFieldIn",eu),e("__addDisposableResource",tu),e("__disposeResources",ru),e("__rewriteRelativeImportExtension",nu)})});import{CliRenderer as Gh,createCliRenderer as Uh,engine as Hh}from"@opentui/core";import{createTestRenderer as xb}from"@opentui/core/testing";import{ASCIIFontRenderable as jh,BoxRenderable as Kh,CodeRenderable as Wh,DiffRenderable as Yh,ImageRenderable as Qh,InputRenderable as Jh,LineNumberRenderable as Vh,MarkdownRenderable as Zh,ScrollBoxRenderable as $h,SelectRenderable as Xh,TabSelectRenderable as zh,TextareaRenderable as qh,TextAttributes as zs,TextNodeRenderable as ef,TextRenderable as tf}from"@opentui/core";import{engine as Ib,Timeline as kb}from"@opentui/core";var tt={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return ja(this.context.count)},getNextContextId(){return ja(this.context.count++)}};function ja(e){let t=String(e),r=t.length-1;return tt.context.id+(r?String.fromCharCode(96+r):"")+t}function Ks(e){tt.context=e}function fh(){return{...tt.context,id:tt.getNextContextId(),count:0}}var Ah=!1,gh=(e,t)=>e===t,Ws=Symbol("solid-proxy"),mh=typeof Proxy==="function",ph=Symbol("solid-track"),ib=Symbol("solid-dev-component"),yi={equals:gh},Ka=null,Va=el,yt=1,mn=2,Za={owned:null,cleanups:null,context:null,owner:null};var ce=null,D=null,bn=null,Fr=null,_e=null,He=null,st=null,vi=0;function pr(e,t){let r=_e,n=ce,i=e.length===0,s=t===void 0?n:t,o=i?Za:{owned:null,cleanups:null,context:s?s.context:null,owner:s},a=i?e:()=>e(()=>wt(()=>ar(o)));ce=o,_e=null;try{return Kt(a,!0)}finally{_e=r,ce=n}}function Y(e,t){t=t?Object.assign({},yi,t):yi;let r={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0},n=(i)=>{if(typeof i==="function")if(D&&D.running&&D.sources.has(r))i=i(r.tValue);else i=i(r.value);return qa(r,i)};return[za.bind(r),n]}function Bt(e,t,r){let n=Js(e,t,!1,yt);if(bn&&D&&D.running)He.push(n);else wn(n)}function _i(e,t,r){Va=vh;let n=Js(e,t,!1,yt),i=Ys&&yn(Ys);if(i)n.suspense=i;if(!r||!r.render)n.user=!0;st?st.push(n):wn(n)}function J(e,t,r){r=r?Object.assign({},yi,r):yi;let n=Js(e,t,!0,0);if(n.observers=null,n.observerSlots=null,n.comparator=r.equals||void 0,bn&&D&&D.running)n.tState=yt,He.push(n);else wn(n);return za.bind(n)}function wt(e){if(!Fr&&_e===null)return e();let t=_e;_e=null;try{if(Fr)return Fr.untrack(e);return e()}finally{_e=t}}function br(e){_i(()=>wt(e))}function je(e){if(ce===null);else if(ce.cleanups===null)ce.cleanups=[e];else ce.cleanups.push(e);return e}function bh(e){if(D&&D.running)return e(),D.done;let t=_e,r=ce;return Promise.resolve().then(()=>{_e=t,ce=r;let n;if(bn||Ys)n=D||(D={sources:new Set,effects:[],promises:new Set,disposed:new Set,queue:new Set,running:!0}),n.done||(n.done=new Promise((i)=>n.resolve=i)),n.running=!0;return Kt(e,!1),_e=ce=null,n?n.done:void 0})}var[sb,Wa]=Y(!1);function $a(e,t){let r=Symbol("context");return{id:r,Provider:Ch(r),defaultValue:e}}function yn(e){let t;return ce&&ce.context&&(t=ce.context[e.id])!==void 0?t:e.defaultValue}function Xa(e){let t=J(e),r=J(()=>Qs(t()));return r.toArray=()=>{let n=r();return Array.isArray(n)?n:n!=null?[n]:[]},r}var Ys;function za(){let e=D&&D.running;if(this.sources&&(e?this.tState:this.state))if((e?this.tState:this.state)===yt)wn(this);else{let t=He;He=null,Kt(()=>wi(this),!1),He=t}if(_e){let t=this.observers?this.observers.length:0;if(!_e.sources)_e.sources=[this],_e.sourceSlots=[t];else _e.sources.push(this),_e.sourceSlots.push(t);if(!this.observers)this.observers=[_e],this.observerSlots=[_e.sources.length-1];else this.observers.push(_e),this.observerSlots.push(_e.sources.length-1)}if(e&&D.sources.has(this))return this.tValue;return this.value}function qa(e,t,r){let n=D&&D.running&&D.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(n,t)){if(D){let i=D.running;if(i||!r&&D.sources.has(e))D.sources.add(e),e.tValue=t;if(!i)e.value=t}else e.value=t;if(e.observers&&e.observers.length)Kt(()=>{for(let i=0;i<e.observers.length;i+=1){let s=e.observers[i],o=D&&D.running;if(o&&D.disposed.has(s))continue;if(o?!s.tState:!s.state){if(s.pure)He.push(s);else st.push(s);if(s.observers)tl(s)}if(!o)s.state=yt;else s.tState=yt}if(He.length>1e6)throw He=[],Error()},!1)}return t}function wn(e){if(!e.fn)return;ar(e);let t=vi;if(Ya(e,D&&D.running&&D.sources.has(e)?e.tValue:e.value,t),D&&!D.running&&D.sources.has(e))queueMicrotask(()=>{Kt(()=>{D&&(D.running=!0),_e=ce=e,Ya(e,e.tValue,t),_e=ce=null},!1)})}function Ya(e,t,r){let n,i=ce,s=_e;_e=ce=e;try{n=e.fn(t)}catch(o){if(e.pure)if(D&&D.running)e.tState=yt,e.tOwned&&e.tOwned.forEach(ar),e.tOwned=void 0;else e.state=yt,e.owned&&e.owned.forEach(ar),e.owned=null;return e.updatedAt=r+1,Vs(o)}finally{_e=s,ce=i}if(!e.updatedAt||e.updatedAt<=r){if(e.updatedAt!=null&&"observers"in e)qa(e,n,!0);else if(D&&D.running&&e.pure){if(!D.sources.has(e))e.value=n;D.sources.add(e),e.tValue=n}else e.value=n;e.updatedAt=r}}function Js(e,t,r,n=yt,i){let s={fn:e,state:n,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:ce,context:ce?ce.context:null,pure:r};if(D&&D.running)s.state=0,s.tState=n;if(ce===null);else if(ce!==Za)if(D&&D.running&&ce.pure)if(!ce.tOwned)ce.tOwned=[s];else ce.tOwned.push(s);else if(!ce.owned)ce.owned=[s];else ce.owned.push(s);if(Fr&&s.fn){let o=s.fn,[a,l]=Y(void 0,{equals:!1}),c=Fr.factory(o,l);je(()=>c.dispose());let u,d=()=>bh(l).then(()=>{if(u)u.dispose(),u=void 0});s.fn=(f)=>{if(a(),D&&D.running){if(!u)u=Fr.factory(o,d);return u.track(f)}return c.track(f)}}return s}function pn(e){let t=D&&D.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===mn)return wi(e);if(e.suspense&&wt(e.suspense.inFallback))return e.suspense.effects.push(e);let r=[e];while((e=e.owner)&&(!e.updatedAt||e.updatedAt<vi)){if(t&&D.disposed.has(e))return;if(t?e.tState:e.state)r.push(e)}for(let n=r.length-1;n>=0;n--){if(e=r[n],t){let i=e,s=r[n+1];while((i=i.owner)&&i!==s)if(D.disposed.has(i))return}if((t?e.tState:e.state)===yt)wn(e);else if((t?e.tState:e.state)===mn){let i=He;He=null,Kt(()=>wi(e,r[0]),!1),He=i}}}function Kt(e,t){if(He)return e();let r=!1;if(!t)He=[];if(st)r=!0;else st=[];vi++;try{let n=e();return yh(r),n}catch(n){if(!r)st=null;He=null,Vs(n)}}function yh(e){if(He){if(bn&&D&&D.running)wh(He);else el(He);He=null}if(e)return;let t;if(D){if(!D.promises.size&&!D.queue.size){let{sources:n,disposed:i}=D;st.push.apply(st,D.effects),t=D.resolve;for(let s of st)"tState"in s&&(s.state=s.tState),delete s.tState;D=null,Kt(()=>{for(let s of i)ar(s);for(let s of n){if(s.value=s.tValue,s.owned)for(let o=0,a=s.owned.length;o<a;o++)ar(s.owned[o]);if(s.tOwned)s.owned=s.tOwned;delete s.tValue,delete s.tOwned,s.tState=0}Wa(!1)},!1)}else if(D.running){D.running=!1,D.effects.push.apply(D.effects,st),st=null,Wa(!0);return}}let r=st;if(st=null,r.length)Kt(()=>Va(r),!1);if(t)t()}function el(e){for(let t=0;t<e.length;t++)pn(e[t])}function wh(e){for(let t=0;t<e.length;t++){let r=e[t],n=D.queue;if(!n.has(r))n.add(r),bn(()=>{n.delete(r),Kt(()=>{D.running=!0,pn(r)},!1),D&&(D.running=!1)})}}function vh(e){let t,r=0;for(t=0;t<e.length;t++){let n=e[t];if(!n.user)pn(n);else e[r++]=n}if(tt.context){if(tt.count){tt.effects||(tt.effects=[]),tt.effects.push(...e.slice(0,r));return}Ks()}if(tt.effects&&(tt.done||!tt.count))e=[...tt.effects,...e],r+=tt.effects.length,delete tt.effects;for(t=0;t<r;t++)pn(e[t])}function wi(e,t){let r=D&&D.running;if(r)e.tState=0;else e.state=0;for(let n=0;n<e.sources.length;n+=1){let i=e.sources[n];if(i.sources){let s=r?i.tState:i.state;if(s===yt){if(i!==t&&(!i.updatedAt||i.updatedAt<vi))pn(i)}else if(s===mn)wi(i,t)}}}function tl(e){let t=D&&D.running;for(let r=0;r<e.observers.length;r+=1){let n=e.observers[r];if(t?!n.tState:!n.state){if(t)n.tState=mn;else n.state=mn;if(n.pure)He.push(n);else st.push(n);n.observers&&tl(n)}}}function ar(e){let t;if(e.sources)while(e.sources.length){let r=e.sources.pop(),n=e.sourceSlots.pop(),i=r.observers;if(i&&i.length){let s=i.pop(),o=r.observerSlots.pop();if(n<i.length)s.sourceSlots[o]=n,i[n]=s,r.observerSlots[n]=o}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)ar(e.tOwned[t]);delete e.tOwned}if(D&&D.running&&e.pure)rl(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)ar(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}if(D&&D.running)e.tState=0;else e.state=0}function rl(e,t){if(!t)e.tState=0,D.disposed.add(e);if(e.owned)for(let r=0;r<e.owned.length;r++)rl(e.owned[r])}function _h(e){if(e instanceof Error)return e;return Error(typeof e==="string"?e:"Unknown error",{cause:e})}function Qa(e,t,r){try{for(let n of t)n(e)}catch(n){Vs(n,r&&r.owner||null)}}function Vs(e,t=ce){let r=Ka&&t&&t.context&&t.context[Ka],n=_h(e);if(!r)throw n;if(st)st.push({fn(){Qa(n,r,t)},state:yt});else Qa(n,r,t)}function Qs(e){if(typeof e==="function"&&!e.length)return Qs(e());if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++){let n=Qs(e[r]);Array.isArray(n)?t.push.apply(t,n):t.push(n)}return t}return e}function Ch(e,t){return function(n){let i;return Bt(()=>i=wt(()=>(ce.context={...ce.context,[e]:n.value},Xa(()=>n.children))),void 0),i}}var xh=Symbol("fallback");function Ja(e){for(let t=0;t<e.length;t++)e[t]()}function Eh(e,t,r={}){let n=[],i=[],s=[],o=0,a=t.length>1?[]:null;return je(()=>Ja(s)),()=>{let l=e()||[],c=l.length,u,d;return l[ph],wt(()=>{let g,A,m,b,w,p,C,_,y;if(c===0){if(o!==0)Ja(s),s=[],n=[],i=[],o=0,a&&(a=[]);if(r.fallback)n=[xh],i[0]=pr((v)=>(s[0]=v,r.fallback())),o=1}else if(o===0){i=Array(c);for(d=0;d<c;d++)n[d]=l[d],i[d]=pr(f);o=c}else{m=Array(c),b=Array(c),a&&(w=Array(c));for(p=0,C=Math.min(o,c);p<C&&n[p]===l[p];p++);for(C=o-1,_=c-1;C>=p&&_>=p&&n[C]===l[_];C--,_--)m[_]=i[C],b[_]=s[C],a&&(w[_]=a[C]);g=new Map,A=Array(_+1);for(d=_;d>=p;d--)y=l[d],u=g.get(y),A[d]=u===void 0?-1:u,g.set(y,d);for(u=p;u<=C;u++)if(y=n[u],d=g.get(y),d!==void 0&&d!==-1)m[d]=i[u],b[d]=s[u],a&&(w[d]=a[u]),d=A[d],g.set(y,d);else s[u]();for(d=p;d<c;d++)if(d in m){if(i[d]=m[d],s[d]=b[d],a)a[d]=w[d],a[d](d)}else i[d]=pr(f);i=i.slice(0,o=c),n=l.slice(0)}return i});function f(g){if(s[d]=g,a){let[A,m]=Y(d);return a[d]=m,t(l[d],A)}return t(l[d])}}}var Sh=!1;function nl(e,t){if(Sh){if(tt.context){let r=tt.context;Ks(fh());let n=wt(()=>e(t||{}));return Ks(r),n}}return wt(()=>e(t||{}))}function bi(){return!0}var Ih={get(e,t,r){if(t===Ws)return r;return e.get(t)},has(e,t){if(t===Ws)return!0;return e.has(t)},set:bi,deleteProperty:bi,getOwnPropertyDescriptor(e,t){return{configurable:!0,enumerable:!0,get(){return e.get(t)},set:bi,deleteProperty:bi}},ownKeys(e){return e.keys()}};function js(e){return!(e=typeof e==="function"?e():e)?{}:e}function kh(){for(let e=0,t=this.length;e<t;++e){let r=this[e]();if(r!==void 0)return r}}function Ci(...e){let t=!1;for(let o=0;o<e.length;o++){let a=e[o];t=t||!!a&&Ws in a,e[o]=typeof a==="function"?(t=!0,J(a)):a}if(mh&&t)return new Proxy({get(o){for(let a=e.length-1;a>=0;a--){let l=js(e[a])[o];if(l!==void 0)return l}},has(o){for(let a=e.length-1;a>=0;a--)if(o in js(e[a]))return!0;return!1},keys(){let o=[];for(let a=0;a<e.length;a++)o.push(...Object.keys(js(e[a])));return[...new Set(o)]}},Ih);let r={},n=Object.create(null);for(let o=e.length-1;o>=0;o--){let a=e[o];if(!a)continue;let l=Object.getOwnPropertyNames(a);for(let c=l.length-1;c>=0;c--){let u=l[c];if(u==="__proto__"||u==="constructor")continue;let d=Object.getOwnPropertyDescriptor(a,u);if(!n[u])n[u]=d.get?{enumerable:!0,configurable:!0,get:kh.bind(r[u]=[d.get.bind(a)])}:d.value!==void 0?d:void 0;else{let f=r[u];if(f){if(d.get)f.push(d.get.bind(a));else if(d.value!==void 0)f.push(()=>d.value)}}}}let i={},s=Object.keys(n);for(let o=s.length-1;o>=0;o--){let a=s[o],l=n[a];if(l&&l.get)Object.defineProperty(i,a,l);else i[a]=l?l.value:void 0}return i}var Rh=(e)=>`Stale read from <${e}>.`;function vt(e){let t="fallback"in e&&{fallback:()=>e.fallback};return J(Eh(()=>e.each,e.children,t||void 0))}function Ie(e){let t=e.keyed,r=J(()=>e.when,void 0,void 0),n=t?r:J(r,void 0,{equals:(i,s)=>!i===!s});return J(()=>{let i=n();if(i){let s=e.children;return typeof s==="function"&&s.length>0?wt(()=>s(t?i:()=>{if(!wt(n))throw Rh("Show");return r()})):s}return e.fallback},void 0,void 0)}import{BaseRenderable as Cl,createTextAttributes as of,ImageRenderable as hl,InputRenderable as qs,InputRenderableEvents as _n,isTextNodeRenderable as io,isEditBufferRenderable as af,parseColor as fl,Renderable as lf,RootTextNodeRenderable as cf,ScrollBoxRenderable as uf,SelectRenderable as Al,SelectRenderableEvents as eo,TabSelectRenderable as gl,TabSelectRenderableEvents as to,TextNodeRenderable as df,TextRenderable as xl}from"@opentui/core";var Zs,Th=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),il=(Zs=String.fromCodePoint)!==null&&Zs!==void 0?Zs:(e)=>{let t="";if(e>65535)e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|e&1023;return t+=String.fromCharCode(e),t};function sl(e){var t;if(e>=55296&&e<=57343||e>1114111)return 65533;return(t=Th.get(e))!==null&&t!==void 0?t:e}function ol(e){let t=typeof atob==="function"?atob(e):typeof Buffer.from==="function"?Buffer.from(e,"base64").toString("binary"):new Buffer(e,"base64").toString("binary"),r=t.length&-2,n=new Uint16Array(r/2);for(let i=0,s=0;i<r;i+=2){let o=t.charCodeAt(i),a=t.charCodeAt(i+1);n[s++]=o|a<<8}return n}var al=ol("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAq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91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");var ot;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(ot||(ot={}));var xe;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"})(xe||(xe={}));var ll=32;function $s(e){return e>=xe.ZERO&&e<=xe.NINE}function Oh(e){return e>=xe.UPPER_A&&e<=xe.UPPER_F||e>=xe.LOWER_A&&e<=xe.LOWER_F}function Bh(e){return e>=xe.UPPER_A&&e<=xe.UPPER_Z||e>=xe.LOWER_A&&e<=xe.LOWER_Z||$s(e)}function Ph(e){return e===xe.EQUALS||Bh(e)}var Ze;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(Ze||(Ze={}));var Wt;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Wt||(Wt={}));class Xs{constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r,this.state=Ze.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=Wt.Strict,this.runConsumed=0}startEntity(e){this.decodeMode=e,this.state=Ze.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case Ze.EntityStart:{if(e.charCodeAt(t)===xe.NUM)return this.state=Ze.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=Ze.NamedEntity,this.stateNamedEntity(e,t)}case Ze.NumericStart:return this.stateNumericStart(e,t);case Ze.NumericDecimal:return this.stateNumericDecimal(e,t);case Ze.NumericHex:return this.stateNumericHex(e,t);case Ze.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|ll)===xe.LOWER_X)return this.state=Ze.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=Ze.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){while(t<e.length){let r=e.charCodeAt(t);if($s(r)||Oh(r)){let n=r<=xe.NINE?r-xe.ZERO:(r|ll)-xe.LOWER_A+10;this.result=this.result*16+n,this.consumed++,t++}else return this.emitNumericEntity(r,3)}return-1}stateNumericDecimal(e,t){while(t<e.length){let r=e.charCodeAt(t);if($s(r))this.result=this.result*10+(r-xe.ZERO),this.consumed++,t++;else return this.emitNumericEntity(r,2)}return-1}emitNumericEntity(e,t){var r;if(this.consumed<=t)return(r=this.errors)===null||r===void 0||r.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===xe.SEMI)this.consumed+=1;else if(this.decodeMode===Wt.Strict)return 0;if(this.emitCodePoint(sl(this.result),this.consumed),this.errors){if(e!==xe.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}stateNamedEntity(e,t){let{decodeTree:r}=this,n=r[this.treeIndex],i=(n&ot.VALUE_LENGTH)>>14;while(t<e.length){if(i===0&&(n&ot.FLAG13)!==0){let o=(n&ot.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let a=n&ot.JUMP_TABLE;if(e.charCodeAt(t)!==a)return this.result===0?0:this.emitNotTerminatedNamedEntity();t++,this.excess++,this.runConsumed++}while(this.runConsumed<o){if(t>=e.length)return-1;let a=this.runConsumed-1,l=r[this.treeIndex+1+(a>>1)],c=a%2===0?l&255:l>>8&255;if(e.charCodeAt(t)!==c)return this.runConsumed=0,this.result===0?0:this.emitNotTerminatedNamedEntity();t++,this.excess++,this.runConsumed++}this.runConsumed=0,this.treeIndex+=1+(o>>1),n=r[this.treeIndex],i=(n&ot.VALUE_LENGTH)>>14}if(t>=e.length)break;let s=e.charCodeAt(t);if(s===xe.SEMI&&i!==0&&(n&ot.FLAG13)!==0)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=Mh(r,n,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return this.result===0||this.decodeMode===Wt.Attribute&&(i===0||Ph(s))?0:this.emitNotTerminatedNamedEntity();if(n=r[this.treeIndex],i=(n&ot.VALUE_LENGTH)>>14,i!==0){if(s===xe.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.decodeMode!==Wt.Strict&&(n&ot.FLAG13)===0)this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0}t++,this.excess++}return-1}emitNotTerminatedNamedEntity(){var e;let{result:t,decodeTree:r}=this,n=(r[t]&ot.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,n,this.consumed),(e=this.errors)===null||e===void 0||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){let{decodeTree:n}=this;if(this.emitCodePoint(t===1?n[e]&~(ot.VALUE_LENGTH|ot.FLAG13):n[e+1],r),t===3)this.emitCodePoint(n[e+2],r);return r}end(){var e;switch(this.state){case Ze.NamedEntity:return this.result!==0&&(this.decodeMode!==Wt.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Ze.NumericDecimal:return this.emitNumericEntity(0,2);case Ze.NumericHex:return this.emitNumericEntity(0,3);case Ze.NumericStart:return(e=this.errors)===null||e===void 0||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Ze.EntityStart:return 0}}}function Dh(e){let t="",r=new Xs(e,(n)=>t+=il(n));return function(i,s){let o=0,a=0;while((a=i.indexOf("&",a))>=0){t+=i.slice(o,a),r.startEntity(s);let c=r.write(i,a+1);if(c<0){o=a+r.end();break}o=a+c,a=c===0?o+1:o}let l=t+i.slice(o);return t="",l}}function Mh(e,t,r,n){let i=(t&ot.BRANCH_LENGTH)>>7,s=t&ot.JUMP_TABLE;if(i===0)return s!==0&&n===s?r:-1;if(s){let c=n-s;return c<0||c>=i?-1:e[r+c]-1}let o=i+1>>1,a=0,l=i-1;while(a<=l){let c=a+l>>>1,u=c>>1,f=e[r+u]>>(c&1)*8&255;if(f<n)a=c+1;else if(f>n)l=c-1;else return e[r+o+c]}return-1}var Nh=Dh(al);function vn(e){return Nh(e,Wt.Strict)}var cl;(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(cl||(cl={}));var ul;(function(e){e[e.UTF8=0]="UTF8",e[e.ASCII=1]="ASCII",e[e.Extensive=2]="Extensive",e[e.Attribute=3]="Attribute",e[e.Text=4]="Text"})(ul||(ul={}));import{BaseRenderable as yf,isTextNodeRenderable as wf,TextNodeRenderable as vf,TextRenderable as _f,Yoga as El}from"@opentui/core";import{BoxRenderable as Hb,RootRenderable as jb}from"@opentui/core";import{TimeToFirstDrawRenderable as xf}from"@opentui/core";import{createSlotRegistry as Qb}from"@opentui/core";class Cn extends ef{_ctx;constructor(e,t){super(t);this._ctx=e}}class Ei extends Cn{constructor(e,t){super(null,e);if(t==="b"||t==="strong")this.attributes=(this.attributes||0)|zs.BOLD;else if(t==="i"||t==="em")this.attributes=(this.attributes||0)|zs.ITALIC;else if(t==="u")this.attributes=(this.attributes||0)|zs.UNDERLINE}}class ro extends Ei{constructor(e){super(e,"b")}}class no extends Ei{constructor(e){super(e,"i")}}class yl extends Ei{constructor(e){super(e,"u")}}class wl extends Cn{constructor(e,t){super(null,t);this.add()}add(){return super.add(`
7
+ `)}}class vl extends Cn{constructor(e,t){let r={...t,link:{url:t.href}};super(null,r)}}var rf={box:Kh,text:tf,input:Jh,select:Xh,textarea:qh,ascii_font:jh,tab_select:zh,scrollbox:$h,code:Wh,diff:Yh,line_number:Vh,markdown:Zh,image:Qh,span:Cn,strong:ro,b:ro,em:no,i:no,u:yl,br:wl,a:vl},_l={...rf};function Yt(e){Object.assign(_l,e)}function nf(){return _l}var lo=$a(),gt=()=>{let e=yn(lo);if(!e)throw Error("No renderer found");return e},sf=(e)=>{let t=gt();br(()=>{t.on("resize",e)}),je(()=>{t.off("resize",e)})},Hr=()=>{let e=gt(),[t,r]=Y({width:e.width,height:e.height});return sf((i,s)=>{r({width:i,height:s})}),t},jr=(e,t)=>{let n=gt().keyInput;br(()=>{if(n.on("keypress",e),t?.release)n.on("keyrelease",e)}),je(()=>{if(n.off("keypress",e),t?.release)n.off("keyrelease",e)})};var hf=(e)=>J(()=>e());function ff({createElement:e,createTextNode:t,createDynamicTextNode:r,createSlotNode:n,isTextNode:i,replaceText:s,insertNode:o,removeNode:a,setProperty:l,getParentNode:c,getFirstChild:u,getNextSibling:d}){function f(_,y,v,x){if(v!==void 0&&!x)x=[];if(typeof y!=="function")return g(_,y,x,v);Bt((B)=>g(_,y(),B,v),x)}function g(_,y,v,x,B){while(typeof v==="function")v=v();if(y===v)return v;let M=typeof y,P=x!==void 0;if(M==="string"||M==="number"){if(M==="number")y=y.toString();if(P){let O=v[0];if(O&&i(O))s(O,y);else O=r(y);v=b(_,v,x,O)}else if(v!==""&&typeof v==="string")s(u(_),v=y);else b(_,v,x,r(y)),v=y}else if(y==null||M==="boolean")v=b(_,v,x);else if(M==="function")return Bt(()=>{let O=y();while(typeof O==="function")O=O();v=g(_,O,v,x)}),()=>v;else if(Array.isArray(y)){let O=[];if(A(O,y,B))return Bt(()=>v=g(_,O,v,x,!0)),()=>v;if(O.length===0){let W=b(_,v,x);if(P)return v=W}else if(Array.isArray(v))if(v.length===0)w(_,O,x);else m(_,v,O);else if(v==null||v==="")w(_,O);else m(_,P&&v||[u(_)],O);v=O}else{if(Array.isArray(v)){if(P)return v=b(_,v,x,y);b(_,v,null,y)}else if(v==null||v===""||!u(_))o(_,y);else p(_,y,u(_));v=y}return v}function A(_,y,v){let x=!1;for(let B=0,M=y.length;B<M;B++){let P=y[B],O;if(P==null||P===!0||P===!1);else if(Array.isArray(P))x=A(_,P)||x;else if((O=typeof P)==="string"||O==="number")_.push(r(P));else if(O==="function")if(v){while(typeof P==="function")P=P();x=A(_,Array.isArray(P)?P:[P])||x}else _.push(P),x=!0;else _.push(P)}return x}function m(_,y,v){let x=v.length,B=y.length,M=x,P=0,O=0,W=d(y[B-1]),Q=null;while(P<B||O<M){if(y[P]===v[O]){P++,O++;continue}while(y[B-1]===v[M-1])B--,M--;if(B===P){let j=M<x?O?d(v[O-1]):v[M-O]:W;while(O<M)o(_,v[O++],j)}else if(M===O)while(P<B){if(!Q||!Q.has(y[P]))a(_,y[P]);P++}else if(y[P]===v[M-1]&&v[O]===y[B-1]){let j=d(y[--B]);o(_,v[O++],d(y[P++])),o(_,v[--M],j),y[B]=v[M]}else{if(!Q){Q=new Map;let ee=O;while(ee<M)Q.set(v[ee],ee++)}let j=Q.get(y[P]);if(j!=null)if(O<j&&j<M){let ee=P,ie=1,z;while(++ee<B&&ee<M){if((z=Q.get(y[ee]))==null||z!==j+ie)break;ie++}if(ie>j-O){let Be=y[P];while(O<j)o(_,v[O++],Be)}else p(_,v[O++],y[P++])}else P++;else a(_,y[P++])}}}function b(_,y,v,x){if(v===void 0){let M;while(M=u(_))a(_,M);return x&&o(_,x),x??""}let B=x||n();if(y.length){let M=!1;for(let P=y.length-1;P>=0;P--){let O=y[P];if(B!==O){let W=c(O)===_;if(!M&&!P)W?p(_,B,O):o(_,B,v);else W&&a(_,O)}else M=!0}}else o(_,B,v);return[B]}function w(_,y,v){for(let x=0,B=y.length;x<B;x++)o(_,y[x],v)}function p(_,y,v){o(_,y,v),a(_,v)}function C(_,y,v={},x){if(y||(y={}),!x)Bt(()=>v.children=g(_,y.children,v.children));return Bt(()=>y.ref&&y.ref(_)),Bt(()=>{for(let B in y){if(B==="children"||B==="ref")continue;let M=y[B];if(M===v[B])continue;l(_,B,M,v[B]),v[B]=M}}),v}return{render(_,y){let v;return pr((x)=>{v=x,f(y,_())}),v},insert:f,spread(_,y,v){if(typeof y==="function")Bt((x)=>C(_,y(),x,v));else C(_,y,void 0,v)},createElement:e,createTextNode:t,insertNode:o,setProp(_,y,v,x){return l(_,y,v,x),v},mergeProps:Ci,effect:Bt,memo:hf,createComponent:nl,use(_,y,v){return wt(()=>_(y,v))}}}function Af(e){let t=ff(e);return t.mergeProps=Ci,t}var xi=new Map;function co(e){if(!xi.has(e))xi.set(e,0);let t=xi.get(e)+1;return xi.set(e,t),`${e}-${t}`}var $e=(...e)=>{if(process.env.DEBUG)console.log("[Reconciler]",...e)};class Gr extends df{static fromString(e,t={}){let r=new Gr(t);return r.add(e),r}}var Ke=(e)=>{if(!e)return;return e.id},so=(e)=>{let t;if(e instanceof xl)t=e.getTextChildren();else t=e.getChildren();return t};function gf(e,t,r){if($e("Inserting node:",Ke(t),"into parent:",Ke(e),"with anchor:",Ke(r),t instanceof Gr),t instanceof Ur)t.parent=e,t=t.getSlotChild(e);if(r&&r instanceof Ur)r=r.getSlotChild(e);if(io(t)){if(!(e instanceof xl)&&!io(e))throw Error(`Orphan text error: "${t.toChunks().map((s)=>s.text).join("")}" must have a <text> as a parent: ${e.id} above ${t.id}`)}if(!(e instanceof Cl))throw console.error("[INSERT]","Tried to mount a non base renderable"),Error("Tried to mount a non base renderable");if(!r){e.add(t);return}let n=so(e),i=n.indexOf(r);if(i===-1)$e("[INSERT]","Could not find anchor",Ke(e),Ke(r),"[children]",...n.map((s)=>s.id));e.add(t,i)}function mf(e,t){$e("Removing node:",Ke(t),"from parent:",Ke(e));let r;if(t instanceof Ur){r=t;let n=r.getSlotChildForRemoval(e);if(!n){if(r.parent===e)r.parent=null;return}t=n}e.remove(t),r?.didRemoveSlotChild(e,t),process.nextTick(()=>{if(t instanceof Cl&&!t.parent){t.destroyRecursively();return}})}function ml(e,t){$e("Creating text node:",e);let r=co("text-node");if(typeof e==="number")e=e.toString();return Gr.fromString(t?vn(e):e,{id:r})}function pf(){let e=co("slot-node");return $e("Creating slot node",e),new Ur(e)}function pl(e){$e("Getting parent of node:",Ke(e));let t=e.parent??void 0;if(t instanceof cf)t=t.textParent??void 0;let r=t?.parent?.parent?.parent;if(r instanceof uf&&r.content===t)t=r;return t}var{render:bf,effect:he,memo:ut,createComponent:Z,createElement:I,createTextNode:Ee,insertNode:T,insert:L,spread:Nb,setProp:h,mergeProps:Lb,use:Fb}=Af({createElement(e){$e("Creating element:",e);let t=co(e),r=yn(lo);if(!r)throw Error("No renderer found");let n=nf();if(!n[e])throw Error(`[Reconciler] Unknown component type: ${e}`);let i=new n[e](r,{id:t});if(i instanceof hl)je(()=>{i.source=void 0});return $e("Element created with id:",t),i},createTextNode:(e)=>ml(e,!0),createDynamicTextNode:(e)=>ml(e,!1),createSlotNode:pf,replaceText(e,t){if($e("Replacing text:",t,"in node:",Ke(e)),!(e instanceof Gr))return;e.replace(t,0)},setProperty(e,t,r,n){if(t.startsWith("on:")){let i=t.slice(3);if(r)e.on(i,r);if(n)e.off(i,n);return}if(io(e)){if(t==="href"){e.link={url:r};return}if(t==="style"){e.attributes|=of(r),e.fg=r.fg?fl(r.fg):e.fg,e.bg=r.bg?fl(r.bg):e.bg;return}return}switch(t){case"id":$e("Id mapped",e.id,"=",r),e[t]=r;break;case"focused":if(!(e instanceof lf))return;if(r)e.focus();else e.blur();break;case"onChange":let i=void 0;if(e instanceof Al)i=eo.SELECTION_CHANGED;else if(e instanceof gl)i=to.SELECTION_CHANGED;else if(e instanceof qs)i=_n.CHANGE;if(!i)break;if(r)e.on(i,r);if(n)e.off(i,n);break;case"onInput":if(e instanceof qs){if(r)e.on(_n.INPUT,r);if(n)e.off(_n.INPUT,n)}break;case"onSubmit":if(e instanceof qs){if(r)e.on(_n.ENTER,r);if(n)e.off(_n.ENTER,n)}else e[t]=r;break;case"onSelect":if(e instanceof Al){if(r)e.on(eo.ITEM_SELECTED,r);if(n)e.off(eo.ITEM_SELECTED,n)}else if(e instanceof gl){if(r)e.on(to.ITEM_SELECTED,r);if(n)e.off(to.ITEM_SELECTED,n)}break;case"style":let s=r??{},o=n??{};if(af(e)&&o.selectionOccupancy&&!s.selectionOccupancy)e.selectionOccupancy=void 0;if(e instanceof hl)for(let a in o){if(Object.prototype.hasOwnProperty.call(s,a))continue;if(a!=="fit"&&a!=="protocol")continue;e[a]=void 0}for(let a in s){let l=s[a];if(l===o[a])continue;e[a]=l}break;case"text":case"content":{let a=typeof r==="string"?r:Array.isArray(r)?r.join(""):`${r}`;e[t]=a;break}default:e[t]=r}},isTextNode(e){return e instanceof Gr},insertNode:gf,removeNode:mf,getParentNode:pl,getFirstChild(e){$e("Getting first child of node:",Ke(e));let t=so(e)[0];if(!t){$e("No first child found for node:",Ke(e));return}return $e("First child found:",Ke(t),"for node:",Ke(e)),t},getNextSibling(e){$e("Getting next sibling of node:",Ke(e));let t=pl(e);if(!t){$e("No parent found for node:",Ke(e));return}if(e instanceof Ur){let s=e.getSlotChildForRemoval(t);if(s)e=s}let r=so(t),n=r.indexOf(e);if(n===-1||n===r.length-1){$e("No next sibling found for node:",Ke(e));return}let i=r[n+1];if(!i){$e("Next sibling is null for node:",Ke(e));return}return $e("Next sibling found:",Ke(i),"for node:",Ke(e)),i}});function bl(e){return e?.getLayoutNode?.()?.constructor}function Cf(e){return e?.create?.()??El.default.Node.create()}class uo extends yf{constructor(e){super({id:e})}add(e,t){throw Error("Can't add children on an Slot renderable")}getChildren(){return[]}remove(e){}insertBefore(e,t){throw Error("Can't add children on an Slot renderable")}getRenderable(e){return}getChildrenCount(){return 0}requestRender(){}findDescendantById(e){return}}class oo extends vf{slotParent;destroyed=!1;constructor(e,t){super({id:e});this._visible=!1,this.slotParent=t}detachFromSlot(){this.slotParent=void 0}disposeWithoutSlotCascade(){if(this.destroyed)return;this.destroyed=!0,this.detachFromSlot()}destroy(){if(this.destroyed)return;this.destroyed=!0;let e=this.slotParent;this.slotParent=void 0,e?.destroy(),super.destroy()}}class ao extends uo{yogaNode;slotParent;destroyed=!1;yogaNodeConstructor;yogaNodeFreed=!1;constructor(e,t,r){super(e);this._visible=!1,this.slotParent=t,this.yogaNodeConstructor=bl(r),this.yogaNode=Cf(this.yogaNodeConstructor),this.yogaNode.setDisplay(El.Display.None)}getLayoutNode(){return this.yogaNode}updateFromLayout(){}updateLayout(){}onRemove(){}isCompatibleWith(e){return this.yogaNodeConstructor===bl(e)}detachFromSlot(){this.slotParent=void 0}freeYogaNode(){if(this.yogaNodeFreed)return;this.yogaNodeFreed=!0;try{this.yogaNode.free()}catch{}}disposeWithoutSlotCascade(){if(this.destroyed)return;this.destroyed=!0,this.detachFromSlot(),this.freeYogaNode()}destroy(){if(this.destroyed)return;this.destroyed=!0;let e=this.slotParent;this.slotParent=void 0,this.freeYogaNode(),e?.destroy()}}class Ur extends uo{destroyed=!1;layoutNodesByParent=new Map;textNodesByParent=new Map;layoutNodeCount=0;textNodeCount=0;constructor(e){super(e);this._visible=!1}get layoutNode(){return this.getCurrentSlotChild(this.layoutNodesByParent)}get textNode(){return this.getCurrentSlotChild(this.textNodesByParent)}isTextSlotParent(e){return wf(e)||e instanceof _f}getCurrentSlotChild(e){for(let t of e.values())if(t.parent)return t;return e.values().next().value}getTextNodeForParent(e){let t=this.textNodesByParent.get(e);if(t)return t;for(let[r,n]of this.textNodesByParent){if(n.parent!==e)continue;return this.textNodesByParent.delete(r),this.textNodesByParent.set(e,n),n}}getLayoutNodeForParent(e){let t=this.layoutNodesByParent.get(e);if(t)return t;for(let[r,n]of this.layoutNodesByParent){if(n.parent!==e)continue;return this.layoutNodesByParent.delete(r),this.layoutNodesByParent.set(e,n),n}}takeReusableTextNode(e){for(let[t,r]of this.textNodesByParent){if(r.parent)continue;return this.textNodesByParent.delete(t),this.textNodesByParent.set(e,r),r}}takeReusableLayoutNode(e){for(let[t,r]of this.layoutNodesByParent){if(r.parent)continue;if(!r.isCompatibleWith(e))continue;return this.layoutNodesByParent.delete(t),this.layoutNodesByParent.set(e,r),r}}disposeDetachedTextNodes(){for(let[e,t]of this.textNodesByParent){if(t.parent)continue;this.textNodesByParent.delete(e),t.disposeWithoutSlotCascade()}}disposeDetachedIncompatibleLayoutNodes(e){for(let[t,r]of this.layoutNodesByParent){if(r.parent||r.isCompatibleWith(e))continue;this.layoutNodesByParent.delete(t),r.disposeWithoutSlotCascade()}}getAttachedSlotParent(e){for(let t of this.textNodesByParent.values())if(t!==e&&t.parent)return t.parent;for(let t of this.layoutNodesByParent.values())if(t!==e&&t.parent)return t.parent;return null}hasOtherAttachedSlotChildren(e){return this.getAttachedSlotParent(e)!==null}getSlotChild(e){if(this.isTextSlotParent(e)){let i=this.getTextNodeForParent(e);if(i)return i;let s=this.takeReusableTextNode(e);if(s)return s;this.disposeDetachedIncompatibleLayoutNodes(e);let o=new oo(`slot-text-${this.id}-${++this.textNodeCount}`,this);return this.textNodesByParent.set(e,o),o}let t=this.getLayoutNodeForParent(e);if(t)return t;let r=this.takeReusableLayoutNode(e);if(r)return r;this.disposeDetachedTextNodes(),this.disposeDetachedIncompatibleLayoutNodes(e);let n=new ao(`slot-layout-${this.id}-${++this.layoutNodeCount}`,this,e);return this.layoutNodesByParent.set(e,n),n}getSlotChildForRemoval(e){if(this.isTextSlotParent(e))return this.getTextNodeForParent(e);return this.getLayoutNodeForParent(e)}didRemoveSlotChild(e,t){let r=this.hasOtherAttachedSlotChildren(t);if(r&&t instanceof oo&&this.getTextNodeForParent(e)===t)this.textNodesByParent.delete(e),t.disposeWithoutSlotCascade();if(r&&t instanceof ao&&this.getLayoutNodeForParent(e)===t)this.layoutNodesByParent.delete(e),t.disposeWithoutSlotCascade();if(this.parent===e)this.parent=this.getAttachedSlotParent(t)}destroy(){if(this.destroyed)return;this.destroyed=!0;let e=new Set(this.layoutNodesByParent.values());this.layoutNodesByParent.clear();for(let r of e)r.destroy();let t=new Set(this.textNodesByParent.values());this.textNodesByParent.clear();for(let r of t)r.destroy()}}Yt({time_to_first_draw:xf});var Ef=(e,t)=>{let r,n=!1,i=!1,s=!0,o=!1,a=e.destroy.bind(e),l=()=>{if(i)return;if(!r){n=!0;return}i=!0,r()};e.once("destroy",l),e.destroy=()=>{if(s){o=!0;return}a()};try{r=bf(()=>Z(lo.Provider,{get value(){return e},get children(){return Z(t,{})}}),e.root)}finally{s=!1,e.destroy=a}if(n)l();if(o)a()},Si=async(e,t={})=>{let r=t instanceof Gh?t:await Uh({...t,onDestroy:()=>{t.onDestroy?.()}});Hh.attach(r),Ef(r,e)};var Sl={tier0:32,tier1:64,tier2:64};import{basename as ym,dirname as ts}from"path";var lr=1,Ii=8;function We(e){if(typeof e!=="number"||!Number.isFinite(e))return 1;return Math.max(1,Math.min(8,Math.round(e)))}function xn(e,t){let r=We(e);return{primary:r,mirrored:t?r-1:0}}var ho=64;var zb=ho*ho;var ey=new RegExp(["asshole","bastard","bitch","bullshit","cunt","dildo","faggot","fuck","goddamn","jackass","jerkoff","kike","nigga","nigger","penis","porn","prick","pussy","retard","scumbag","shit","slut","tits","twat","vagina","whore","wanker"].join("|"));var fo={version:1,linkedRoles:{leftLegFoot:"leftLeg",rightLegFoot:"rightLeg",leftArmFoot:"leftArm",rightArmFoot:"rightArm",leftSleeve:"leftArm",rightSleeve:"rightArm"},clips:{idle:{duration:2.4,loop:!0,model:{positionY:[[0,0.004],[0.25,0.008],[0.5,0.004],[0.75,0],[1,0.004]]},roles:{leftArm:{positionZ:[[0,0],[0.25,0.006],[0.5,0],[0.75,-0.006],[1,0]]},rightArm:{positionZ:[[0,0],[0.25,-0.006],[0.5,0],[0.75,0.006],[1,0]]}}},walk:{duration:0.9,loop:!0,model:{positionY:[[0,0.015],[0.25,0.06],[0.5,0.015],[0.75,0.06],[1,0.015]]},roles:{leftLeg:{positionZ:[[0,0],[0.25,0.055],[0.5,0],[0.75,-0.055],[1,0]]},rightLeg:{positionZ:[[0,0],[0.25,-0.055],[0.5,0],[0.75,0.055],[1,0]]},leftArm:{positionZ:[[0,0],[0.25,-0.055],[0.5,0],[0.75,0.055],[1,0]]},rightArm:{positionZ:[[0,0],[0.25,0.055],[0.5,0],[0.75,-0.055],[1,0]]}}},jump:{duration:0.78,loop:!1,model:{positionY:[[0,0],[0.76,0],[0.9,-0.055],[0.98,0],[1,0]],rotationX:[[0,0],[0.2,0.04],[0.58,0.14],[0.82,0.09],[1,0]]},roles:{leftLeg:{positionY:[[0,0],[0.18,-0.008],[0.48,0.035],[0.72,0.026],[0.88,-0.006],[1,0]]},rightLeg:{positionY:[[0,0],[0.18,-0.007],[0.48,0.032],[0.72,0.024],[0.88,-0.007],[1,0]]},leftArm:{positionZ:[[0,0],[0.25,-0.025],[0.58,0.05],[0.82,0.02],[1,0]],rotationX:[[0,0],[0.25,-0.3],[0.58,0.55],[0.82,0.25],[1,0]],rotationZ:[[0,0],[0.25,0.06],[0.58,0.09],[0.82,0.035],[1,0]]},rightArm:{positionZ:[[0,0],[0.25,0.03],[0.58,-0.045],[0.82,-0.018],[1,0]],rotationX:[[0,0],[0.25,0.35],[0.58,-0.5],[0.82,-0.22],[1,0]],rotationZ:[[0,0],[0.25,-0.07],[0.58,-0.08],[0.82,-0.035],[1,0]]}}},frontFlip:{duration:0.8,loop:!1,model:{rotationX:[[0,0],[0.08,0.25],[0.2,1.15],[0.35,2.35],[0.5,3.1416],[0.65,3.93],[0.8,5.13],[0.92,6.03],[1,6.2832]],positionY:[[0,0],[0.08,0.017],[0.2,0.326],[0.35,0.937],[0.5,1.1],[0.65,0.935],[0.8,0.327],[0.92,0.017],[1,0]],positionZ:[[0,0],[0.08,-0.136],[0.2,-0.502],[0.35,-0.391],[0.5,0],[0.65,0.393],[0.8,0.503],[0.92,0.138],[1,0]]},roles:{leftArm:{rotationX:[[0,0],[0.15,-1.25],[0.5,0.85],[0.85,0.25],[1,0]]},rightArm:{rotationX:[[0,0],[0.15,-1.15],[0.5,0.8],[0.85,0.22],[1,0]]},leftLeg:{positionY:[[0,0],[0.3,0.05],[0.55,0.075],[0.85,0.01],[1,0]]},rightLeg:{positionY:[[0,0],[0.3,0.048],[0.55,0.07],[0.85,0.012],[1,0]]}}},run:{duration:0.55,loop:!0,model:{positionY:[[0,0.02],[0.25,0.085],[0.5,0.02],[0.75,0.085],[1,0.02]]},roles:{leftLeg:{positionY:[[0,0],[0.25,0.035],[0.5,0],[0.75,0],[1,0]],positionZ:[[0,0],[0.25,0.085],[0.5,0],[0.75,-0.085],[1,0]],rotationX:[[0,0],[0.25,-0.34],[0.5,0],[0.75,0.34],[1,0]]},rightLeg:{positionY:[[0,0],[0.25,0],[0.5,0],[0.75,0.035],[1,0]],positionZ:[[0,0],[0.25,-0.085],[0.5,0],[0.75,0.085],[1,0]],rotationX:[[0,0],[0.25,0.34],[0.5,0],[0.75,-0.34],[1,0]]},leftArm:{positionY:[[0,0],[0.25,0],[0.5,0],[0.75,0.03],[1,0]],positionZ:[[0,0],[0.25,-0.072],[0.5,0],[0.75,0.072],[1,0]],rotationX:[[0,0],[0.25,0.3],[0.5,0],[0.75,-0.3],[1,0]]},rightArm:{positionY:[[0,0],[0.25,0.03],[0.5,0],[0.75,0],[1,0]],positionZ:[[0,0],[0.25,0.072],[0.5,0],[0.75,-0.072],[1,0]],rotationX:[[0,0],[0.25,-0.3],[0.5,0],[0.75,0.3],[1,0]]}}},swim:{duration:1.2,loop:!0,model:{positionY:[[0,0.018],[0.25,0.04],[0.5,0.018],[0.75,0],[1,0.018]],rotationX:[[0,0.1],[0.25,0.14],[0.5,0.1],[0.75,0.06],[1,0.1]]},roles:{leftArm:{positionY:[[0,0.045],[0.25,0.02],[0.5,0],[0.75,0.018],[1,0.045]],positionZ:[[0,0],[0.25,-0.055],[0.5,0],[0.75,0.04],[1,0]],rotationX:[[0,-0.9],[0.25,-0.15],[0.5,0.75],[0.75,0.15],[1,-0.9]],rotationZ:[[0,0.18],[0.25,0.34],[0.5,0.18],[0.75,0.08],[1,0.18]]},rightArm:{positionY:[[0,0],[0.25,0.018],[0.5,0.045],[0.75,0.02],[1,0]],positionZ:[[0,0],[0.25,0.04],[0.5,0],[0.75,-0.055],[1,0]],rotationX:[[0,0.75],[0.25,0.15],[0.5,-0.9],[0.75,-0.15],[1,0.75]],rotationZ:[[0,-0.18],[0.25,-0.08],[0.5,-0.18],[0.75,-0.34],[1,-0.18]]},leftLeg:{positionY:[[0,0.018],[0.25,0.035],[0.5,0],[0.75,0.012],[1,0.018]],positionZ:[[0,-0.045],[0.25,0],[0.5,0.045],[0.75,0],[1,-0.045]],rotationX:[[0,0.24],[0.25,0],[0.5,-0.24],[0.75,0],[1,0.24]]},rightLeg:{positionY:[[0,0],[0.25,0.012],[0.5,0.018],[0.75,0.035],[1,0]],positionZ:[[0,0.045],[0.25,0],[0.5,-0.045],[0.75,0],[1,0.045]],rotationX:[[0,-0.24],[0.25,0],[0.5,0.24],[0.75,0],[1,-0.24]]}}},horseWalk:{duration:0.9,loop:!0,model:{positionY:[[0,0.008],[0.125,0.016],[0.25,0.008],[0.375,0.016],[0.5,0.008],[0.625,0.016],[0.75,0.008],[0.875,0.016],[1,0.008]],rotationX:[[0,0],[0.125,0.012],[0.25,0],[0.375,-0.012],[0.5,0],[0.625,0.012],[0.75,0],[0.875,-0.012],[1,0]]},roles:{leftLeg:{positionY:[[0,0],[0.125,0],[0.25,0],[0.375,0],[0.5,0],[0.625,0.025],[0.75,0.055],[0.875,0.035],[1,0]],positionZ:[[0,0.025],[0.125,0.012],[0.25,-0.008],[0.375,-0.022],[0.5,-0.03],[0.625,-0.012],[0.75,0.012],[0.875,0.025],[1,0.025]],rotationX:[[0,-0.3],[0.125,-0.16],[0.25,0.03],[0.375,0.2],[0.5,0.28],[0.625,0.12],[0.75,-0.1],[0.875,-0.26],[1,-0.3]]},leftArm:{positionY:[[0,0.055],[0.125,0.035],[0.25,0],[0.375,0],[0.5,0],[0.625,0],[0.75,0],[0.875,0.025],[1,0.055]],positionZ:[[0,0.012],[0.125,0.025],[0.25,0.025],[0.375,0.012],[0.5,-0.008],[0.625,-0.022],[0.75,-0.03],[0.875,-0.012],[1,0.012]],rotationX:[[0,-0.1],[0.125,-0.26],[0.25,-0.3],[0.375,-0.16],[0.5,0.03],[0.625,0.2],[0.75,0.28],[0.875,0.12],[1,-0.1]]},rightLeg:{positionY:[[0,0],[0.125,0.025],[0.25,0.055],[0.375,0.035],[0.5,0],[0.625,0],[0.75,0],[0.875,0],[1,0]],positionZ:[[0,-0.03],[0.125,-0.012],[0.25,0.012],[0.375,0.025],[0.5,0.025],[0.625,0.012],[0.75,-0.008],[0.875,-0.022],[1,-0.03]],rotationX:[[0,0.28],[0.125,0.12],[0.25,-0.1],[0.375,-0.26],[0.5,-0.3],[0.625,-0.16],[0.75,0.03],[0.875,0.2],[1,0.28]]},rightArm:{positionY:[[0,0],[0.125,0],[0.25,0],[0.375,0.025],[0.5,0.055],[0.625,0.035],[0.75,0],[0.875,0],[1,0]],positionZ:[[0,-0.008],[0.125,-0.022],[0.25,-0.03],[0.375,-0.012],[0.5,0.012],[0.625,0.025],[0.75,0.025],[0.875,0.012],[1,-0.008]],rotationX:[[0,0.03],[0.125,0.2],[0.25,0.28],[0.375,0.12],[0.5,-0.1],[0.625,-0.26],[0.75,-0.3],[0.875,-0.16],[1,0.03]]}}},horseRun:{duration:0.55,loop:!0,model:{positionY:[[0,0.087361],[0.125,0.094508],[0.25,0.078511],[0.375,0.048743],[0.5,0.022639],[0.625,0.015492],[0.75,0.031489],[0.875,0.061257],[1,0.087361]],rotationX:[[0,0.013907],[0.125,-0.038677],[0.25,-0.068605],[0.375,-0.058344],[0.5,-0.013907],[0.625,0.038677],[0.75,0.068605],[0.875,0.058344],[1,0.013907]]},roles:{leftArm:{positionY:[[0,0],[0.125,0.060104],[0.25,0.085],[0.375,0.060104],[0.5,0],[0.625,0],[0.75,0],[0.875,0],[1,0]],positionZ:[[0,0],[0.125,0.120208],[0.25,0.17],[0.375,0.120208],[0.5,0],[0.625,-0.120208],[0.75,-0.17],[0.875,-0.120208],[1,0]],rotationX:[[0,0],[0.125,-0.240416],[0.25,-0.34],[0.375,-0.240416],[0.5,0],[0.625,0.240416],[0.75,0.34],[0.875,0.240416],[1,0]]},rightArm:{positionY:[[0,0],[0.125,0.027977],[0.25,0.076538],[0.375,0.080264],[0.5,0.036972],[0.625,0],[0.75,0],[0.875,0],[1,0]],positionZ:[[0,-0.073944],[0.125,0.055955],[0.25,0.153076],[0.375,0.160527],[0.5,0.073944],[0.625,-0.055955],[0.75,-0.153076],[0.875,-0.160527],[1,-0.073944]],rotationX:[[0,0.147888],[0.125,-0.111909],[0.25,-0.306152],[0.375,-0.321055],[0.5,-0.147888],[0.625,0.111909],[0.75,0.306152],[0.875,0.321055],[1,0.147888]]},leftLeg:{positionY:[[0,0.033275],[0.125,0],[0.25,0],[0.375,0],[0.5,0],[0.625,0.02518],[0.75,0.068884],[0.875,0.072237],[1,0.033275]],positionZ:[[0,0.077641],[0.125,-0.058752],[0.25,-0.16073],[0.375,-0.168554],[0.5,-0.077641],[0.625,0.058752],[0.75,0.16073],[0.875,0.168554],[1,0.077641]],rotationX:[[0,-0.125705],[0.125,0.095123],[0.25,0.260229],[0.375,0.272897],[0.5,0.125705],[0.625,-0.095123],[0.75,-0.260229],[0.875,-0.272897],[1,-0.125705]]},rightLeg:{positionY:[[0,0],[0.125,0],[0.25,0],[0.375,0],[0.5,0],[0.625,0.054094],[0.75,0.0765],[0.875,0.054094],[1,0]],positionZ:[[0,0],[0.125,-0.126219],[0.25,-0.1785],[0.375,-0.126219],[0.5,0],[0.625,0.126219],[0.75,0.1785],[0.875,0.126219],[1,0]],rotationX:[[0,0],[0.125,0.204354],[0.25,0.289],[0.375,0.204354],[0.5,0],[0.625,-0.204354],[0.75,-0.289],[0.875,-0.204354],[1,0]]}}},wave:{duration:2,loop:!1,model:{positionY:[[0,0],[1,0]]},roles:{leftArm:{positionY:[[0,0],[0.5,-0.08],[1,0]],rotationX:[[0,0],[0.5,-1.5],[1,0]]}}},look:{duration:4.9,loop:!1,model:{rotationY:[[0,0],[0.125,0.07],[0.25,0],[0.375,-0.16],[0.5,0],[0.625,0.16],[0.75,0],[0.875,-0.07],[1,0]]},roles:{leftArm:{positionZ:[[0,0],[0.125,0.012],[0.25,0],[0.375,-0.025],[0.5,0],[0.625,0.025],[0.75,0],[0.875,-0.012],[1,0]]},rightArm:{positionZ:[[0,0],[0.125,-0.012],[0.25,0],[0.375,0.025],[0.5,0],[0.625,-0.025],[0.75,0],[0.875,0.012],[1,0]]}}},sit:{duration:6.2,loop:!1,model:{positionY:[[0,0],[0.25,-0.042426],[0.5,-0.06],[0.75,-0.042426],[1,0]]},roles:{leftLeg:{positionY:[[0,0],[0.25,-0.024749],[0.5,-0.035],[0.75,-0.024749],[1,0]],positionZ:[[0,0],[0.25,0.070711],[0.5,0.1],[0.75,0.070711],[1,0]]},rightLeg:{positionY:[[0,0],[0.25,-0.024749],[0.5,-0.035],[0.75,-0.024749],[1,0]],positionZ:[[0,0],[0.25,0.070711],[0.5,0.1],[0.75,0.070711],[1,0]]},leftArm:{positionZ:[[0,0],[0.25,-0.021213],[0.5,-0.03],[0.75,-0.021213],[1,0]]},rightArm:{positionZ:[[0,0],[0.25,-0.021213],[0.5,-0.03],[0.75,-0.021213],[1,0]]}}}}};var If=["positionX","positionY","positionZ","rotationX","rotationY","rotationZ","scaleX","scaleY","scaleZ"];var kf=new Set(If);function Kr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Il(e,t){if(!Kr(e))return[`${t} must be an object`];let r=[];for(let[n,i]of Object.entries(e)){if(!kf.has(n)){r.push(`${t} uses unknown property ${n}`);continue}if(!Array.isArray(i)||i.length<2){r.push(`${t}.${n} must contain at least two keyframes`);continue}let s=-1;for(let[o,a]of i.entries()){if(!Array.isArray(a)||a.length!==2||!a.every((c)=>typeof c==="number"&&Number.isFinite(c))){r.push(`${t}.${n}[${o}] is invalid`);continue}let l=a[0];if(l<0||l>1||l<=s)r.push(`${t}.${n} keyframe times must increase from 0 to 1`);s=l}if(i[0]?.[0]!==0||i.at(-1)?.[0]!==1)r.push(`${t}.${n} must start at 0 and end at 1`)}return r}function Rl(e){if(!Kr(e))return["Animation catalog must be an object"];let t=[];if(e.version!==1)t.push("Animation catalog version must be 1");if(!Kr(e.linkedRoles))t.push("Animation catalog linkedRoles must be an object");else if(Object.values(e.linkedRoles).some((r)=>typeof r!=="string"))t.push("Animation catalog linked roles must target role names");if(!Kr(e.clips))return t.push("Animation catalog clips must be an object"),t;for(let[r,n]of Object.entries(e.clips)){let i=`Clip ${r}`;if(!Kr(n)){t.push(`${i} must be an object`);continue}if(typeof n.duration!=="number"||!Number.isFinite(n.duration)||n.duration<=0)t.push(`${i} must have a positive duration`);if(typeof n.loop!=="boolean")t.push(`${i} must declare whether it loops`);if(n.model===void 0)t.push(`${i} must include a model animation track`);else t.push(...Il(n.model,`${i}.model`));if(n.roles!==void 0)if(!Kr(n.roles))t.push(`${i}.roles must be an object`);else for(let[s,o]of Object.entries(n.roles))t.push(...Il(o,`${i}.roles.${s}`))}return t}var kl=Rl(fo);if(kl.length>0)throw Error(`Invalid character animation catalog:
8
+ ${kl.join(`
9
+ `)}`);var Rf=fo,Tf=["jump","frontFlip","horseWalk","swim"],Of=Object.keys(Rf.clips).filter((e)=>!Tf.includes(e));var Ol=["top","side","bottom"],Bl=["left","right","bottom","top","back","front"],Pl=["humanoid","female","pig","robot","dog","cat","horse","bird","octopus"],ki=["leftLeg","rightLeg","leftArm","rightArm","leftLegFoot","rightLegFoot","leftArmFoot","rightArmFoot","leftSleeve","rightSleeve"],Dl=["leftWing","rightWing","carried","muzzle"];var hy=new Set(Pl),fy=new Set([...ki,...Dl]),Ay=new Set(Ol),gy=new Set(Bl),my=["cree","per"].join(""),En=["H","oof"].join(""),py=new Map([[`leftLeg${En}`,"leftLegFoot"],[`rightLeg${En}`,"rightLegFoot"],[`leftArm${En}`,"leftArmFoot"],[`rightArm${En}`,"rightArmFoot"]]),by=["horse",En].join("");var Df=Math.PI*2;var _y=new Set(ki);var Ml={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],transparent:[0,0,0,0],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]};function Nl(e){let t=new Set;for(let r of e)for(let n of r)if(n.active&&n.color)t.add(n.color);return t}function Ao(e,t){let r=Nl(t);return e.filter((n)=>r.has(n))}var Nf=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Lf=/^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)(deg|grad|rad|turn)?$/i,Ti=(e,t,r)=>Math.max(t,Math.min(r,e));function Oi(e){let t=e.trim(),r=t.endsWith("%"),n=r?t.slice(0,-1):t;if(!Nf.test(n))return null;let i=Number(n);return Number.isFinite(i)?{value:i,percentage:r}:null}function Fl(e){if(e===null)return 1;let t=Oi(e);if(!t)return null;return Ti(t.percentage?t.value/100:t.value,0,1)}function Gl(e,t){let r=/^([a-z]+)\(\s*(.*?)\s*\)$/i.exec(e.trim());if(!r||!t.includes(r[1].toLowerCase()))return null;let n=r[2];if(n.includes(",")){let a=n.split("/");if(a.length>2)return null;let l=a[0].split(",").map((c)=>c.trim());if(l.some((c)=>!c))return null;if(a.length===2){let c=a[1].trim();return l.length===3&&c?{channels:l,alpha:c}:null}return l.length===3||l.length===4?{channels:l.slice(0,3),alpha:l[3]??null}:null}let i=n.split("/");if(i.length>2)return null;let s=i[0].trim().split(/\s+/),o=i.length===2?i[1].trim():null;return s.length===3&&(i.length===1||o)?{channels:s,alpha:o}:null}function Ff(e){let t=Lf.exec(e.trim());if(!t)return null;let r=Number(t[1]);if(!Number.isFinite(r))return null;switch(t[2]?.toLowerCase()){case"grad":return r*0.9;case"rad":return r*180/Math.PI;case"turn":return r*360;default:return r}}function Sn(e){let t=Gl(e,["hsl","hsla"]);if(!t)return null;let r=Ff(t.channels[0]),n=Oi(t.channels[1]),i=Oi(t.channels[2]),s=Fl(t.alpha);if(r===null||!n||!i||s===null)return null;return[r,Ti(n.value,0,100),Ti(i.value,0,100),s]}function Ul(e,t,r){let n=t/100,i=r/100,s=(1-Math.abs(2*i-1))*n,o=(e%360+360)%360/60,a=s*(1-Math.abs(o%2-1)),l=0,c=0,u=0;if(o<1)[l,c,u]=[s,a,0];else if(o<2)[l,c,u]=[a,s,0];else if(o<3)[l,c,u]=[0,s,a];else if(o<4)[l,c,u]=[0,a,s];else if(o<5)[l,c,u]=[a,0,s];else[l,c,u]=[s,0,a];let d=i-s/2;return{r:Math.round((l+d)*255),g:Math.round((c+d)*255),b:Math.round((u+d)*255)}}function Hl({r:e,g:t,b:r}){let n=e/255,i=t/255,s=r/255,o=Math.max(n,i,s),a=Math.min(n,i,s),l=o-a,c=(o+a)/2;if(l===0)return{h:0,s:0,l:c*100};let u;if(o===n)u=((i-s)/l+(i<s?6:0))*60;else if(o===i)u=((s-n)/l+2)*60;else u=((n-i)/l+4)*60;return{h:u,s:l/(1-Math.abs(2*c-1))*100,l:c*100}}function In({r:e,g:t,b:r}){let n=(i)=>Math.round(Math.max(0,Math.min(255,i))).toString(16).padStart(2,"0");return`#${n(e)}${n(t)}${n(r)}`}var Ll=(e,t)=>{let r=Math.max(-100,Math.min(100,t))/100;return r>=0?e+(100-e)*r:e*(1+r)};var Ri=(e)=>{let t=Math.round(e*1000)/1000;return String(Object.is(t,-0)?0:t)};function go(e,t,r){if(t===0&&r===0)return e;let n=Sn(e),i=n?null:Pt(e);if(!n&&!i)return e;let s=n?{h:n[0],s:n[1],l:n[2]}:Hl(i),o=s.s===0?0:Ll(s.s,t),a=Ll(s.l,r),l=n?.[3]??i?.a??1;return`hsla(${Ri(s.h)}, ${Ri(o)}%, ${Ri(a)}%, ${Ri(l)})`}function dt(e){return typeof e==="number"&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function kn(e,t,r){let n=dt(t),i=dt(r);if(n===0&&i===0)return e;return e.map((s)=>go(s,n,i))}function Qt(e,t,r){if(t===0&&r===0)return e;let n=new Map,i=(s)=>{let o=n.get(s);if(o===void 0)o=go(s,t,r),n.set(s,o);return o};return e.map((s)=>s.map((o)=>({...o,color:o.color===null?null:i(o.color)})))}function Gf(e){let t=/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.exec(e.trim());if(!t)return null;let r=t[1],n=r.length<=4?[...r].map((i)=>i+i).join(""):r;return{r:Number.parseInt(n.slice(0,2),16),g:Number.parseInt(n.slice(2,4),16),b:Number.parseInt(n.slice(4,6),16),a:n.length===8?Number.parseInt(n.slice(6,8),16)/255:1}}function Uf(e){let t=Gl(e,["rgb","rgba"]);if(!t)return null;let r=t.channels.map(Oi),n=Fl(t.alpha);if(r.some((l)=>l===null)||n===null)return null;let[i,s,o]=r,a=(l)=>Ti(l.percentage?l.value/100*255:l.value,0,255);return{r:a(i),g:a(s),b:a(o),a:n}}function Pt(e){let t=e.trim(),r=Gf(t);if(r)return r;let n=Sn(t);if(n)return{...Ul(n[0],n[1],n[2]),a:n[3]};let i=Uf(t);if(i)return i;let s=Ml[t.toLowerCase()];if(!s)return null;return{r:s[0],g:s[1],b:s[2],a:s[3]??1}}function cr(e){let t=Pt(e);return t?{r:t.r,g:t.g,b:t.b}:null}var Bi=1;var mo=30;function Rn(e){return e.trim().slice(0,30)}function Pi(e,t){return e.trim().replace(/[^a-z0-9_-]+/gi,"-").replace(/^-+|-+$/g,"")||t}var Tn=0.16,po=0.1;var Wr=0.15,bo=0.12;var yr=0.25;var Di=[-1,1];function wr(...e){let t=Math.max(0,Math.min(...e));return Math.max(0.22,t*0.5)}var ke=64,yo=ke*ke;var wo=64,Kl=512,Zy=Kl*Kl,Yf=128,Ql=65535,Qf=20,Jf=/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i,Vf=/^[a-z]+$/i,Zf=/^(?:rgb|rgba|hsl|hsla)\([\d\s.,%+\-/e]*(?:(?:deg|grad|rad|turn)[\d\s.,%+\-/e]*)?\)$/i;function Jl(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Yr(e,t,r){return Number.isInteger(e)&&Number(e)>=t&&Number(e)<=r}function _t(e){if(typeof e!=="string"||e.length===0||e.length>Yf)return!1;return Jf.test(e)||Vf.test(e)||Zf.test(e)}function $f(e){return Jl(e)&&e.v===2}function Wl(e,t){return e===void 0||Array.isArray(e)&&e.length<=t&&e.every((r)=>Yr(r,0,t-1))}function Yl(e,t,r){return e===void 0||Array.isArray(e)&&e.length===t&&e.every((n)=>Yr(n,0,r))}function Xf(e,t,r){let{w:n,h:i,palette:s,cells:o,activeNoColor:a,tiles:l,depths:c,mirrorZ:u}=e;if(!Yr(n,0,t)||!Yr(i,0,t))return!1;let d=n*i;return d<=r&&Array.isArray(s)&&s.length<=d&&s.every(_t)&&Array.isArray(o)&&o.length===d&&o.every((f)=>Yr(f,0,s.length))&&Wl(a,d)&&Yl(l,d,Ql+1)&&Yl(c,d,Qf)&&Wl(u,d)}function zf(e){if(!Jl(e)||typeof e.active!=="boolean")return!1;if(e.color!==null&&!_t(e.color))return!1;if(e.tileIndex!==void 0&&e.tileIndex!==null&&!Yr(e.tileIndex,0,Ql))return!1;if(e.depth!==void 0&&e.depth!==null&&!Number.isFinite(e.depth))return!1;return e.mirrorZ===void 0||e.mirrorZ===null||typeof e.mirrorZ==="boolean"}function qf(e){if(e.length>ke)return null;let t=0,r=[];for(let n of e){if(!Array.isArray(n)||n.length>ke)return null;if(t+=n.length,t>yo||!n.every(zf))return null;r.push(n.map((i)=>({active:i.active,color:i.color,...i.tileIndex!=null?{tileIndex:i.tileIndex}:{},...We(i.depth)>lr?{depth:We(i.depth)}:{},...i.mirrorZ?{mirrorZ:!0}:{}})))}return r}function Qr(e){let t=e.length,r=t>0?e[0].length:0,n=[],i=new Map,s=Array(r*t).fill(0),o=[],a=null,l=null,c=[];for(let d=0;d<t;d++){let f=e[d];for(let g=0;g<r;g++){let A=f?.[g],m=d*r+g;if(!A)continue;if(A.color){let w=i.get(A.color);if(w===void 0)n.push(A.color),w=n.length,i.set(A.color,w);s[m]=w}else if(A.active)o.push(m);if(A.tileIndex!=null)a??=Array(r*t).fill(0),a[m]=A.tileIndex+1;let b=We(A.depth);if(b>lr)l??=Array(r*t).fill(0),l[m]=b;if(A.mirrorZ)c.push(m)}}let u={v:2,w:r,h:t,palette:n,cells:s};if(o.length>0)u.activeNoColor=o;if(a)u.tiles=a;if(l)u.depths=l;if(c.length>0)u.mirrorZ=c;return u}function On(e){if($f(e))return Xf(e,ke,yo)?eA(e):[];return Array.isArray(e)?qf(e)??[]:[]}function eA(e){let{w:t,h:r,palette:n,cells:i,activeNoColor:s,tiles:o,depths:a}=e,l=s?new Set(s):null,c=e.mirrorZ?new Set(e.mirrorZ):null,u=Array(r);for(let d=0;d<r;d++){let f=Array(t);for(let g=0;g<t;g++){let A=d*t+g,m=i[A];if(m>0)f[g]={active:!0,color:n[m-1]??null};else if(l?.has(A))f[g]={active:!0,color:null};else f[g]={active:!1,color:null};let b=o?.[A];if(b)f[g].tileIndex=b-1;let w=We(a?.[A]);if(w>lr)f[g].depth=w;if(c?.has(A))f[g].mirrorZ=!0}u[d]=f}return u}var tA={top:0,side:1,bottom:2};var rA=/^data:image\/(?:png|gif|webp);base64,[a-z\d+/=]+$/i;var nA=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}\/[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}\/[\da-f]{64}\.png$/i;function vo(e,t){return Number.isInteger(e)&&Number(e)>0&&Number(e)<=t}function iA(e){if(typeof e!=="string"||e.length===0||e.length>256)return!1;return![...e].some((t)=>{let r=t.charCodeAt(0);return r<32||r===127})}function sA(e,t){return e===void 0||Array.isArray(e)&&e.length<=t&&e.every((r)=>r===null||typeof r==="string"&&r.length<=128&&/^[a-z0-9_-]+$/i.test(r))}function _o(e){if(!e||e.v!==2&&e.v!==3)return!1;if(!iA(e.name)||!vo(e.tileSize,64)||!vo(e.cols,256)||!vo(e.rows,256))return!1;if(e.faceLayout!==void 0&&e.faceLayout!=="top-side-bottom")return!1;if(!sA(e.tileIds,e.cols*e.rows))return!1;let t=e.cols*e.tileSize*(e.faceLayout?3:1),r=e.rows*e.tileSize;return e.cols*e.tileSize<=4096&&r<=4096&&t*r<=16777216}function oA(e,t){if(typeof e!=="string"||e.length===0||e.length>4096)return null;for(let r of e){let n=r.charCodeAt(0);if(n<=32||n===127||`<>"'\\`.includes(r))return null}if(typeof t!=="string"||!nA.test(t))return null;try{let r=new URL(e);return r.protocol==="https:"&&r.hostname==="ldxdyymfagplpxxsqmgs.supabase.co"&&r.port===""&&r.username===""&&r.password===""&&r.search===""&&r.hash===""&&r.pathname===`/storage/v1/object/public/tilesets/${t}`?e:null}catch{return null}}function Co(e){if(!_o(e))return null;if(e.v===2)return e.imageDataUrl.length<=16777216&&rA.test(e.imageDataUrl)?e.imageDataUrl:null;if(e.v===3)return oA(e.url,e.path);return null}function Bn(e,t,r="top"){if(!_o(e))return null;if(!Number.isInteger(t)||t<0||t>=e.cols*e.rows)return null;let n=e.faceLayout?3:1,i=e.faceLayout?tA[r]:0,s=e.cols*e.tileSize;return{sx:i*s+t%e.cols*e.tileSize,sy:Math.floor(t/e.cols)*e.tileSize,tileSize:e.tileSize,sheetW:s*n,sheetH:e.rows*e.tileSize}}function xo(e){if(!_o(e))return null;return{width:e.cols*e.tileSize*(e.faceLayout?3:1),height:e.rows*e.tileSize}}function aA(e){let t=e.length;for(let r=0;r<e.length;r+=101)t=(t<<5)-t+e.charCodeAt(r)|0;return`iso-sheet-${(t>>>0).toString(36)}`}var vr={corners:[[0,0,1],[1,0,1],[1,1,1],[0,1,1]],shade:1},Pn={corners:[[0,1,1],[0,1,0],[1,1,0],[1,1,1]],shade:0.97},Jr={corners:[[1,0,1],[1,0,0],[1,1,0],[1,1,1]],shade:0.94},_r=0.5,lA=0.75,cA="rgba(0, 0, 0, 0.16)",uA=0.92,dA="#92929a";function hA(e){if(!Number.isFinite(e))return _r;return Math.max(0,Math.min(1,e))}function Vl(e,t){if(t<_r){let n=t/_r,i=e*lA;return i+(e-i)*n}let r=(t-_r)/(1-_r);return e+(1-e)*r}function ue(e){return e.toFixed(2)}function Dt(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Zl(e){return`${ue(e[0])},${ue(e[1])}`}function fA([e,t]){let r=Zl(e),n=Zl(t);return r<n?`${r} ${n}`:`${n} ${r}`}function $l(e,t){return`<polygon points="${e.map(([n,i])=>`${ue(n)},${ue(i)}`).join(" ")}" fill="${Dt(t)}"/>`}function Xl(e,t,r){let n=t[0]-e[0],i=t[1]-e[1],s=Math.hypot(n,i)||1,o=Math.min(r,s/2)/s;return[e[0]+n*o,e[1]+i*o]}function AA(e,t){let r=e.length,n="";for(let i=0;i<r;i++){let s=e[i],o=e[(i-1+r)%r],a=e[(i+1)%r],l=Xl(s,o,t),c=Xl(s,a,t);n+=`${i===0?"M":"L"}${ue(l[0])},${ue(l[1])}`,n+=`Q${ue(s[0])},${ue(s[1])} ${ue(c[0])},${ue(c[1])}`}return`${n}Z`}function zl(e,t,r,n){return`<path d="${e}" fill="${Dt(t)}" stroke="${Dt(r)}" stroke-width="${ue(n)}" stroke-linejoin="round"/>`}function gA(e,t){if(e.length===0)return"";return`<path d="${e.map(([n,i])=>`M${ue(n[0])},${ue(n[1])}L${ue(i[0])},${ue(i[1])}`).join("")}" fill="none" stroke="${Dt(t)}" stroke-width="1" stroke-linejoin="round" vector-effect="non-scaling-stroke"/>`}function Eo(e){let{grid:t,numCols:r,numRows:n,scale:i=16,showGridLines:s=!1,sideLighting:o=_r,cellGroups:a=!1,tileset:l=null,tilesetImageId:c,embedTilesetImage:u=!0,blockStyle:d="normal"}=e,f=Number.isFinite(i)&&i>0?Math.min(i,1024):16,g=s&&d!=="jelly"?cA:void 0,A=hA(o),m=Co(l),b=l&&m?l:null,w=xo(b),p=w?.width??0,C=w?.height??0,_=m&&c&&/^[a-z_][\w:.-]{0,127}$/i.test(c)?c:null,y=m?_??aA(m):"",v=u||!_,x=t.slice(0,ke),B=Math.min(Number.isInteger(n)&&n>0?n:0,x.length,ke),M=x.reduce((H,S)=>Math.max(H,Array.isArray(S)?S.length:0),0),P=Math.min(Number.isInteger(r)&&r>0?r:0,M,ke),O=f,W=f/Math.sqrt(3),Q=f*2/Math.sqrt(3),j=d==="jelly"?O*Tn:0,ee=(H)=>H?.tileIndex!=null?Bn(b,H.tileIndex):null,ie=(H)=>{if(_t(H?.color))return H.color;return ee(H)?dA:null},z=(H,S,fe)=>[(H-S)*O,(H+S)*W-fe*Q],Be=(H,S)=>{let fe=t[S]?.[H];return fe?.active&&ie(fe)?We(fe.depth):0},Pe=[];for(let H=0;H<B;H++)for(let S=0;S<P;S++){let fe=t[H]?.[S],Ge=ie(fe);if(fe?.active&&Ge)Pe.push({x:S,y:H,color:Ge,tileIndex:fe.tileIndex??null,depth:We(fe.depth),mirrorZ:!!fe.mirrorZ})}if(Pe.length===0)return'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 0 0"/>';Pe.sort((H,S)=>H.x+H.y-(S.x+S.y)||H.depth-S.depth);let Je=[],ze=1/0,pe=-1/0,te=1/0,q=-1/0,F=!1,U=Vl(Jr.shade,A),ae=Vl(Pn.shade,A),se=(H)=>H===vr?H.shade:H===Jr?U:ae,Ne=(H,S)=>{if(H<ze)ze=H;if(H>pe)pe=H;if(S<te)te=S;if(S>q)q=S};for(let{x:H,y:S,color:fe,tileIndex:Ge,depth:At,mirrorZ:De}of Pe){let lt=Sn(fe),et=[],pt=[],{primary:re,mirrored:Oe}=xn(At,De),Tt=(ge)=>lt?`hsla(${lt[0]}, ${lt[1]}%, ${Math.max(0,Math.min(100,lt[2]*ge))}%, ${lt[3]})`:fe,qt=(ge,ye=0,Ue=re)=>ge.corners.map(([Ce,de,ne])=>z(H+Ce,S+de,ne===0?ye:Ue)),Mr=(ge,ye=0,Ue=re)=>{let Ce=qt(ge,ye,Ue);if(j>0){let de=se(ge),ne=Tt(de),le=AA(Ce,j),Me=ge===vr?Tt(Math.min(1.18,de+0.13)):Tt(de*uA);et.push(zl(le,ne,ne,j),zl(le,"none",Me,j*0.3))}else et.push($l(Ce,Tt(se(ge))));for(let[de,ne]of Ce)Ne(de,ne)},er=De?-Oe:Be(H+1,S),tr=De?-Oe:Be(H,S+1),Nr=a&&!De?0:er,Ot=a&&!De?0:tr,An=a||De||Nr<re,Ai=a||De||Ot<re;if(An)Mr(Jr,Nr,re);if(Ai)Mr(Pn,Ot,re);if(Mr(vr,re,re),g){let ge=new Set,ye=(ne,le)=>{let Me=fA([ne,le]);if(ge.has(Me))return;ge.add(Me),pt.push([ne,le])},Ue=(ne)=>{for(let le=0;le<ne.length;le++)ye(ne[le],ne[(le+1)%ne.length])},Ce=(ne,le)=>{let[Me,Ve]=ne.corners.filter(([,,Se])=>Se===0);for(let Se=Math.floor(le)+1;Se<re;Se++)ye(z(H+Me[0],S+Me[1],Se),z(H+Ve[0],S+Ve[1],Se))},de=qt(vr,re,re);if(ye(de[0],de[1]),Be(H+1,S)!==re)ye(de[1],de[2]);if(Be(H,S+1)!==re)ye(de[2],de[3]);if(ye(de[3],de[0]),De||er<re)Ue(qt(Jr,er,re)),Ce(Jr,er);if(De||tr<re)Ue(qt(Pn,tr,re)),Ce(Pn,tr)}let gi=Ge==null?null:Bn(b,Ge);if(gi){F=!0;let ge=(Ce,de,ne,le,Me,Ve,Se,nt)=>{let it=Bn(b,Ge,Ce);if(!it)return;let xt=1-nt;et.push(`<g transform="matrix(${de} ${ne} ${le} ${Me} ${ue(Ve)} ${ue(Se)})"><svg x="0" y="0" width="1" height="1" viewBox="${it.sx} ${it.sy} ${it.tileSize} ${it.tileSize}" preserveAspectRatio="none"><use href="#${y}" xlink:href="#${y}"/></svg>`+(xt>0?`<rect x="0" y="0" width="1" height="1" fill="#000" opacity="${xt.toFixed(2)}"/>`:"")+"</g>")};if(An){let[Ce,de]=z(H+1,S,re);ge("side",-O,W,0,Q*(re-Nr),Ce,de,se(Jr))}if(Ai){let[Ce,de]=z(H,S+1,re);ge("side",O,W,0,Q*(re-Ot),Ce,de,se(Pn))}let[ye,Ue]=z(H,S,re);ge("top",O,W,-O,W,ye,Ue,vr.shade)}if(g)et.push(gA(pt,g));if(d!=="normal"&&!gi){if(d==="lego"){let ge=Math.SQRT2*Wr*O,ye=Math.SQRT2*Wr*W,Ue=Tt(U),Ce=Tt(vr.shade),de=[[-1,-1],[-1,1],[1,-1],[1,1]];for(let[ne,le]of de){let Me=H+0.5+ne*yr,Ve=S+0.5+le*yr,[Se,nt]=z(Me,Ve,re),[,it]=z(Me,Ve,re+bo);Ne(Se-ge,nt+ye),Ne(Se+ge,it-ye);let xt='shape-rendering="geometricPrecision"';et.push(`<ellipse cx="${ue(Se)}" cy="${ue(nt)}" rx="${ue(ge)}" ry="${ue(ye)}" fill="${Dt(Ue)}" ${xt}/>`,`<rect x="${ue(Se-ge)}" y="${ue(it)}" width="${ue(ge*2)}" height="${ue(nt-it)}" fill="${Dt(Ue)}" ${xt}/>`,`<ellipse cx="${ue(Se)}" cy="${ue(it)}" rx="${ue(ge)}" ry="${ue(ye)}" fill="${Dt(Ce)}" ${xt}/>`)}}else if(d==="voxel"){let ge=(ne,le,Me,Ve,Se,nt)=>{let it=(xt,Us)=>{for(let[gn,mi]of xt)Ne(gn,mi);et.push($l(xt,Tt(Us)))};it([z(le,Me,nt),z(le,Me,Se),z(le,Ve,Se),z(le,Ve,nt)],U),it([z(ne,Ve,nt),z(ne,Ve,Se),z(le,Ve,Se),z(le,Ve,nt)],ae),it([z(ne,Me,nt),z(le,Me,nt),z(le,Ve,nt),z(ne,Ve,nt)],vr.shade)},ye=po,Ue=wr(1,1),Ce=De||er<re?er:null,de=De||tr<re?tr:null;if(ge(H+0.5-Ue/2,H+0.5+Ue/2,S+0.5-Ue/2,S+0.5+Ue/2,re,re+ye),Ce!==null){let ne=wr(1,re-Ce),le=(re+Ce)/2;ge(H+1,H+1+ye,S+0.5-ne/2,S+0.5+ne/2,le-ne/2,le+ne/2)}if(de!==null){let ne=wr(1,re-de),le=(re+de)/2;ge(H+0.5-ne/2,H+0.5+ne/2,S+1,S+1+ye,le-ne/2,le+ne/2)}}}if(a)Je.push(`<g data-color="${Dt(fe)}">${et.join("")}</g>`);else Je.push(...et)}let be=2+j/2,rt=ze-be,qe=te-be,Le=pe-ze+be*2,Fe=q-te+be*2,Rt=F&&b&&m&&v?`<defs><image id="${y}" href="${Dt(m)}" xlink:href="${Dt(m)}" x="0" y="0" width="${p}" height="${C}" style="image-rendering:pixelated"/></defs>`:"";return[`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="${ue(rt)} ${ue(qe)} ${ue(Le)} ${ue(Fe)}" shape-rendering="crispEdges">`,Rt,...Je,"</svg>"].join("")}var mA="hsla(278, 100%, 70%, 1)",pA=/hsla\(278, 100%, ([\d.]+)%, 1\)/g,Dn=(e)=>Eo({grid:[[{active:!0,color:mA}]],numCols:1,numRows:1,blockStyle:e,sideLighting:0.15}).replaceAll(pA,"hsl(var(--block-style-icon-hs, 278 100%) $1% / 1)"),bA=[{style:"normal",label:"Normal",icon:Dn("normal")},{style:"voxel",label:"Voxel",icon:Dn("voxel")},{style:"lego",label:"Lego",icon:Dn("lego")},{style:"jelly",label:"Jelly",icon:Dn("jelly")}];function yA(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function So(e,t,r,n,i=1){let s=yA(t),o=`<rect x="${r}" y="${n}" width="${i}" height="${i}" fill="${s}"/>`;if(e==="normal")return o;if(e==="jelly"){let c=i*Tn,u=i*0.055,d=u/2;return`<g shape-rendering="geometricPrecision">${[`<rect x="${r}" y="${n}" width="${i}" height="${i}" rx="${c}" fill="${s}"/>`,`<path d="M${r+d} ${n+i-c}V${n+c}Q${r+d} ${n+d} ${r+c} ${n+d}H${r+i-c}" fill="none" stroke="rgba(255, 255, 255, 0.22)" stroke-width="${u}" stroke-linecap="round"/>`,`<path d="M${r+i-d} ${n+c}V${n+i-c}Q${r+i-d} ${n+i-d} ${r+i-c} ${n+i-d}H${r+c}" fill="none" stroke="rgba(0, 0, 0, 0.14)" stroke-width="${u}" stroke-linecap="round"/>`].join("")}</g>`}if(e==="voxel"){let c=i*wr(1,1),u=r+(i-c)/2,d=n+(i-c)/2,f=i*0.045,g=i*0.035;return[o,`<rect x="${u+f}" y="${d+f}" width="${c}" height="${c}" fill="rgba(0, 0, 0, 0.22)"/>`,`<rect x="${u}" y="${d}" width="${c}" height="${c}" fill="${s}"/>`,`<path d="M${u} ${d+c}V${d}H${u+c}" fill="none" stroke="rgba(255, 255, 255, 0.26)" stroke-width="${g}"/>`,`<path d="M${u+c} ${d}V${d+c}H${u}" fill="none" stroke="rgba(0, 0, 0, 0.12)" stroke-width="${g}"/>`].join("")}let a=i*Wr,l=(c)=>Di.flatMap((u)=>Di.map((d)=>{let f=r+i*(0.5+u*yr+c),g=n+i*(0.5+d*yr+c);return`M${f+a} ${g}A${a} ${a} 0 1 1 ${f-a} ${g}A${a} ${a} 0 1 1 ${f+a} ${g}Z`})).join("");return`<g shape-rendering="geometricPrecision">${[o,`<path d="${l(0.04)}" fill="rgba(0, 0, 0, 0.22)"/>`,`<path d="${l(0)}" fill="${s}"/>`,`<path d="${l(0)}" fill="rgba(0, 0, 0, 0.06)" stroke="rgba(255, 255, 255, 0.12)" stroke-width="${i*0.025}"/>`].join("")}</g>`}var ht=[{name:"Classic",colors:["hsla(278, 100%, 50%, 1)","hsla(278, 100%, 16%, 1)","hsla(278, 100%, 80%, 1)","hsla(306, 100%, 50%, 1)","hsla(28, 100%, 60%, 1)","hsla(0, 80%, 60%, 1)","hsla(278, 60%, 35%, 1)","hsla(306, 100%, 80%, 1)","hsla(306, 80%, 30%, 1)","hsla(28, 100%, 80%, 1)"]},{name:"Super Mario",colors:["hsla(218, 100%, 68%, 1)","hsla(0, 85%, 55%, 1)","hsla(225, 85%, 45%, 1)","hsla(28, 100%, 80%, 1)","hsla(22, 60%, 32%, 1)","hsla(120, 70%, 40%, 1)","hsla(45, 100%, 55%, 1)","hsla(0, 0%, 100%, 1)","hsla(0, 0%, 8%, 1)","hsla(22, 45%, 22%, 1)"]},{name:"Pac-Man",colors:["hsla(60, 100%, 50%, 1)","hsla(240, 100%, 56%, 1)","hsla(0, 100%, 50%, 1)","hsla(300, 100%, 86%, 1)","hsla(180, 100%, 50%, 1)","hsla(32, 100%, 66%, 1)","hsla(0, 0%, 100%, 1)","hsla(0, 0%, 5%, 1)","hsla(240, 100%, 25%, 1)","hsla(60, 100%, 80%, 1)"]},{name:"Grayscale",colors:["hsla(0, 0%, 98%, 1)","hsla(0, 0%, 92%, 1)","hsla(0, 0%, 86%, 1)","hsla(0, 0%, 80%, 1)","hsla(0, 0%, 74%, 1)","hsla(0, 0%, 68%, 1)","hsla(0, 0%, 62%, 1)","hsla(0, 0%, 56%, 1)","hsla(0, 0%, 50%, 1)","hsla(0, 0%, 44%, 1)"]},{name:"Sunset",colors:["hsla(45, 100%, 70%, 1)","hsla(28, 100%, 60%, 1)","hsla(12, 90%, 55%, 1)","hsla(350, 80%, 55%, 1)","hsla(320, 60%, 45%, 1)","hsla(280, 45%, 25%, 1)","hsla(50, 100%, 88%, 1)","hsla(38, 100%, 78%, 1)","hsla(20, 100%, 68%, 1)","hsla(5, 85%, 45%, 1)"]},{name:"Ocean",colors:["hsla(180, 70%, 80%, 1)","hsla(190, 75%, 60%, 1)","hsla(205, 75%, 50%, 1)","hsla(215, 70%, 40%, 1)","hsla(225, 65%, 28%, 1)","hsla(235, 55%, 15%, 1)","hsla(175, 60%, 92%, 1)","hsla(185, 70%, 70%, 1)","hsla(195, 75%, 55%, 1)","hsla(200, 70%, 45%, 1)"]},{name:"Pastel",colors:["hsla(350, 100%, 88%, 1)","hsla(30, 100%, 85%, 1)","hsla(55, 85%, 82%, 1)","hsla(135, 60%, 82%, 1)","hsla(200, 75%, 85%, 1)","hsla(275, 70%, 85%, 1)","hsla(15, 100%, 86%, 1)","hsla(45, 100%, 85%, 1)","hsla(90, 55%, 82%, 1)","hsla(160, 55%, 82%, 1)"]},{name:"Gameboy",colors:["hsla(85, 60%, 85%, 1)","hsla(88, 58%, 78%, 1)","hsla(90, 56%, 72%, 1)","hsla(93, 55%, 66%, 1)","hsla(95, 55%, 60%, 1)","hsla(98, 53%, 54%, 1)","hsla(102, 52%, 48%, 1)","hsla(105, 51%, 42%, 1)","hsla(110, 50%, 35%, 1)","hsla(113, 52%, 30%, 1)"]},{name:"Neon",colors:["hsla(320, 100%, 60%, 1)","hsla(180, 100%, 55%, 1)","hsla(60, 100%, 60%, 1)","hsla(270, 100%, 65%, 1)","hsla(130, 100%, 55%, 1)","hsla(25, 100%, 55%, 1)","hsla(300, 100%, 50%, 1)","hsla(200, 100%, 60%, 1)","hsla(90, 100%, 55%, 1)","hsla(45, 100%, 55%, 1)"]},{name:"Forest",colors:["hsla(80, 35%, 75%, 1)","hsla(100, 40%, 50%, 1)","hsla(120, 45%, 30%, 1)","hsla(140, 35%, 18%, 1)","hsla(30, 40%, 35%, 1)","hsla(25, 50%, 22%, 1)","hsla(70, 40%, 88%, 1)","hsla(90, 45%, 62%, 1)","hsla(110, 45%, 40%, 1)","hsla(130, 40%, 24%, 1)"]},{name:"Candy",colors:["hsla(340, 100%, 80%, 1)","hsla(320, 90%, 65%, 1)","hsla(280, 85%, 65%, 1)","hsla(200, 90%, 70%, 1)","hsla(165, 75%, 65%, 1)","hsla(50, 100%, 70%, 1)","hsla(350, 100%, 90%, 1)","hsla(0, 90%, 70%, 1)","hsla(30, 100%, 72%, 1)","hsla(60, 90%, 75%, 1)"]},{name:"Cobalt",colors:["hsla(215, 85%, 94%, 1)","hsla(215, 85%, 86%, 1)","hsla(215, 85%, 78%, 1)","hsla(215, 85%, 70%, 1)","hsla(215, 85%, 62%, 1)","hsla(215, 85%, 54%, 1)","hsla(215, 85%, 46%, 1)","hsla(215, 85%, 40%, 1)","hsla(215, 85%, 34%, 1)","hsla(215, 85%, 28%, 1)"]},{name:"Terracotta",colors:["hsla(25, 55%, 78%, 1)","hsla(20, 65%, 55%, 1)","hsla(15, 60%, 40%, 1)","hsla(15, 50%, 25%, 1)","hsla(35, 40%, 60%, 1)","hsla(0, 25%, 12%, 1)","hsla(30, 60%, 88%, 1)","hsla(25, 60%, 68%, 1)","hsla(18, 65%, 48%, 1)","hsla(12, 55%, 32%, 1)"]},{name:"Vaporwave",colors:["hsla(330, 100%, 78%, 1)","hsla(290, 80%, 60%, 1)","hsla(200, 90%, 72%, 1)","hsla(170, 70%, 60%, 1)","hsla(40, 90%, 78%, 1)","hsla(260, 45%, 18%, 1)","hsla(320, 100%, 88%, 1)","hsla(310, 90%, 70%, 1)","hsla(280, 70%, 45%, 1)","hsla(250, 60%, 55%, 1)"]},{name:"Mint",colors:["hsla(160, 65%, 88%, 1)","hsla(165, 60%, 65%, 1)","hsla(170, 55%, 45%, 1)","hsla(175, 50%, 28%, 1)","hsla(180, 30%, 15%, 1)","hsla(55, 60%, 90%, 1)","hsla(155, 70%, 95%, 1)","hsla(160, 60%, 78%, 1)","hsla(165, 55%, 55%, 1)","hsla(170, 50%, 36%, 1)"]},{name:"Sakura",colors:["hsla(340, 100%, 93%, 1)","hsla(345, 85%, 80%, 1)","hsla(350, 70%, 65%, 1)","hsla(355, 60%, 48%, 1)","hsla(30, 40%, 32%, 1)","hsla(120, 30%, 42%, 1)","hsla(340, 100%, 97%, 1)","hsla(342, 90%, 87%, 1)","hsla(348, 80%, 72%, 1)","hsla(352, 65%, 56%, 1)"]},{name:"Desert",colors:["hsla(40, 55%, 82%, 1)","hsla(30, 50%, 65%, 1)","hsla(15, 45%, 48%, 1)","hsla(90, 30%, 45%, 1)","hsla(95, 25%, 22%, 1)","hsla(200, 40%, 72%, 1)","hsla(42, 60%, 92%, 1)","hsla(35, 55%, 74%, 1)","hsla(25, 50%, 56%, 1)","hsla(18, 45%, 38%, 1)"]},{name:"Galaxy",colors:["hsla(265, 70%, 82%, 1)","hsla(275, 75%, 55%, 1)","hsla(290, 85%, 35%, 1)","hsla(220, 70%, 40%, 1)","hsla(230, 60%, 12%, 1)","hsla(50, 90%, 82%, 1)","hsla(260, 80%, 92%, 1)","hsla(270, 75%, 68%, 1)","hsla(285, 80%, 45%, 1)","hsla(300, 85%, 28%, 1)"]},{name:"Ember",colors:["hsla(25, 100%, 95%, 1)","hsla(25, 100%, 88%, 1)","hsla(25, 100%, 80%, 1)","hsla(25, 100%, 72%, 1)","hsla(25, 100%, 65%, 1)","hsla(25, 100%, 58%, 1)","hsla(25, 100%, 50%, 1)","hsla(25, 100%, 44%, 1)","hsla(25, 100%, 38%, 1)","hsla(25, 100%, 32%, 1)"]},{name:"Watermelon",colors:["hsla(350, 85%, 80%, 1)","hsla(350, 75%, 62%, 1)","hsla(355, 65%, 45%, 1)","hsla(90, 45%, 62%, 1)","hsla(110, 50%, 30%, 1)","hsla(0, 0%, 8%, 1)","hsla(350, 90%, 90%, 1)","hsla(350, 80%, 70%, 1)","hsla(352, 70%, 55%, 1)","hsla(358, 60%, 38%, 1)"]}];var wA=16777216,vA=16;function Vr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function _A(e){if(!Array.isArray(e))return[...ht[0].colors];let t=e.slice(0,vA).flatMap((r)=>{if(typeof r==="string"&&_t(r))return[r];if(Vr(r)&&_t(r.color)&&typeof r.opacity==="number"&&Number.isFinite(r.opacity)&&r.opacity>=0&&r.opacity<=1)return[r.color];return[]});return t.length>0?t:[...ht[0].colors]}function CA(e){if(!Array.isArray(e.artboards))return 0;return Number.isInteger(e.activeArtboard)&&Number(e.activeArtboard)>=0&&Number(e.activeArtboard)<e.artboards.length?Number(e.activeArtboard):0}function xA(e){let t=Vr(e)?e:{};return{saturation:dt(t.saturation),lightness:dt(t.lightness)}}function Mn(e){if(e.length>wA)throw Error("Draft is too large");let t=JSON.parse(e);if(!Vr(t)||t.version!==1)throw Error("Not a Flatblox version-1 draft");let r=On(t.grid),n=t.gridSize===void 0?r.length:t.gridSize;if(!Number.isInteger(n)||Number(n)<1||Number(n)>ke||r.length!==n||!r.every((o)=>o.length===n))throw Error("Draft contains an invalid grid");let i=_A(t.palette),s=_t(t.activeColor)?t.activeColor:i[0];return{filename:typeof t.filename==="string"?Rn(t.filename):"untitled",grid:r,palette:i,activeColor:s,paletteColorAdjustment:xA(t.paletteColorAdjustment),draft:{data:t,activeArtboard:CA(t)}}}function EA(e,t){let r=Array.isArray(t)?t:[];return e.map((n,i)=>{let s=r[i];if(!Vr(s))return{color:n,opacity:1};let o=typeof s.opacity==="number"&&Number.isFinite(s.opacity)&&s.opacity>=0&&s.opacity<=1?s.opacity:1;return{...s,color:n,opacity:o}})}function SA(e,t){let r=e.draft?.data.artboards,n=Array.isArray(r)?[...r]:[],i=n.length>0?Math.min(e.draft?.activeArtboard??0,n.length-1):0;if(n.length===0)n.push(t);else{let s=n[i];n[i]=Vr(s)&&"grid"in s?{...s,grid:t}:t}return{artboards:n,activeArtboard:i}}function Nn(e){let t=e.draft?.data,r=Qr(e.grid),n=EA(e.palette,t?.palette),{artboards:i,activeArtboard:s}=SA(e,r),o=e.paletteColorAdjustment??{saturation:0,lightness:0},a=Vr(t?.paletteColorAdjustment)?t.paletteColorAdjustment:{};return JSON.stringify({...t,version:1,grid:r,gridSize:e.grid.length,palette:n,paletteColorAdjustment:{...a,saturation:dt(o.saturation),lightness:dt(o.lightness)},activeColor:e.activeColor,artboards:i,activeArtboard:s,filename:e.filename,savedAt:new Date().toISOString()},null,2)}function Zr(e){return e==="rectangle"||e==="circle"}function IA(e,t){let r=Math.min(e.x,t.x),n=Math.max(e.x,t.x),i=Math.min(e.y,t.y),s=Math.max(e.y,t.y),o=[];for(let a=r;a<=n;a++)if(o.push({x:a,y:i}),s!==i)o.push({x:a,y:s});for(let a=i+1;a<s;a++)if(o.push({x:r,y:a}),n!==r)o.push({x:n,y:a});return o}function kA(e,t){let r=[],n=(b,w)=>r.push({x:b,y:w}),i=Math.min(e.x,t.x),s=Math.max(e.x,t.x),o=Math.min(e.y,t.y),a=Math.max(e.y,t.y),l=s-i,c=a-o;if(l===0||c===0){for(let b=o;b<=a;b++)for(let w=i;w<=s;w++)n(w,b);return r}let u=c&1,d=4*(1-l)*c*c,f=4*(u+1)*l*l,g=d+f+u*l*l;o+=c+1>>1,a=o-u;let A=8*l*l,m=8*c*c;do{n(s,o),n(i,o),n(i,a),n(s,a);let b=2*g;if(b<=f)o++,a--,f+=A,g+=f;if(b>=d||2*g>f)i++,s--,d+=m,g+=d}while(i<=s);while(o-a<c)n(i-1,o),n(s+1,o),o++,n(i-1,a),n(s+1,a),a--;return r}function Io(e,t,r){let n=e==="circle"?kA(t,r):IA(t,r),i=new Set;return n.filter((s)=>{let o=`${s.x}:${s.y}`;if(i.has(o))return!1;return i.add(o),!0})}var ec=16,RA=100;function ko(e,t,r){return Math.max(t,Math.min(r,e))}function ql(e){return e.map((t)=>t.map((r)=>({...r})))}function TA(e){return Array.from({length:e},()=>Array.from({length:e},()=>({active:!1,color:null})))}function tc(e){if(!Number.isInteger(e)||e<1||e>ke)throw Error(`Grid size must be between 1 and ${ke}`);return e}function Fn(e=ec){let t=[...ht[0].colors];return{filename:"untitled",grid:TA(tc(e)),palette:t,activeColor:t[0],paletteColorAdjustment:{saturation:0,lightness:0}}}function Ln(e,t,r,n){let i=[t];if(r)i.push({x:e-1-t.x,y:t.y});if(n)i.push({x:t.x,y:e-1-t.y});if(r&&n)i.push({x:e-1-t.x,y:e-1-t.y});return[...new Map(i.map((s)=>[`${s.x}:${s.y}`,s])).values()]}class Jt{palette;paletteColorAdjustment;cursor={x:0,y:0};tool="draw";mirrorX=!1;mirrorY=!1;activeColorIndex;currentId=0;nextId=1;savedId=0;currentFilename;savedFilename;undoStack=[];redoStack=[];currentGrid;pendingChanges=null;draft;constructor(e){let t=tc(e.grid.length);if(!e.grid.every((n)=>n.length===t))throw Error("Grid must be square");if(e.palette.length===0)throw Error("Palette is empty");this.currentFilename=e.filename||"untitled",this.savedFilename=this.currentFilename,this.palette=[...e.palette],this.paletteColorAdjustment={saturation:dt(e.paletteColorAdjustment?.saturation),lightness:dt(e.paletteColorAdjustment?.lightness)},this.draft=e.draft,this.currentGrid=ql(e.grid);let r=this.palette.indexOf(e.activeColor);this.activeColorIndex=r>=0?r:0}get grid(){return this.currentGrid}get filename(){return this.currentFilename}get size(){return this.currentGrid.length}get activeColor(){return this.palette[this.activeColorIndex]}get selectedColorIndex(){return this.activeColorIndex}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}get dirty(){return this.currentId!==this.savedId||this.currentFilename!==this.savedFilename}get revision(){return{id:this.currentId,filename:this.currentFilename}}rename(e){let t=e.trim();if(!t||t===this.currentFilename)return!1;return this.currentFilename=t,!0}moveCursor(e,t){this.setCursor(this.cursor.x+e,this.cursor.y+t)}setCursor(e,t){this.cursor={x:ko(Math.round(e),0,this.size-1),y:ko(Math.round(t),0,this.size-1)}}setTool(e){this.tool=e}selectColor(e){let t=this.palette.length;this.activeColorIndex=(Math.round(e)%t+t)%t}selectNextColor(e){this.selectColor(this.activeColorIndex+e)}toggleMirrorX(){this.mirrorX=!this.mirrorX}toggleMirrorY(){this.mirrorY=!this.mirrorY}applyAtCursor(e=this.tool){return this.applyAt(this.cursor.x,this.cursor.y,e)}applyAt(e,t,r=this.tool){if(e<0||e>=this.size||t<0||t>=this.size)return!1;if(r==="extrude")return this.extrudeAt(e,t,1);return this.commit(()=>r==="fill"?this.fill(e,t):this.paintMirrored(e,t,r==="erase"?null:this.activeColor))}depthAt(e,t){let r=this.currentGrid[t]?.[e];return r?.active?We(r.depth):null}extrudeAt(e,t,r){if(e<0||e>=this.size||t<0||t>=this.size)return!1;return this.commit(()=>{let n=!1;for(let i of Ln(this.size,{x:e,y:t},this.mirrorX,this.mirrorY)){let s=this.currentGrid[i.y][i.x];if(!s.active)continue;let o=We(s.depth),a=ko(o+r,lr,Ii);if(a===o)continue;this.replaceCell(i.x,i.y,{...s,depth:a}),n=!0}return n})}applyShape(e,t,r){if(!Zr(e))return!1;let n=this.shapePreview(e,t,r);if(n.length===0)return!1;return this.commit(()=>{let i=!1;for(let s of n)if(this.paintMirrored(s.x,s.y,this.activeColor))i=!0;return i})}shapePreview(e,t,r){let n=(i)=>i.x>=0&&i.x<this.size&&i.y>=0&&i.y<this.size;return Io(e,t,r).filter(n)}commit(e){let t=new Map;this.pendingChanges=t;try{if(!e())return!1}catch(n){for(let i of t.values())this.currentGrid[i.y][i.x]=i.before;throw n}finally{this.pendingChanges=null}let r=this.nextId++;if(this.undoStack.push({cells:[...t.values()],beforeId:this.currentId,afterId:r}),this.undoStack.length>RA)this.undoStack.shift();return this.redoStack=[],this.currentId=r,!0}replaceCell(e,t,r){let n=t*this.size+e,i=this.pendingChanges?.get(n);this.pendingChanges?.set(n,{x:e,y:t,before:i?.before??{...this.currentGrid[t][e]},after:{...r}}),this.currentGrid[t][e]=r}undo(){let e=this.undoStack.pop();if(!e)return!1;this.redoStack.push(e);for(let t of e.cells)this.currentGrid[t.y][t.x]={...t.before};return this.currentId=e.beforeId,!0}redo(){let e=this.redoStack.pop();if(!e)return!1;this.undoStack.push(e);for(let t of e.cells)this.currentGrid[t.y][t.x]={...t.after};return this.currentId=e.afterId,!0}markSaved(e=this.revision){return this.savedId=e.id,this.savedFilename=e.filename,!this.dirty}toDocument(){return{filename:this.currentFilename,grid:ql(this.currentGrid),palette:[...this.palette],activeColor:this.activeColor,paletteColorAdjustment:{...this.paletteColorAdjustment},...this.draft?{draft:{data:this.draft.data,activeArtboard:this.draft.activeArtboard}}:{}}}paintMirrored(e,t,r){let n=!1;for(let i of Ln(this.size,{x:e,y:t},this.mirrorX,this.mirrorY)){let s=this.currentGrid[i.y][i.x],o=r!==null;if(s.active===o&&s.color===r&&s.tileIndex==null)continue;this.replaceCell(i.x,i.y,o?{...s,active:o,color:r,tileIndex:null}:{active:o,color:r}),n=!0}return n}fill(e,t){let r=this.currentGrid[t][e];if(r.active&&r.color===this.activeColor&&r.tileIndex==null)return!1;let{active:n,color:i}=r,s=r.tileIndex??null,o=[{x:e,y:t}],a=new Set,l=!1;while(o.length>0){let c=o.pop();if(c.x<0||c.x>=this.size||c.y<0||c.y>=this.size)continue;let u=c.y*this.size+c.x;if(a.has(u))continue;a.add(u);let d=this.currentGrid[c.y][c.x];if(d.active!==n||n&&(d.color!==i||(d.tileIndex??null)!==s))continue;this.replaceCell(c.x,c.y,{...d,active:!0,color:this.activeColor,tileIndex:null}),l=!0,o.push({x:c.x+1,y:c.y},{x:c.x-1,y:c.y},{x:c.x,y:c.y+1},{x:c.x,y:c.y-1})}return l}}import{randomUUID as OA}from"crypto";import{link as BA,mkdir as PA,rename as DA,unlink as MA,writeFile as NA}from"fs/promises";import{dirname as LA}from"path";async function $r(e,t,r=!1){await PA(LA(e),{recursive:!0,mode:448});let n=`${e}.${OA()}.tmp`;try{if(await NA(n,t,{flag:"wx",mode:384}),r)await BA(n,e);else await DA(n,e)}finally{await MA(n).catch((i)=>{if(i.code!=="ENOENT")throw i})}}import{createConnection as FA}from"net";var GA="127.0.0.1",UA=47642,HA=3000,jA=32,KA=1048576,WA=16384,rc=[0.57,0.57,0.6,1],Mi=new Map;function YA(e){if(!e)return[...rc];let t=Mi.get(e);if(!t){let r=Pt(e);if(t=r?[r.r/255,r.g/255,r.b/255,r.a]:[...rc],Mi.size>=4096)Mi.clear();Mi.set(e,t)}return t}function QA(e){if(!e?.active)return{active:!1,color:null,depth:1,mirrorZ:!1};return{active:!0,color:YA(e.color),depth:We(e.depth),mirrorZ:!!e.mirrorZ}}function ic(e,t,r){return{x:t%r,y:Math.floor(t/r),...e}}function JA(e,t){let r=e.color===t.color||!!e.color&&!!t.color&&e.color.every((n,i)=>n===t.color?.[i]);return e.active===t.active&&r&&e.depth===t.depth&&e.mirrorZ===t.mirrorZ}function sc(e){let{saturation:t,lightness:r}=e.paletteColorAdjustment??{saturation:0,lightness:0},n=Qt(e.grid,t,r),i=n.length,s=n[0]?.length??0;return Array.from({length:s*i},(o,a)=>QA(n[Math.floor(a/s)]?.[a%s]))}function VA(e){let t=e.grid.length,r=e.grid[0]?.length??0,n=sc(e);return{message:{protocol:Bi,type:"snapshot",columns:r,rows:t,cells:n.flatMap((i,s)=>i.active?[ic(i,s,r)]:[])},state:n}}function ZA(e,t,r){return t.flatMap((n,i)=>e[i]&&JA(e[i],n)?[]:[ic(n,i,r)])}function nc(e){return(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string"?e.code:"")==="ECONNREFUSED"?"Blender add-on not found. Enable Flatblox Live in Blender.":"Could not connect to the Blender add-on."}class Ro{document;connector;socket=null;status={state:"disconnected"};listeners=new Set;connectPromise=null;resolveConnect=null;connectTimer=null;patchTimer=null;handshakeBuffer="";previousGrid=null;previousColumns=0;previousRows=0;pendingCells=new Map;backpressured=!1;dirty=!1;constructor(e,t=FA){this.document=e,this.connector=t}getStatus(){return{...this.status}}onStatus(e){return this.listeners.add(e),()=>this.listeners.delete(e)}connect(){if(this.status.state==="connected")return Promise.resolve(this.getStatus());if(this.connectPromise)return this.connectPromise;this.disconnectSocket(),this.resetStream(),this.handshakeBuffer="",this.setStatus({state:"connecting"}),this.connectPromise=new Promise((t)=>{this.resolveConnect=t});let e;try{e=this.connector({host:GA,port:UA})}catch(t){let r={state:"error",message:nc(t)};return this.setStatus(r),this.finishConnect(r),Promise.resolve(r)}return this.socket=e,e.setNoDelay(!0),e.on("data",(t)=>this.handleHandshake(e,t)),e.on("error",(t)=>this.fail(e,nc(t))),e.on("close",()=>this.handleClose(e)),e.on("drain",()=>{if(this.socket!==e)return;if(this.backpressured=!1,this.dirty)this.sync()}),this.connectTimer=setTimeout(()=>{this.fail(e,"Timed out waiting for the Blender add-on.")},HA),this.connectPromise}disconnect(){this.disconnectSocket(),this.resetStream();let e={state:"disconnected"};return this.setStatus(e),this.finishConnect(e),e}sync(){if(this.status.state!=="connected"||!this.socket)return;if(this.dirty=!0,this.backpressured)return;if(!this.patchTimer)this.patchTimer=setTimeout(()=>this.flushPatch(),jA)}collectChanges(){let e=this.document(),t=e.grid.length,r=e.grid[0]?.length??0;if(!this.previousGrid||r!==this.previousColumns||t!==this.previousRows){this.sendSnapshot(e);return}let n=sc(e);for(let i of ZA(this.previousGrid,n,r))this.pendingCells.set(i.y*r+i.x,i);this.previousGrid=n}dispose(){this.disconnect(),this.listeners.clear()}handleHandshake(e,t){if(this.socket!==e||this.status.state!=="connecting")return;if(this.handshakeBuffer+=t.toString("utf8"),Buffer.byteLength(this.handshakeBuffer)>WA){this.fail(e,"Blender sent an invalid handshake.");return}let r=this.handshakeBuffer.indexOf(`
10
+ `);if(r<0)return;let n;try{n=JSON.parse(this.handshakeBuffer.slice(0,r))}catch{this.fail(e,"Blender sent an invalid handshake.");return}if(typeof n!=="object"||n===null||!("type"in n)||n.type!=="hello"||!("protocol"in n)||n.protocol!==Bi){this.fail(e,"The Blender add-on uses an incompatible protocol.");return}this.clearConnectTimer(),this.handshakeBuffer="";let i={state:"connected",message:"Live in Blender"};this.setStatus(i),this.sendSnapshot(this.document()),this.finishConnect(this.getStatus())}handleClose(e){if(this.socket!==e)return;this.socket=null,this.clearConnectTimer(),this.resetStream();let t=this.status.state==="connecting"?{state:"error",message:"Blender closed the connection during setup."}:{state:"disconnected",message:"Blender disconnected."};this.setStatus(t),this.finishConnect(t)}sendSnapshot(e){if(this.patchTimer)clearTimeout(this.patchTimer);this.patchTimer=null,this.pendingCells.clear();let{message:t,state:r}=VA(e);if(this.previousGrid=r,this.previousColumns=t.columns,this.previousRows=t.rows,!this.send(t))this.previousGrid=null}flushPatch(){if(this.patchTimer=null,this.backpressured)return;if(this.dirty=!1,this.status.state==="connected"&&this.socket)this.collectChanges();if(this.status.state!=="connected"||this.pendingCells.size===0){this.pendingCells.clear();return}let e={protocol:Bi,type:"patch",columns:this.previousColumns,rows:this.previousRows,cells:[...this.pendingCells.values()]};if(this.pendingCells.clear(),!this.send(e))this.previousGrid=null}send(e){let t=this.socket;if(!t||this.status.state!=="connected")return!1;if(!t.writable)return this.fail(t,"Blender connection is no longer writable."),!1;let r=Buffer.from(`${JSON.stringify(e)}
11
+ `);if(r.length>KA)return this.fail(t,"Artwork exceeds the Blender message size limit."),!1;try{return this.backpressured=t.write(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))===!1,!0}catch{return this.fail(t,"Could not send artwork to Blender."),!1}}fail(e,t){if(this.socket!==e)return;this.socket=null,this.clearConnectTimer(),this.resetStream(),e.destroy();let r={state:"error",message:t};this.setStatus(r),this.finishConnect(r)}disconnectSocket(){let e=this.socket;this.socket=null,this.clearConnectTimer(),e?.destroy()}resetStream(){if(this.backpressured=!1,this.dirty=!1,this.patchTimer)clearTimeout(this.patchTimer);this.patchTimer=null,this.previousGrid=null,this.previousColumns=0,this.previousRows=0,this.pendingCells.clear()}clearConnectTimer(){if(this.connectTimer)clearTimeout(this.connectTimer);this.connectTimer=null}finishConnect(e){this.resolveConnect?.({...e}),this.resolveConnect=null,this.connectPromise=null}setStatus(e){this.status=e;for(let t of this.listeners)t({...e})}}import{NativeImage as ac,parseColor as Oo}from"@opentui/core";import{parseColor as $A,Renderable as XA,RGBA as zA}from"@opentui/core";var To=new WeakMap;function Et(e){let t=e.terminalWidth??e.width,r=e.terminalHeight??e.height,n=e.resolution;if(!n||t<=0||r<=0||n.width<=0||n.height<=0)return To.get(e)??null;let i=n.width/t,s=n.height/r,o=To.get(e);if(o&&o.width===i&&o.height===s)return o;let a=Number.isFinite(i)&&Number.isFinite(s)&&i>0&&s>0?{width:i,height:s}:null;if(a)To.set(e,a);return a??o??null}function Ni(e){let t=Et(e);if(!t)return 2;let r=t.height/t.width;return Number.isFinite(r)&&r>=0.5&&r<=4?r:2}function ur(e){if(!e||e.image_protocol==="blocks")return!1;if(e.image_protocol==="kitty"||e.image_protocol==="sixel")return!0;if(e.multiplexer==="tmux")return!1;return Boolean(e.kitty_graphics||e.sixel)}function Li(e){return Boolean(Et(e)&&ur(e.capabilities))}var qA={width:8,height:16};function eg(e,t,r,n,i,s,o="center"){let a=Math.max(1,Math.round(e*i)),l=Math.max(1,Math.round(t*s)),c=Math.min(a/r,l/n),u=Math.max(1,Math.min(a,Math.round(r*c))),d=Math.max(1,Math.min(l,Math.round(n*c)));return{pixelWidth:a,pixelHeight:l,fittedWidth:u,fittedHeight:d,left:o==="center"?Math.floor((a-u)/2):0,top:Math.floor((l-d)/2)}}class Gn extends XA{_source=null;_background=zA.fromInts(0,0,0);_backgroundKey="";_kernel="default";_align="center";frame=null;frameCache=null;constructor(e,t){super(e,{...t,buffered:!0});if(this._source=t.source??null,t.background)this.background=t.background;if(t.kernel)this._kernel=t.kernel;if(t.align)this._align=t.align}set source(e){let t=e??null;if(t===this._source)return;this._source=t,this.releaseFrame(),this.requestRender()}get source(){return this._source}set background(e){if(!e||e===this._backgroundKey)return;this._backgroundKey=e,this._background=$A(e),this.releaseFrame(),this.requestRender()}set kernel(e){if(!e||e===this._kernel)return;this._kernel=e,this.releaseFrame(),this.requestRender()}set align(e){if(!e||e===this._align)return;this._align=e,this.releaseFrame(),this.requestRender()}renderSelf(e){e.clear(this._background);let t=this._source;if(!t||this.width<=0||this.height<=0||!ur(this._ctx.capabilities)){this.releaseFrame();return}let r=Et(this._ctx)??qA,n=eg(this.width,this.height,t.width,t.height,r.width,r.height,this._align),i=this._backgroundKey,s=this.frameCache;if(!(this.frame&&s&&s.source===t&&s.pixelWidth===n.pixelWidth&&s.pixelHeight===n.pixelHeight&&s.background===i)){let a=t.resize({width:n.fittedWidth,height:n.fittedHeight,kernel:this._kernel}),l=a.extend({left:n.left,top:n.top,right:n.pixelWidth-n.fittedWidth-n.left,bottom:n.pixelHeight-n.fittedHeight-n.top,background:this._background.toInts()});if(l!==a)a.dispose();this.releaseFrame(),this.frame=l,this.frameCache={source:t,pixelWidth:n.pixelWidth,pixelHeight:n.pixelHeight,background:i}}if(!this.frame)return;e.drawImage(this.frame,0,0,this.width,this.height,n.pixelWidth,n.pixelHeight,0,0,n.pixelWidth,n.pixelHeight,"auto")}releaseFrame(){this.frame?.dispose(),this.frame=null,this.frameCache=null}destroySelf(){this.releaseFrame(),super.destroySelf()}}var oc=new WeakMap;function Xr(){let e=gt(),t=oc.get(e);if(t)return t;let r=pr(()=>{let[n,i]=Y(ur(e.capabilities));return e.on("capabilities",()=>i(ur(e.capabilities))),n});return oc.set(e,r),r}Yt({fitted_image:Gn});var Bo=32;function tg(e){let[t,r,n]=Oo(e).toInts();return ac.fromRgba(new Uint8Array([t,r,n,255]),1,1)}function rg(e,t,r=Bo){let n=Oo(e).toInts(),i=Oo(t).toInts(),s=new Uint8Array(r*r*4),o=r/2;for(let a=0;a<r;a++)for(let l=0;l<r;l++){let c=Math.hypot(l+0.5-o,a+0.5-o),u=Math.max(0,Math.min(1,o-c+0.5)),d=(a*r+l)*4;for(let f=0;f<3;f++)s[d+f]=Math.round(i[f]+(n[f]-i[f])*u);s[d+3]=255}return s}var Fi=new Map;function ng(e,t){let r=`${e}|${t}`,n=Fi.get(r);if(!n){if(Fi.size>=256)Fi.clear();n=rg(e,t),Fi.set(r,n)}return ac.fromRgba(n,Bo,Bo)}function Un(e){let t=Xr(),r=()=>e.width??2,n=()=>e.shape??"square",i=J(()=>{let s=n()==="circle"?ng(e.color,e.background):tg(e.color);return je(()=>s.dispose()),s});return Z(Ie,{get when(){return t()},get fallback(){return(()=>{var s=I("text");return L(s,(()=>{var o=ut(()=>n()==="circle");return()=>o()?"\u2B24":"\u2588".repeat(r())})()),he((o)=>h(s,"fg",e.color,o)),s})()},get children(){var s=I("fitted_image");return h(s,"height",1),h(s,"align","start"),he((o)=>{var a=r(),l=i(),c=e.background,u=n()==="circle"?"default":"nearest";return a!==o.e&&(o.e=h(s,"width",a,o.e)),l!==o.t&&(o.t=h(s,"source",l,o.t)),c!==o.a&&(o.a=h(s,"background",c,o.a)),u!==o.o&&(o.o=h(s,"kernel",u,o.o)),o},{e:void 0,t:void 0,a:void 0,o:void 0}),s}})}function lc(e,t,r,n=3){for(let i=n;i>1;i--)if(e*i<=t&&Math.ceil(e*i/2)<=r)return i;return 1}import{existsSync as og,statSync as ag}from"fs";import{homedir as lg}from"os";import{basename as cg,join as ug,resolve as Po}from"path";import{deflateSync as dg}from"zlib";var Vt=Math.PI/4,dr=Math.asin(1/Math.sqrt(3)),ig=1,sg=2500000;function cc(e,t,r,n,i={}){let{density:s=ig,maxPixels:o=sg}=i,a=Math.max(1,Math.round(e*r*s)),l=Math.max(1,Math.round(t*n*s)),c=Math.min(1,2560/Math.max(a,l),Math.sqrt(o/(a*l)));return{width:Math.max(1,Math.round(a*c)),height:Math.max(1,Math.round(l*c))}}function Gi(e){let t=e.length,r=e.reduce((i,s)=>Math.max(i,s.length),0),n=[];for(let i=0;i<t;i+=1)for(let s=0;s<e[i].length;s+=1){let o=e[i][s];if(!o.active||!o.color)continue;let{primary:a,mirrored:l}=xn(o.depth,o.mirrorZ),c=s-(r-1)/2,u=i-(t-1)/2;if(n.push({x:c,y:a/2,z:u,height:a,color:o.color}),l>0)n.push({x:c,y:-l/2,z:u,height:l,color:o.color})}return n}function uc(e=process.platform,t=process.arch){if(e==="linux")return t==="x64";if(e==="win32")return t==="x64";return e==="darwin"&&(t==="x64"||t==="arm64")}var Mt=["svg","obj","png"],hg=512,fg=512,Ag=new Uint8Array([137,80,78,71,13,10,26,10]);function dc(e){return Mt.includes(e)}function Hn(e,t){return(e??Pi(t,"untitled")).replace(/\.flatblox\.json$/i,"").replace(/\.json$/i,"")}function Ui(e,t,r){let n=e.trim();if(!n)return Po(r);let i=n.startsWith("~/")?ug(lg(),n.slice(2)):n;if(/[\\/]$/.test(i)||og(i)&&ag(i).isDirectory())return Po(i,Pi(t,"untitled"));return Po(Hn(i,i).replace(/\.(svg|obj|mtl|png)$/i,""))}function hc(e){return e.reduce((t,r)=>Math.max(t,r.length),0)}function fc(e,t,r){let n=r/Math.max(1,e,t);return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}}function Ac(e){return e.active&&!!e.color}function gg(e){let t=e.length,r=hc(e),n=[];for(let o=0;o<t;o++)for(let a=0;a<e[o].length;a++){let l=e[o][a];if(Ac(l))n.push(So("normal",l.color,a,o))}let{width:i,height:s}=fc(r,t,hg);return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${r} ${t}" width="${i}" height="${s}" shape-rendering="crispEdges">${n.join("")}</svg>`}function mg(e,t){let r=cr(e);return`color_${r?[r.r,r.g,r.b].map((i)=>i.toString(16).padStart(2,"0")).join(""):String(t)}_${t}`}function Cr(e){return Number(e.toFixed(4)).toString()}function pg(e,t){let r=Gi(e),n=new Map,i=[`mtllib ${t}`],s=[],o=0;for(let a of r){let l=n.get(a.color);if(!l){l=mg(a.color,n.size),n.set(a.color,l);let w=cr(a.color)??{r:255,g:255,b:255},p=Pt(a.color)?.a??1;s.push(`newmtl ${l}`,`Kd ${Cr(w.r/255)} ${Cr(w.g/255)} ${Cr(w.b/255)}`,...p<1?[`d ${Cr(p)}`]:[],"")}let c=a.x-0.5,u=a.x+0.5,d=a.y-a.height/2,f=a.y+a.height/2,g=a.z-0.5,A=a.z+0.5,m=[[c,d,g],[u,d,g],[u,f,g],[c,f,g],[c,d,A],[u,d,A],[u,f,A],[c,f,A]];for(let[w,p,C]of m)i.push(`v ${Cr(w)} ${Cr(p)} ${Cr(C)}`);let b=[[4,3,2,1],[5,6,7,8],[1,2,6,5],[8,7,3,4],[2,3,7,6],[1,5,8,4]];i.push(`usemtl ${l}`);for(let w of b)i.push(`f ${w.map((p)=>p+o).join(" ")}`);o+=8}return{obj:`${i.join(`
12
12
  `)}
13
13
  `,mtl:`${s.join(`
14
14
  `)}
15
- `}}function wo(e,t){let r=new Uint8Array(12+t.length),n=new DataView(r.buffer);return n.setUint32(0,t.length),r.set(new TextEncoder().encode(e),4),r.set(t,8),n.setUint32(8+t.length,Bun.hash.crc32(r.subarray(4,8+t.length))),r}function Wf(e,t=vo){let r=e.length,i=Zl(e)*t,s=r*t,o=i*4+1,a=new Uint8Array(o*s);for(let f=0;f<r;f++)for(let g=0;g<e[f].length;g++){let m=e[f][g];if(!Xl(m))continue;let p=Jt(m.color);if(!p)continue;for(let v=0;v<t;v++){let y=(f*t+v)*o+1;for(let E=0;E<t;E++){let _=y+(g*t+E)*4;a[_]=p.r,a[_+1]=p.g,a[_+2]=p.b,a[_+3]=Math.round(p.a*255)}}}let l=new Uint8Array(13),c=new DataView(l.buffer);c.setUint32(0,i),c.setUint32(4,s),l[8]=8,l[9]=6;let u=[Uf,wo("IHDR",l),wo("IDAT",new Uint8Array(Gf(a))),wo("IEND",new Uint8Array(0))],d=new Uint8Array(u.reduce((f,g)=>f+g.length,0)),A=0;for(let f of u)d.set(f,A),A+=f.length;return d}function Yf(e,t,r=Tt){let n=[],{saturation:i,lightness:s}=e.paletteColorAdjustment??{saturation:0,lightness:0},o=Qt(e.grid,i,s);for(let a of r)if(a==="svg")n.push({path:`${t}.svg`,content:Hf(o)});else if(a==="obj"){let l=`${t}.mtl`,{obj:c,mtl:u}=Kf(o,Lf(l));n.push({path:`${t}.obj`,content:c}),n.push({path:l,content:u})}else n.push({path:`${t}.png`,content:Wf(o)});return n}async function Bi(e,t,r=Tt,n=(i,s)=>Bun.write(i,s)){let i=Yf(e,t,r);for(let s of i)await n(s.path,s.content);return i.map((s)=>s.path)}import{mkdir as Qf,readFile as Jf,writeFile as Vf}from"fs/promises";import{homedir as $f}from"os";import{dirname as Zf,join as zl}from"path";function ql(e=process.env){if(e.FLATBLOX_TUI_EXPORT_FILE)return e.FLATBLOX_TUI_EXPORT_FILE;let t=e.XDG_CONFIG_HOME||zl($f(),".config");return zl(t,"flatblox","tui-export.json")}async function ec(e=ql()){try{let t=JSON.parse(await Jf(e,"utf8")),r=typeof t==="object"&&t!==null?t.directory:void 0;return typeof r==="string"&&r.length>0?r:null}catch{return null}}async function tc(e,t=ql()){await Qf(Zf(t),{recursive:!0,mode:448}),await Vf(t,`${JSON.stringify({directory:e},null,2)}
16
- `)}function or(e){let t=e.name.toLowerCase();return t==="return"||t==="enter"||t==="space"||e.sequence===" "}function wr(e){switch(e){case"left":case"h":return{dx:-1,dy:0};case"right":case"l":return{dx:1,dy:0};case"up":case"k":return{dx:0,dy:-1};case"down":case"j":return{dx:0,dy:1};default:return}}import{MouseButton as _o,NativeImage as nc,parseColor as og,Renderable as ag,RGBA as Un,TextAttributes as ic}from"@opentui/core";import{RGBA as Xf}from"@opentui/core";var zf={r:76,g:76,b:76,a:1},qf={r:96,g:96,b:96,a:1},rc=new Map;function eg(e){let t=rc.get(e);if(t!==void 0)return t;let r=Jt(e);return rc.set(e,r),r}function tg(e,t){return(e+t)%2===0?zf:qf}function rg(e,t){let r=Math.max(0,Math.min(1,e.a));return{r:Math.round(e.r*r+t.r*(1-r)),g:Math.round(e.g*r+t.g*(1-r)),b:Math.round(e.b*r+t.b*(1-r)),a:1}}function ng(e,t,r){let n=tg(t,r),i=e?.active&&e.color?eg(e.color):null;return i?rg(i,n):n}var ig=[new Map,new Map],sg=4096;function ar(e,t,r){let n=ig[(t+r)%2],i=e?.active&&e.color?e.color:"",s=n.get(i);if(!s){if(n.size>=sg)n.clear();let o=ng(e,t,r);s=Xf.fromInts(o.r,o.g,o.b),n.set(i,s)}return s}var Oi=Un.fromInts(22,8,33),sc=Un.fromInts(33,22,41),Co=4,lg=Un.fromInts(255,255,255),cg=Un.fromInts(8,10,16),ug=0.25,Pi=512,oc=16384,dg=25000000;function ac(e,t){if(!e||e.points.length===0)return null;let r=new Set;for(let n of e.points)r.add(n.y*t+n.x);return{cells:r,color:og(e.color)}}function xo(e){let[t,r,n]=e.toInts(),i=(0.2126*t+0.7152*r+0.0722*n)/255,[s,o,a]=i>0.55?cg.toInts():lg.toInts(),l=(c,u)=>Math.round(c+(u-c)*ug);return Un.fromInts(l(t,s),l(r,o),l(n,a))}function lc(e,t,r){return Math.max(0,Math.min(r-t,e-Math.floor(t/2)))}function hg(e,t){let r=Math.ceil(e/Pi)*Pi,n=Math.ceil(t/Pi)*Pi;if(r>oc||n>oc||r*n>dg)return null;return{width:r,height:n}}function Ag(e,t,r,n,i){let o=Math.max(1,Math.floor(n)),a=Math.max(1,Math.round(o*2/i)),l=Math.min(r,Math.floor(e/o)),c=Math.min(r,Math.floor(t*2/a)),u=l*o,d=c*a;return{columns:l,pixelRows:c,columnZoom:o,subrowZoom:a,renderedColumns:u,renderedSubrows:d,terminalRows:Math.ceil(d/2)}}function fg(e,t,r,n,i,s){let o=Math.max(1,Math.floor(n)),a=Math.max(1,Math.round(o*i)),l=Math.min(r,Math.floor(e/o)),c=Math.min(r,Math.floor(t*s/a)),u=l*a,d=c*a,A=d*2/s;return{columns:l,pixelRows:c,columnZoom:o,subrowZoom:a*2/s,renderedColumns:l*o,renderedSubrows:A,terminalRows:Math.ceil(d/s),pixelWidth:u,pixelHeight:d}}class Eo extends ag{textFrame=null;artworkImage=null;artworkImageCache=null;worldImage=null;worldImageSide=0;worldImageWidth=0;worldImageHeight=0;currentModel={grid:[],cursor:{x:0,y:0},zoom:1};cellHandler;viewport={originX:0,originY:0,startX:0,startY:0,columns:0,pixelRows:0,columnZoom:1,subrowZoom:1,renderedSubrows:0};constructor(e,t){super(e,{...t,buffered:!0});if(t.model)this.currentModel=t.model;this.cellHandler=t.onCell,this.onMouseDown=(r)=>this.handleMouse(r)}set model(e){if(!e)return;this.currentModel=e,this.requestRender()}set onCell(e){this.cellHandler=e}sameTextFrame(e){let t=this.currentModel,r=this.textFrame;if(r&&r.grid===t.grid&&r.revision===t.revision&&r.preview===t.preview&&r.cursorX===t.cursor.x&&r.cursorY===t.cursor.y&&r.zoom===t.zoom&&r.width===this.width&&r.height===this.height&&r.cellAspect===e)return!0;return this.textFrame={grid:t.grid,revision:t.revision,preview:t.preview,cursorX:t.cursor.x,cursorY:t.cursor.y,zoom:t.zoom,width:this.width,height:this.height,cellAspect:e},!1}renderSelf(e){let t=this.currentModel.grid.length,r=Ii(this._ctx),n=xt(this._ctx),i=n!==null&&ki(this._ctx);if(i)this.textFrame=null;else if(this.sameTextFrame(r))return;if(e.clear(Oi),t===0||this.width<=0||this.height<=0){this.viewport.columns=0,this.viewport.pixelRows=0;return}let s=n&&i?fg(this.width,this.height,t,this.currentModel.zoom,n.width,n.height):null,o=s??Ag(this.width,this.height,t,this.currentModel.zoom,r),{columns:a,pixelRows:l}=o;if(a===0||l===0){this.viewport.columns=0,this.viewport.pixelRows=0,this.viewport.columnZoom=o.columnZoom,this.viewport.subrowZoom=o.subrowZoom,this.viewport.renderedSubrows=0;return}let{renderedColumns:c,renderedSubrows:u,terminalRows:d}=o,A=lc(this.currentModel.cursor.x,a,t),f=lc(this.currentModel.cursor.y,l,t),g=Math.floor((this.width-c)/2),m=Math.floor((this.height-d)/2);if(s&&n){if(!this.drawWorldGridImage(e,g,m,n.width,n.height))this.drawWorldGrid(e,g,m,r)}else this.releaseWorldImage(),this.drawWorldGrid(e,g,m,r);if(this.viewport={originX:g,originY:m,startX:A,startY:f,columns:a,pixelRows:l,columnZoom:o.columnZoom,subrowZoom:o.subrowZoom,renderedSubrows:u},s){this.drawArtworkImage(e,s,g,m,A,f);return}this.releaseArtworkImage();let{grid:p,cursor:v}=this.currentModel,y=ac(this.currentModel.preview,t),{subrowZoom:E,columnZoom:_}=o;for(let b=0;b<d;b++){let w=b*2,C=w+1,O=f+Math.floor(w/E),N=f+Math.floor(C/E),P=p[O],R=p[N];for(let U=0;U<c;U++){let X=A+Math.floor(U/_),V=y?.cells.has(O*t+X)?y.color:ar(P?.[X],X,O),te=C<u&&N<t?y?.cells.has(N*t+X)?y.color:ar(R?.[X],X,N):Oi,ge=v.x===X&&v.y===O,z=v.x===X&&v.y===N;e.setCell(g+U,m+b,"\u2580",ge?xo(V):V,z?xo(te):te)}}}drawArtworkImage(e,t,r,n,i,s){let o=this.currentModel.cursor,a=this.artworkImageCache;if(!(this.artworkImage&&a&&a.grid===this.currentModel.grid&&a.revision===this.currentModel.revision&&a.preview===this.currentModel.preview&&a.columns===t.columns&&a.pixelRows===t.pixelRows&&a.pixelWidth===t.pixelWidth&&a.pixelHeight===t.pixelHeight&&a.startX===i&&a.startY===s&&a.cursorX===o.x&&a.cursorY===o.y)){let c=this.currentModel.grid.length,u=ac(this.currentModel.preview,c),d=new Uint8Array(t.columns*t.pixelRows*4);for(let g=0;g<t.pixelRows;g++){let m=s+g;for(let p=0;p<t.columns;p++){let v=i+p,y=u?.cells.has(m*c+v)?u.color:ar(this.currentModel.grid[m]?.[v],v,m);if(o.x===v&&o.y===m)y=xo(y);let[E,_,b]=y.toInts(),w=(g*t.columns+p)*4;d[w]=E,d[w+1]=_,d[w+2]=b,d[w+3]=255}}let A=nc.fromRgba(d,t.columns,t.pixelRows),f=A.resize({width:t.pixelWidth,height:t.pixelHeight,kernel:"nearest"});A.dispose(),this.releaseArtworkImage(),this.artworkImage=f,this.artworkImageCache={grid:this.currentModel.grid,revision:this.currentModel.revision,preview:this.currentModel.preview,columns:t.columns,pixelRows:t.pixelRows,pixelWidth:t.pixelWidth,pixelHeight:t.pixelHeight,startX:i,startY:s,cursorX:o.x,cursorY:o.y}}if(!this.artworkImage)return;e.drawImage(this.artworkImage,r,n,t.renderedColumns,t.terminalRows,t.pixelWidth,t.pixelHeight,0,0,t.pixelWidth,t.pixelHeight,"auto")}releaseArtworkImage(){this.artworkImage?.dispose(),this.artworkImage=null,this.artworkImageCache=null}drawWorldGridImage(e,t,r,n,i){let s=Math.max(1,Math.round(this.width*n)),o=Math.max(1,Math.round(this.height*i)),a=Math.max(1,Math.round(Co*n)),l=Math.round(t*n),c=Math.round(r*i),u=s+a,d=o+a,A=hg(u,d);if(!A)return this.releaseWorldImage(),!1;if(!this.worldImage||a!==this.worldImageSide||u>this.worldImageWidth||d>this.worldImageHeight){let{width:m,height:p}=A,v=new Uint8Array(m*p*4),[y,E,_]=Oi.toInts(),[b,w,C]=sc.toInts(),O=m*4,N=new Uint8Array(O),P=new Uint8Array(O);for(let R=0;R<m;R++){let U=R*4,X=R%a===0;N[U]=X?b:y,N[U+1]=X?w:E,N[U+2]=X?C:_,N[U+3]=255,P[U]=b,P[U+1]=w,P[U+2]=C,P[U+3]=255}for(let R=0;R<p;R++)v.set(R%a===0?P:N,R*O);this.releaseWorldImage(),this.worldImage=nc.fromRgba(v,m,p),this.worldImageSide=a,this.worldImageWidth=m,this.worldImageHeight=p}if(!this.worldImage)return!1;let f=(-l%a+a)%a,g=(-c%a+a)%a;return e.drawImage(this.worldImage,0,0,this.width,this.height,s,o,f,g,s,o,"auto"),!0}releaseWorldImage(){this.worldImage?.dispose(),this.worldImage=null,this.worldImageSide=0,this.worldImageWidth=0,this.worldImageHeight=0}drawWorldGrid(e,t,r,n){let i=Math.max(1,Math.round(Co/n));for(let s=0;s<this.height;s++){let o=s+1-r,a=Math.floor(o/i)!==Math.floor((o-1)/i);for(let l=0;l<this.width;l++){let c=l>0&&(l-t)%Co===0;if(!a&&!c)continue;e.setCell(l,s,c?"\u258F":" ",sc,Oi,a?ic.UNDERLINE:ic.NONE)}}}destroySelf(){this.releaseArtworkImage(),this.releaseWorldImage(),super.destroySelf()}handleMouse(e){if(e.button!==_o.LEFT&&e.button!==_o.RIGHT)return;let t=e.x-this.screenX-this.viewport.originX,r=e.y-this.screenY-this.viewport.originY;if(t<0||t>=this.viewport.columns*this.viewport.columnZoom||r<0||r>=Math.ceil(this.viewport.renderedSubrows/2))return;let n=this.viewport.startX+Math.floor(t/this.viewport.columnZoom),i=e.modifiers.shift?1:0,s=r*2+i;if(s>=this.viewport.renderedSubrows)return;let o=this.viewport.startY+Math.floor(s/this.viewport.subrowZoom);if(o>=this.currentModel.grid.length)return;this.cellHandler?.({x:n,y:o,...e.button===_o.RIGHT?{tool:"erase"}:{}})}}import{RGBA as Cg}from"@opentui/core";import{SuperSampleType as xg,ThreeRenderable as Eg}from"@opentui/three";import{appendFileSync as gg}from"fs";var cc=process.env.FLATBLOX_TUI_TIMING;function vr(e,t){if(!cc)return;let r=(performance.now()-t).toFixed(0);gg(cc,`${e} ${r}ms
17
- `)}import{RGBA as mg}from"@opentui/core";var So="Loading voxel preview\u2026",pg=mg.fromInts(175,129,202);function Di(e,t,r,n){if(t<1||r<1)return;let i=t>=So.length?So:So.slice(0,t),s=Math.max(0,Math.floor((t-i.length)/2)),o=Math.floor((r-1)/2);e.drawText(i,s,o,pg,n)}import{THREE as Ce}from"@opentui/three";var bg=1.12,yg=[0.76,0.64,1,0.42,0.9,0.72],uc=128,wg=2,dc=6710886,vg=new Uint8Array([76,76,76,255,96,96,96,255,96,96,96,255,76,76,76,255]);function _g(e,t){let r=[];for(let n of yg){let i=t?n**2.2:n;for(let s=0;s<4;s+=1)r.push(i,i,i)}e.setAttribute("color",new Ce.Float32BufferAttribute(r,3))}class Hn{scene=new Ce.Scene;camera=new Ce.OrthographicCamera(-1,1,1,-1,0.1,1000);boxGeometry=new Ce.BoxGeometry(1,1,1);boxMaterial;sceneHalfExtents=new Ce.Vector3(2,2,2);groundGeometry;groundMaterial;groundTexture;ground;worldGrid;mesh=null;model;aspect=1;sceneCenterY=0;constructor(e,t){if(this.model=e,_g(this.boxGeometry,t==="raster"),this.boxMaterial=new Ce.MeshBasicMaterial({toneMapped:!1,vertexColors:!0}),t==="raster"){this.groundGeometry=new Ce.PlaneGeometry(1,1),this.groundTexture=new Ce.DataTexture(vg,2,2),this.groundTexture.colorSpace=Ce.SRGBColorSpace,this.groundTexture.magFilter=Ce.NearestFilter,this.groundTexture.minFilter=Ce.NearestFilter,this.groundTexture.wrapS=Ce.RepeatWrapping,this.groundTexture.wrapT=Ce.RepeatWrapping,this.groundTexture.needsUpdate=!0,this.groundMaterial=new Ce.MeshBasicMaterial({map:this.groundTexture,toneMapped:!1}),this.ground=new Ce.Mesh(this.groundGeometry,this.groundMaterial),this.ground.rotation.x=-Math.PI/2,this.scene.add(this.ground),this.worldGrid=new Ce.GridHelper(uc,uc/wg,dc,dc);let r=Array.isArray(this.worldGrid.material)?this.worldGrid.material:[this.worldGrid.material];for(let n of r)n.toneMapped=!1,n.transparent=!0,n.opacity=0.06;this.scene.add(this.worldGrid)}this.rebuildMesh(),this.updateCamera()}update(e,t=this.aspect){let r=e.grid!==this.model.grid||e.revision!==this.model.revision;if(this.model=e,this.aspect=Math.max(0.25,t),r)this.rebuildMesh();this.updateCamera()}setAspect(e){this.aspect=Math.max(0.25,e),this.updateCamera()}dispose(){this.scene.clear(),this.mesh=null}rebuildMesh(){if(this.mesh)this.scene.remove(this.mesh);let e=Ri(this.model.grid),t=this.model.grid.length,r=this.model.grid.reduce((l,c)=>Math.max(l,c.length),0),n=e.reduce((l,c)=>Math.min(l,c.y-c.height/2),0),i=e.reduce((l,c)=>Math.max(l,c.y+c.height/2),0);if(this.sceneHalfExtents.set(Math.max(1,r)/2,Math.max(1,i-n)/2,Math.max(1,t)/2),this.sceneCenterY=(n+i)/2,this.ground)this.ground.position.y=n-0.04,this.ground.scale.set(Math.max(1,r),Math.max(1,t),1),this.groundTexture?.repeat.set(Math.max(1,r)/2,Math.max(1,t)/2);if(this.worldGrid)this.worldGrid.position.y=n-0.08;if(e.length===0){this.mesh=null;return}let s=new Ce.InstancedMesh(this.boxGeometry,this.boxMaterial,e.length),o=new Ce.Object3D,a=new Ce.Color;for(let l=0;l<e.length;l+=1){let c=e[l];o.position.set(c.x,c.y,c.z),o.scale.set(1,c.height,1),o.updateMatrix(),s.setMatrixAt(l,o.matrix);let u=nr(c.color)??{r:255,g:255,b:255};s.setColorAt(l,a.setRGB(u.r/255,u.g/255,u.b/255,Ce.SRGBColorSpace))}if(s.instanceMatrix.needsUpdate=!0,s.instanceColor)s.instanceColor.needsUpdate=!0;this.scene.add(s),this.mesh=s}updateCamera(){let e=new Ce.Vector3(Math.sin(this.model.yaw)*Math.cos(this.model.pitch),Math.sin(this.model.pitch),Math.cos(this.model.yaw)*Math.cos(this.model.pitch)),t=new Ce.Vector3(0,this.sceneCenterY,0);this.camera.position.copy(t).addScaledVector(e,100),this.camera.lookAt(t);let r=new Ce.Vector3(Math.sin($t)*Math.cos(sr),Math.sin(sr),Math.cos($t)*Math.cos(sr)),n=new Ce.Vector3(Math.cos($t),0,-Math.sin($t)),i=r.clone().cross(n).normalize(),s=Math.abs(n.x)*this.sceneHalfExtents.x+Math.abs(n.z)*this.sceneHalfExtents.z,o=Math.abs(i.x)*this.sceneHalfExtents.x+Math.abs(i.y)*this.sceneHalfExtents.y+Math.abs(i.z)*this.sceneHalfExtents.z,a=Math.sqrt(2/this.model.zoom),l=Math.max(1,o,s/this.aspect)*bg*a;this.camera.left=-l*this.aspect,this.camera.right=l*this.aspect,this.camera.top=l,this.camera.bottom=-l,this.camera.updateProjectionMatrix()}}function Ni(){return{grid:[],yaw:$t,pitch:sr,zoom:1}}var hc=Cg.fromInts(22,8,33),Sg=250;class Io extends Eg{currentModel;sceneController;initErrorHandler;rendererReady=!1;firstFrameDrawn=!1;destroyRequested=!1;sceneDisposed=!1;constructor(e,t){let{model:r,onInitError:n,renderer:i,...s}=t,o=r??Ni(),a=new Hn(o,"terminal");super(e,{...s,scene:a.scene,camera:a.camera,autoAspect:!1,live:!1,renderer:{backgroundColor:hc,superSample:xg.GPU,...i}});this.currentModel=o,this.sceneController=a,this.initErrorHandler=n,this.sceneController.setAspect(this.aspectRatio),setTimeout(()=>void this.warmUp(),Sg);let l=this.renderer.drawScene.bind(this.renderer);this.renderer.drawScene=async(...u)=>{if(await l(...u),!this.firstFrameDrawn)this.firstFrameDrawn=!0,this.requestRender()};let c=this.renderer.init.bind(this.renderer);this.renderer.init=async()=>{try{if(await c(),this.rendererReady=!0,this.destroyRequested)this.disposeScene()}catch(u){let d=u instanceof Error?u.message:String(u);throw this.initErrorHandler?.(d),u}}}async warmUp(){if(this.destroyRequested)return;let e=performance.now(),r=await this.ensureInitialized();if(vr("voxel preview init",e),!r||this.destroyRequested||!this.sceneController)return;let n=this.renderer,i=performance.now();await n.threeRenderer?.render(this.sceneController.scene,this.sceneController.camera),vr("voxel preview first render",i)}get model(){return this.currentModel}set model(e){this.currentModel=e,this.sceneController?.update(e,this.aspectRatio),this.requestRender()}set onInitError(e){this.initErrorHandler=e}renderSelf(e,t){if(super.renderSelf(e,t),!this.firstFrameDrawn&&this.visible)Di(e,this.width,this.height,hc)}onResize(e,t){super.onResize(e,t),this.sceneController?.setAspect(this.aspectRatio)}destroySelf(){if(this.destroyRequested=!0,super.destroySelf(),this.rendererReady)this.disposeScene()}disposeScene(){if(this.sceneDisposed)return;this.sceneDisposed=!0,this.sceneController?.dispose()}}import{NativeImage as Ig,Renderable as kg,RGBA as Rg}from"@opentui/core";import{CLICanvas as Tg,SuperSampleType as Bg,THREE as Mi}from"@opentui/three";import{createWebGPUDevice as Og,setupGlobals as Pg}from"bun-webgpu";import{WebGPURenderer as Dg}from"three/webgpu";var Li=[22,8,33],Ac=Rg.fromInts(...Li),Ng=250,fc=64,Mg=250,Lg=150,Fg=0.4;class ko extends kg{currentModel;sceneController;initErrorHandler;frame=null;device=null;canvas=null;context=null;webgpuRenderer=null;readbackBuffer=null;readbackSize=0;renderWidth=0;renderHeight=0;pending=!1;scheduled=!1;rendering=!1;failed=!1;destroyRequested=!1;warmedUp=!1;lowDetail=!1;lastModelUpdate=0;refineTimer=null;constructor(e,t){let{model:r,onInitError:n,...i}=t;super(e,{...i,buffered:!0,live:!1});this.currentModel=r??Ni(),this.sceneController=new Hn(this.currentModel,"raster"),this.initErrorHandler=n,this.scheduleRender(),setTimeout(()=>void this.warmUp(),Ng)}async warmUp(){if(this.warmedUp||this.rendering||this.failed||this.destroyRequested)return;this.rendering=!0;try{if(await this.ensureRenderer(fc,fc),this.destroyRequested)return;this.sceneController.update(this.currentModel,1);let e=performance.now();await this.webgpuRenderer.render(this.sceneController.scene,this.sceneController.camera),vr("voxel raster first render",e),this.warmedUp=!0}catch(e){this.failed=!0;let t=e instanceof Error?e.message:String(e);this.initErrorHandler?.(t)}finally{if(this.rendering=!1,this.destroyRequested)this.releaseGpu();else if(this.pending)this.scheduleRender()}}get model(){return this.currentModel}set model(e){this.currentModel=e;let t=performance.now();if(this.lowDetail=t-this.lastModelUpdate<Mg,this.lastModelUpdate=t,this.refineTimer)clearTimeout(this.refineTimer);this.refineTimer=setTimeout(()=>{if(this.refineTimer=null,!this.lowDetail)return;this.lowDetail=!1,this.scheduleRender()},Lg),this.scheduleRender()}set onInitError(e){this.initErrorHandler=e}renderSelf(e){e.clear(Ac);let t=this.frame,r=xt(this._ctx);if(!t||!r||!ir(this._ctx.capabilities)){if(!t&&!this.failed)Di(e,this.width,this.height,Ac);return}let n=Math.max(1,Math.round(this.width*r.width)),i=Math.max(1,Math.round(this.height*r.height));e.drawImage(t,0,0,this.width,this.height,n,i,0,0,t.width,t.height,"auto")}onResize(e,t){if(super.onResize(e,t),this.sceneController)this.scheduleRender()}set visible(e){if(super.visible=e,e&&this.pending)this.scheduleRender()}get visible(){return super.visible}destroySelf(){if(this.destroyRequested=!0,this.refineTimer)clearTimeout(this.refineTimer);if(this.releaseFrame(),!this.rendering)this.releaseGpu();super.destroySelf()}scheduleRender(){if(this.pending=!0,this.scheduled||this.rendering||this.failed||this.destroyRequested||!this.visible&&this.warmedUp)return;this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,this.flushRender()})}async flushRender(){if(this.rendering||this.failed||this.destroyRequested)return;this.rendering=!0;try{while(this.pending&&!this.destroyRequested){if(!this.visible&&this.warmedUp)break;this.pending=!1,await this.renderFrame(),this.warmedUp=!0}}catch(e){this.failed=!0;let t=e instanceof Error?e.message:String(e);this.initErrorHandler?.(t)}finally{if(this.rendering=!1,this.destroyRequested)this.releaseGpu();else if(this.pending)this.scheduleRender()}}dimensions(){let e=xt(this._ctx);if(!e||this.width<=0||this.height<=0)return null;return Jl(this.width,this.height,e.width,e.height,this.lowDetail?{density:Fg}:void 0)}async renderFrame(){let e=this.dimensions();if(!e)return;if(await this.ensureRenderer(e.width,e.height),this.destroyRequested)return;this.resizeRenderer(e.width,e.height),this.sceneController.update(this.currentModel,e.width/e.height),await this.webgpuRenderer.render(this.sceneController.scene,this.sceneController.camera);let t=await this.captureFrame(e.width,e.height);if(!t)return;this.releaseFrame(),this.frame=t,this.requestRender()}async ensureRenderer(e,t){if(this.webgpuRenderer)return;let r=performance.now();await Pg();let n=await Og();vr("voxel raster device",r);let i=new Tg(n,e,t,Bg.NONE),s=new Dg({canvas:i,device:n,alpha:!0});s.outputColorSpace=Mi.SRGBColorSpace,s.toneMapping=Mi.NoToneMapping,s.setClearColor(new Mi.Color().setRGB(Li[0]/255,Li[1]/255,Li[2]/255,Mi.SRGBColorSpace),1),s.setSize(e,t,!1),await s.init(),vr("voxel raster renderer init",r),this.device=n,this.canvas=i,this.context=i.getContext("webgpu"),this.webgpuRenderer=s,this.renderWidth=e,this.renderHeight=t}resizeRenderer(e,t){if(e===this.renderWidth&&t===this.renderHeight)return;this.canvas.setSize(e,t),this.webgpuRenderer.setSize(e,t,!1),this.renderWidth=e,this.renderHeight=t,this.releaseReadback()}async captureFrame(e,t){let r=this.device,n=this.context,i=Math.ceil(e*4/256)*256,s=i*t;if(!this.readbackBuffer||this.readbackSize!==s)this.releaseReadback(),this.readbackBuffer=r.createBuffer({label:"Flatblox voxel image readback",size:s,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.readbackSize=s;let o=n.getCurrentTexture();n.switchTextures();let a=r.createCommandEncoder({label:"Flatblox voxel image capture"});if(a.copyTextureToBuffer({texture:o},{buffer:this.readbackBuffer,bytesPerRow:i,rowsPerImage:t},{width:e,height:t}),r.queue.submit([a.finish()]),await this.readbackBuffer.mapAsync(GPUMapMode.READ),this.destroyRequested)return this.readbackBuffer.unmap(),null;let l=new Uint8Array(this.readbackBuffer.getMappedRange().slice(0));this.readbackBuffer.unmap();let c=o.format,u=Ig.fromPixels(l,e,t,{stride:i,format:c==="bgra8unorm"?"bgra8":"rgba8",alpha:"opaque"});return u.ensureEncodedPng(),u}releaseFrame(){this.frame?.dispose(),this.frame=null}releaseReadback(){this.readbackBuffer?.destroy(),this.readbackBuffer=null,this.readbackSize=0}releaseGpu(){this.releaseReadback(),this.webgpuRenderer?.dispose(),this.canvas?.destroy(),this.device?.destroy(),this.webgpuRenderer=null,this.canvas=null,this.context=null,this.device=null,this.sceneController.dispose()}}var gc={name:"flatblox-tui",version:"0.2.9",description:"Flatblox pixel art editor for the terminal",homepage:"https://flatblox.com",keywords:["pixel-art","pixel art","voxel","tui","terminal","cli","editor","sprite","bun","opentui","solid","three"],author:{name:"Nico Pellerin",email:"hello@nicopellerin.io"},license:"MIT",type:"module",bin:{"flatblox-tui":"dist/index.js"},files:["dist","README.md"],publishConfig:{access:"public"},scripts:{build:"bun --env-file=../web/.env scripts/build.ts",dev:"bun --env-file=../web/.env --watch src/index.tsx",prepack:"bun run build",start:"bun --env-file=../web/.env src/index.tsx",typecheck:"tsc --noEmit",test:"bun test --preload ./scripts/preload.ts"},dependencies:{"@opentui/core":"^0.5.10","@opentui/solid":"^0.5.10","@opentui/three":"^0.5.10",bun:"^1.4.0","bun-webgpu":"0.1.7","solid-js":"1.9.12",three:"0.177.0"},devDependencies:{"@flatblox/editor-core":"workspace:*","@flatblox/shared":"workspace:*","@supabase/supabase-js":"^2.49.4","@types/bun":"latest","@types/three":"0.177.0",typescript:"~5.9.3"}};var Fi=`v${gc.version}`;import{NativeImage as mc,parseColor as Ug}from"@opentui/core";Yt({fitted_image:Ln});var Hg=new URL("./flatblox-logo.png",import.meta.url),jg=mc.load(Hg),Ro=new Map;function Kg(e){let t=Ro.get(e);if(!t)t=jg.then((r)=>{let[n,i,s]=Ug(e).toInts(),o=new Uint8Array(r.width*r.height*4);for(let l=0;l<o.length;l+=4)o[l]=n,o[l+1]=i,o[l+2]=s,o[l+3]=255;let a=mc.fromRgba(o,r.width,r.height);try{return a.composite(r)}finally{a.dispose()}}),t.catch(()=>Ro.delete(e)),Ro.set(e,t);return t}function $r(e){let t=ht(),r=Jr(),[n,i]=j(),s=!1;return gr(()=>{Kg(e.backgroundColor).then((o)=>{if(!s)i(o),t.requestRender()},()=>{})}),ot(()=>{s=!0}),Q(ke,{get when(){return lt(()=>!!r())()&&n()},get fallback(){return(()=>{var o=S("box");return h(o,"alignItems","center"),h(o,"justifyContent","center"),L(o,Q(ke,{get when(){return e.height>=2},get fallback(){return(()=>{var a=S("text"),l=S("b");return k(a,l),k(l,Re("FLATBLOX")),de((c)=>h(a,"fg",e.foregroundColor,c)),a})()},get children(){var a=S("ascii_font");return h(a,"text","FLATBLOX"),h(a,"font","tiny"),de((l)=>{var c=`${e.id}-ascii`,u=e.foregroundColor,d=e.backgroundColor;return c!==l.e&&(l.e=h(a,"id",c,l.e)),u!==l.t&&(l.t=h(a,"color",u,l.t)),d!==l.a&&(l.a=h(a,"backgroundColor",d,l.a)),l},{e:void 0,t:void 0,a:void 0}),a}})),de((a)=>{var{id:l,width:c,height:u,backgroundColor:d}=e;return l!==a.e&&(a.e=h(o,"id",l,a.e)),c!==a.t&&(a.t=h(o,"width",c,a.t)),u!==a.a&&(a.a=h(o,"height",u,a.a)),d!==a.o&&(a.o=h(o,"backgroundColor",d,a.o)),a},{e:void 0,t:void 0,a:void 0,o:void 0}),o})()},get children(){var o=S("fitted_image");return de((a)=>{var l=e.id,c=n(),u=e.width,d=e.height,A=e.backgroundColor;return l!==a.e&&(a.e=h(o,"id",l,a.e)),c!==a.t&&(a.t=h(o,"source",c,a.t)),u!==a.a&&(a.a=h(o,"width",u,a.a)),d!==a.o&&(a.o=h(o,"height",d,a.o)),A!==a.i&&(a.i=h(o,"background",A,a.i)),a},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),o}})}Yt({pixel_grid:Eo,voxel_raster:ko,voxel_preview:Io});var x={background:je("hsl(275 45% 12%)"),panel:je("hsl(275 45% 14%)"),panelActive:je("hsl(275 45% 17%)"),card:je("hsl(275 45% 19%)"),border:je("hsl(275 45% 31%)"),text:je("hsl(278 100% 80%)"),muted:je("hsl(278 41% 65%)"),accent:je("hsl(315 68% 71%)"),accentText:je("hsl(278 70% 80%)"),warning:je("hsl(37 100% 71%)"),textPink:je("hsl(308, 50%, 75%)"),orangeActive:je("hsl(28, 80%, 38%)")};function je(e){let t=nr(e);return t?En(t):"#ffffff"}function Zt(e){return e[0].toUpperCase()+e.slice(1)}function Yg(e){return(()=>{var t=S("box");return h(t,"flexDirection","column"),h(t,"gap",0),L(t,Q(wt,{get each(){return e.colors.slice(0,10)},children:(r,n)=>{let i=K(()=>(e.refresh(),e.session.selectedColorIndex===n())),s=n()===9?"0":String(n()+1);return(()=>{var o=S("box"),a=S("text"),l=Re(" ");return k(o,a),h(o,"height",1),h(o,"flexDirection","row"),h(o,"paddingX",1),L(o,Q(Fn,{get color(){return je(r)},get background(){return lt(()=>!!i())()?x.panelActive:x.panel}}),a),k(a,l),L(a,()=>i()?" \u203A ":" ",l),L(a,s,l),L(a,()=>je(r),null),de((c)=>{var u=i()?x.panelActive:x.panel,d=i()?x.text:x.muted;return u!==c.e&&(c.e=h(o,"backgroundColor",u,c.e)),d!==c.t&&(c.t=h(a,"fg",d,c.t)),c},{e:void 0,t:void 0}),o})()}})),t})()}function Qg(e){let t=K(()=>(e.refresh(),{tool:Zt(e.session.tool),mirrorX:e.session.mirrorX?"on":"off",mirrorY:e.session.mirrorY?"on":"off",cursor:`${e.session.cursor.x+1}, ${e.session.cursor.y+1}`}));return(()=>{var r=S("box"),n=S("box"),i=S("box"),s=S("text"),o=Re("Tool: "),a=S("text"),l=Re("Cursor: "),c=S("box"),u=S("box"),d=S("box"),A=S("text"),f=Re("Mirror X: "),g=S("text"),m=Re("Mirror Y: ");return k(r,n),h(r,"id","sidebar"),h(r,"flexDirection","column"),h(r,"paddingY",1),k(n,i),k(n,c),k(n,u),k(n,d),h(n,"width","100%"),h(n,"flexDirection","column"),h(n,"paddingX",1),k(i,s),k(i,a),h(i,"flexDirection","column"),k(s,o),L(s,()=>t().tool,null),k(a,l),L(a,()=>t().cursor,null),h(c,"height",1),L(n,Q(Yg,{get session(){return e.session},get colors(){return e.colors},get refresh(){return e.refresh}}),u),h(u,"height",1),k(d,A),k(d,g),h(d,"flexDirection","column"),k(A,f),L(A,()=>t().mirrorX,null),k(g,m),L(g,()=>t().mirrorY,null),de((p)=>{var v=e.visible?28:0,y=e.visible,E=x.panel,_=x.textPink,b=x.textPink,w=x.muted,C=x.muted;return v!==p.e&&(p.e=h(r,"width",v,p.e)),y!==p.t&&(p.t=h(r,"visible",y,p.t)),E!==p.a&&(p.a=h(r,"backgroundColor",E,p.a)),_!==p.o&&(p.o=h(s,"fg",_,p.o)),b!==p.i&&(p.i=h(a,"fg",b,p.i)),w!==p.n&&(p.n=h(A,"fg",w,p.n)),C!==p.s&&(p.s=h(g,"fg",C,p.s)),p},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),r})()}function Jg(e){let t=K(()=>{e.refresh();let r=`${e.session.mirrorX?"X":"-"}${e.session.mirrorY?"Y":"-"}`;return{tool:Zt(e.session.tool),color:je(e.colors[e.session.selectedColorIndex]??e.session.activeColor),mirror:r}});return(()=>{var r=S("box"),n=S("text"),i=Re("Tool "),s=Re(" Color "),o=S("text"),a=Re(" "),l=Re(" Mirror ");return k(r,n),k(r,o),h(r,"border",!0),h(r,"borderStyle","rounded"),h(r,"paddingX",1),h(r,"flexDirection","row"),k(n,i),k(n,s),L(n,()=>t().tool,s),L(r,Q(Fn,{get color(){return t().color},get background(){return x.panel}}),o),k(o,a),k(o,l),L(o,()=>t().color,l),L(o,()=>t().mirror,null),de((c)=>{var u=e.visible?3:0,d=e.visible,A=x.border,f=x.panel,g=x.textPink,m=x.textPink;return u!==c.e&&(c.e=h(r,"height",u,c.e)),d!==c.t&&(c.t=h(r,"visible",d,c.t)),A!==c.a&&(c.a=h(r,"borderColor",A,c.a)),f!==c.o&&(c.o=h(r,"backgroundColor",f,c.o)),g!==c.i&&(c.i=h(n,"fg",g,c.i)),m!==c.n&&(c.n=h(o,"fg",m,c.n)),c},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),r})()}var Vg=11;function $g(e){return[["Move","Arrow keys or H J K L"],["Paint","Space or Enter"],["Tools","D draw | E erase | F fill | R rectangle | O circle"],["Shapes","Space sets a corner, Space again draws, Esc cancels"],["Palette","1\u20130 direct | [ and ] cycle"],["Mirroring","X horizontal | Y vertical"],["Blender","B connect / disconnect"],["History","U undo | Ctrl+Z undo | Ctrl+Y redo"],["View","C toggle 2D / 3D | arrows orbit | R resets rotation"],["Zoom","- / +"],["Save","Ctrl+S"],["Export","Ctrl+E choose SVG / OBJ / PNG and a destination"],["Help","?"],...e?[["Artworks","Escape"],["Quit","Q"]]:[["Quit","Q or Escape"]],["",""],["Mouse","Click to paint | right-click to erase"],["","Shift+click targets the lower half-cell"],["",""],["","Press ? or Escape to close help."]]}function Zg(e){let t=K(()=>$g(e.canGoBack)),r=K(()=>Math.max(1,Math.min(70,e.width-2))),n=K(()=>Math.max(1,Math.min(t().length+4,e.height-2)));return(()=>{var i=S("box");return h(i,"id","help-overlay"),h(i,"position","absolute"),h(i,"zIndex",20),h(i,"border",!0),h(i,"title"," Keyboard & mouse "),h(i,"padding",1),L(i,Q(wt,{get each(){return t()},children:([s,o])=>(()=>{var a=S("box"),l=S("text"),c=S("text");return k(a,l),k(a,c),h(a,"flexDirection","row"),L(l,()=>s.padEnd(Vg)),L(c,o),de((u)=>{var{textPink:d,accentText:A}=x;return d!==u.e&&(u.e=h(l,"fg",d,u.e)),A!==u.t&&(u.t=h(c,"fg",A,u.t)),u},{e:void 0,t:void 0}),a})()})),de((s)=>{var o=Math.max(0,Math.floor((e.width-r())/2)),a=Math.max(0,Math.floor((e.height-n())/2)),l=r(),c=n(),u=e.visible,d=x.border,A=x.panel,f=x.accent;return o!==s.e&&(s.e=h(i,"left",o,s.e)),a!==s.t&&(s.t=h(i,"top",a,s.t)),l!==s.a&&(s.a=h(i,"width",l,s.a)),c!==s.o&&(s.o=h(i,"height",c,s.o)),u!==s.i&&(s.i=h(i,"visible",u,s.i)),d!==s.n&&(s.n=h(i,"borderColor",d,s.n)),A!==s.s&&(s.s=h(i,"backgroundColor",A,s.s)),f!==s.h&&(s.h=h(i,"titleColor",f,s.h)),s},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),i})()}function Xg(e){let t=K(()=>Math.max(1,Math.min(48,e.width-4))),r=K(()=>Math.max(1,Math.min(7,e.height-2))),n=K(()=>r()>=7?1:0);return(()=>{var i=S("box"),s=S("box"),o=S("input"),a=S("box"),l=S("text");return k(i,s),h(i,"id","filename-modal"),h(i,"position","absolute"),h(i,"zIndex",30),h(i,"border",!0),h(i,"title"," Save artwork "),h(i,"flexDirection","column"),k(s,o),k(s,a),k(s,l),h(s,"flexGrow",1),h(s,"width","100%"),h(s,"padding",1),h(s,"flexDirection","column"),h(o,"id","artwork-name-input"),h(o,"width","100%"),h(o,"maxLength",ro),h(o,"focused",!0),h(o,"onKeyDown",(c)=>{if(c.eventType!=="release"&&c.name==="escape")c.preventDefault(),e.onCancel()}),L(l,()=>e.error||"Enter save \xB7 Esc cancel"),de((c)=>{var u=Math.max(0,Math.floor((e.width-t())/2)),d=Math.max(0,Math.floor((e.height-r())/2)),A=t(),f=r(),g=x.border,m=x.panel,p=x.accent,v=x.panel,y=e.value,E=x.panelActive,_=x.panelActive,b=x.text,w=x.text,C=e.onInput,O=e.onSubmit,N=n(),P=e.error?x.warning:x.accentText;return u!==c.e&&(c.e=h(i,"left",u,c.e)),d!==c.t&&(c.t=h(i,"top",d,c.t)),A!==c.a&&(c.a=h(i,"width",A,c.a)),f!==c.o&&(c.o=h(i,"height",f,c.o)),g!==c.i&&(c.i=h(i,"borderColor",g,c.i)),m!==c.n&&(c.n=h(i,"backgroundColor",m,c.n)),p!==c.s&&(c.s=h(i,"titleColor",p,c.s)),v!==c.h&&(c.h=h(s,"backgroundColor",v,c.h)),y!==c.r&&(c.r=h(o,"value",y,c.r)),E!==c.d&&(c.d=h(o,"backgroundColor",E,c.d)),_!==c.l&&(c.l=h(o,"focusedBackgroundColor",_,c.l)),b!==c.u&&(c.u=h(o,"textColor",b,c.u)),w!==c.c&&(c.c=h(o,"focusedTextColor",w,c.c)),C!==c.w&&(c.w=h(o,"onInput",C,c.w)),O!==c.m&&(c.m=h(o,"on:enter",O,c.m)),N!==c.f&&(c.f=h(a,"height",N,c.f)),P!==c.y&&(c.y=h(l,"fg",P,c.y)),c},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0,m:void 0,f:void 0,y:void 0}),i})()}var zg={svg:"SVG flat vector",obj:"OBJ voxel mesh (+ .mtl)",png:"PNG 16px per cell"};function qg(e){let t=K(()=>Math.max(1,Math.min(66,e.width-4))),r=K(()=>Math.max(1,Math.min(12,e.height-2)));return(()=>{var n=S("box"),i=S("box"),s=S("box"),o=S("text"),a=S("input"),l=S("box"),c=S("text");return k(n,i),h(n,"id","export-modal"),h(n,"position","absolute"),h(n,"zIndex",30),h(n,"border",!0),h(n,"title"," Export artwork "),h(n,"flexDirection","column"),k(i,s),k(i,o),k(i,a),k(i,l),k(i,c),h(i,"flexGrow",1),h(i,"width","100%"),h(i,"padding",1),h(i,"flexDirection","column"),L(i,Q(wt,{each:Tt,children:(u,d)=>(()=>{var A=S("box"),f=S("text");return k(A,f),h(A,"flexDirection","row"),L(f,()=>e.focus==="formats"&&e.cursor===d()?"\u203A ":" ",null),L(f,()=>e.formats.includes(u)?"[x] ":"[ ] ",null),L(f,()=>zg[u],null),de((g)=>h(f,"fg",e.focus==="formats"&&e.cursor===d()?x.accent:x.text,g)),A})()}),s),h(s,"height",1),k(o,Re("Destination")),h(a,"id","export-path-input"),h(a,"width","100%"),h(a,"onKeyDown",(u)=>{if(u.name==="escape"||u.name==="tab")u.preventDefault()}),h(l,"height",1),L(c,()=>e.error||(e.focus==="formats"?"Space toggle \xB7 Tab destination \xB7 Enter export \xB7 Esc cancel":"Tab formats \xB7 Enter export \xB7 Esc cancel")),de((u)=>{var d=Math.max(0,Math.floor((e.width-t())/2)),A=Math.max(0,Math.floor((e.height-r())/2)),f=t(),g=r(),m=x.border,p=x.panel,v=x.accent,y=x.panel,E=x.textPink,_=e.path,b=x.panelActive,w=x.panelActive,C=x.text,O=x.text,N=e.focus==="path",P=e.onPathInput,R=e.onSubmit,U=e.error?x.warning:x.accentText;return d!==u.e&&(u.e=h(n,"left",d,u.e)),A!==u.t&&(u.t=h(n,"top",A,u.t)),f!==u.a&&(u.a=h(n,"width",f,u.a)),g!==u.o&&(u.o=h(n,"height",g,u.o)),m!==u.i&&(u.i=h(n,"borderColor",m,u.i)),p!==u.n&&(u.n=h(n,"backgroundColor",p,u.n)),v!==u.s&&(u.s=h(n,"titleColor",v,u.s)),y!==u.h&&(u.h=h(i,"backgroundColor",y,u.h)),E!==u.r&&(u.r=h(o,"fg",E,u.r)),_!==u.d&&(u.d=h(a,"value",_,u.d)),b!==u.l&&(u.l=h(a,"backgroundColor",b,u.l)),w!==u.u&&(u.u=h(a,"focusedBackgroundColor",w,u.u)),C!==u.c&&(u.c=h(a,"textColor",C,u.c)),O!==u.w&&(u.w=h(a,"focusedTextColor",O,u.w)),N!==u.m&&(u.m=h(a,"focused",N,u.m)),P!==u.f&&(u.f=h(a,"onInput",P,u.f)),R!==u.y&&(u.y=h(a,"on:enter",R,u.y)),U!==u.g&&(u.g=h(c,"fg",U,u.g)),u},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0,m:void 0,f:void 0,y:void 0,g:void 0}),n})()}function Zr(e){let t=ht(),r=Jr(),n=Lr(),[i,s]=j(0),[o,a]=j("Ready"),[l,c]=j(!1),[u,d]=j(null),[A,f]=j(null),[g,m]=j(!1),[p,v]=j(!1),[y,E]=j(""),[_,b]=j(""),[w,C]=j(!1),[O,N]=j(["svg"]),[P,R]=j(0),[U,X]=j("formats"),[V,te]=j(""),[ge,z]=j(""),[Me,Le]=j(2),[q,Z]=j(2),[ue,pe]=j(!1),[M,re]=j(""),ie=Vl(),[oe,qe]=j($t),[me,Se]=j(sr),[gt,Ze]=j(null),et=!e.blenderLive,ee=e.blenderLive??new go(()=>e.session.toDocument()),[mt,T]=j(ee.getStatus()),Y=ee.onStatus(T);ot(()=>{if(Y(),et)ee.dispose()});let he=K(()=>n().width>=88&&n().height>=19),it=()=>i(),[Ct,Fe]=j(0),be=(B=!1)=>{if(s((I)=>I+1),B)Fe((I)=>I+1),ee.sync()},Xe=()=>(i(),e.session.dirty),Lt=K(()=>(i(),Sn(e.session.palette,e.session.paletteColorAdjustment.saturation,e.session.paletteColorAdjustment.lightness))),se=K(()=>(Ct(),Qt(e.session.grid,e.session.paletteColorAdjustment.saturation,e.session.paletteColorAdjustment.lightness))),di=K(()=>{i();let B=u(),I=e.session.tool;if(!B||!Qr(I))return;let G=e.session;return{points:G.shapePreview(I,B,G.cursor).flatMap((_e)=>Si(G.size,_e,G.mirrorX,G.mirrorY)),color:je(Lt()[G.selectedColorIndex]??G.activeColor)}}),Ft=K(()=>(i(),{grid:se(),revision:Ct(),cursor:e.session.cursor,zoom:Me(),preview:di()})),hr=K(()=>({grid:se(),revision:Ct(),yaw:oe(),pitch:me(),zoom:q()})),Gt=()=>{if(A())f(null)},Ut=(B,I)=>{if(!Qr(B))return!1;let G=u();if(!G)return d({...I}),a(`${Zt(B)} from ${I.x+1}, ${I.y+1} \xB7 Space or click to finish \xB7 Esc cancels`),be(),!0;let Ie=e.session.applyShape(B,G,I);return d(null),be(Ie),a(Ie?`${Zt(B)} drawn`:"No change"),!0},qt=()=>{if(!u())return!1;return d(null),a(`${Zt(e.session.tool)} cancelled`),be(),!0},un=(B=e.session.tool)=>{if(Gt(),Ut(B,e.session.cursor))return;let I=e.session.applyAtCursor(B);be(I),a(I?`${Zt(B)} applied`:"No change")},dn=(B,I)=>{Gt(),e.session.moveCursor(B,I);let G=gt(),Ie=G?e.session.applyAtCursor(G):!1;be(Ie),a(G&&Ie?`${Zt(G)} at ${e.session.cursor.x+1}, ${e.session.cursor.y+1}`:`Cell ${e.session.cursor.x+1}, ${e.session.cursor.y+1}`)},Ar=(B)=>{let I=B==="undo"?e.session.undo():e.session.redo();a(I?B==="undo"?"Undo":"Redo":`Nothing to ${B}`),be(I)},hn=(B)=>{e.session.selectNextColor(B),Gt(),a(`Color ${e.session.selectedColorIndex+1}`),be()},An=async()=>{if(g())return;let B=e.session.revision,I=e.session.toDocument();m(!0),a("Saving\u2026");try{let G;if(e.saveDocument)G=await e.saveDocument(I);else{let _e=e.filePath??`${e.session.filename}.flatblox.json`,pt=Dn(I);if(e.writeFile)await e.writeFile(_e,pt);else await Bun.write(_e,pt);G=`Saved ${_e}`}let Ie=e.session.markSaved(B);f(null),a(Ie?G||"Saved":`${G||"Saved"}; newer edits remain unsaved`),be()}catch(G){let Ie=G instanceof Error?G.message:String(G);a(`Save failed: ${Ie}`)}finally{m(!1)}},Ae=()=>Ti("",e.session.filename,Gn(e.filePath,e.session.filename)),we="",We=async()=>{if(g())return;let B=await ec();we=B?Ti(`${B}/`,e.session.filename,Ae()):Ae(),te(we),z(""),R(0),X("formats"),C(!0),a("Choose export formats and destination")},xe=()=>{C(!1),a("Export cancelled")},fe=(B)=>{N((I)=>I.includes(B)?I.filter((G)=>G!==B):Tt.filter((G)=>G===B||I.includes(G))),z("")},ne=async()=>{let B=O();if(B.length===0){z("Select at least one format");return}let I=Ti(V(),e.session.filename,Ae());C(!1),m(!0),a("Exporting\u2026");try{let Ie=(await Bi(e.session.toDocument(),I,B,e.writeFile)).map((_e)=>Wg(_e));if(a(`Exported ${Ie.join(", ")} to ${Gi(I)}`),Gi(I)!==Gi(we))await tc(Gi(I)).catch(()=>{})}catch(G){let Ie=G instanceof Error?G.message:String(G);a(`Export failed: ${Ie}`)}finally{m(!1)}},ae=(B)=>{let I=B.name.toLowerCase();if(I==="escape")xe();else if(I==="tab")X((G)=>G==="path"?"formats":"path");else if(U()==="path")return;else if(I==="return"||I==="enter")ne();else if(I==="up"||I==="k")R((G)=>(G+Tt.length-1)%Tt.length);else if(I==="down"||I==="j")R((G)=>(G+1)%Tt.length);else if(or(B))fe(Tt[P()])},Ge=()=>{if(e.promptForFilenameOnSave){E(""),b(""),v(!0),a("Name artwork before saving");return}An()},Ye=(B)=>{let I=In(B);if(!I){b("Enter an artwork name");return}e.session.rename(I),b(""),v(!1),be(),An()},Pe=()=>{v(!1),b(""),a("Save cancelled")},Qe=(B)=>{if(!Xe()||A()===B){if(B==="back"&&e.onBack)e.onBack();else t.destroy();return}f(B),a(B==="back"?"Unsaved changes \u2014 press Escape again to return":"Unsaved changes \u2014 press Q again to quit")},De=(B)=>{e.session.setTool(B),d(null),Gt(),a(`${Zt(B)} tool`),be()},at=(B)=>{let I=ue(),G=I?q():Me(),Ie=I?0.25:1,_e=I&&B>0&&G<1?1:G+B,pt=Math.max(Ie,Math.min(8,_e));if(I)Z(pt);else Le(pt);a(`Zoom ${pt}\xD7`)},xs=()=>{if(!ue()&&!ie){a("3D preview is unavailable on this platform");return}if(!ue()&&M()){a(`3D unavailable: ${M()}`);return}Ze(null),d(null),pe((B)=>(a(B?"2D editor":"Voxel preview"),!B))},Es=(B,I)=>{qe((G)=>G+B*0.16),Se((G)=>Math.max(0.18,Math.min(1.15,G-I*0.12))),a("3D orbit")},Ss=()=>{qe($t),Se(sr),a("Rotation reset")},Aa=(B)=>{if(re(B),!ue())return;pe(!1),a(`3D unavailable: ${B}`)},Pd=async()=>{let B=ee.getStatus();if(B.state==="connected"||B.state==="connecting"){ee.disconnect(),a("Blender Live disconnected");return}a("Connecting to Blender\u2026");let I=await ee.connect();a(I.state==="connected"?"Drawing live in Blender":I.message??"Blender Live disconnected")},Dd=(B)=>{e.session.setCursor(B.x,B.y);let I=B.tool??e.session.tool;if(Gt(),Ut(I,{x:B.x,y:B.y}))return;let G=e.session.applyAt(B.x,B.y,I);a(G?`${Zt(I)} at ${B.x+1}, ${B.y+1}`:`Cell ${B.x+1}, ${B.y+1}`),be(G)};Fr((B)=>{let I=B.name.toLowerCase(),G=B.sequence,Ie=or(B),_e=wr(I);if(B.eventType==="release"){if(Ie)Ze(null);return}if(p())return;if(w()){ae(B);return}if(l()){if(I==="escape"||G==="?")c(!1);return}let pt=I==="q"||I==="escape"||B.ctrl&&I==="c";if(A()&&!pt)f(null);if(B.ctrl){if(I==="s")Ge();else if(I==="e")We();else if(I==="z"&&B.shift)Ar("redo");else if(I==="z")Ar("undo");else if(I==="y")Ar("redo");else if(I==="c")Qe("quit");return}if(G==="?"){c(!0);return}if(I==="escape"&&qt())return;if(I==="escape"&&e.onBack){Qe("back");return}if(I==="q"||I==="escape"){Qe("quit");return}if(I==="c"){xs();return}if(ue()){if(I==="r")Ss();else if(_e)Es(_e.dx,_e.dy);else if(G==="+"||I==="+"||I==="=")at(1);else if(G==="-"||I==="-")at(-1);return}if(_e)dn(_e.dx,_e.dy);else if(Ie){let st=e.session.tool;Ze(B.source==="kitty"&&(st==="draw"||st==="erase")?st:null),un(st)}else if(I==="b")Pd();else if(I==="d")De("draw");else if(I==="e")De("erase");else if(I==="f")De("fill");else if(I==="r")De("rectangle");else if(I==="o")De("circle");else if(I==="x")e.session.toggleMirrorX(),a(`Mirror X ${e.session.mirrorX?"on":"off"}`),be();else if(I==="y")e.session.toggleMirrorY(),a(`Mirror Y ${e.session.mirrorY?"on":"off"}`),be();else if(I==="u")Ar("undo");else if(G==="+"||I==="+"||I==="=")at(1);else if(G==="-"||I==="-")at(-1);else if(G==="[")hn(-1);else if(G==="]")hn(1);else if(/^[0-9]$/.test(I))e.session.selectColor(I==="0"?9:Number(I)-1),a(`Color ${e.session.selectedColorIndex+1}`),be()},{release:!0});let Nd=()=>{i();let B=e.session.dirty?" \u25CF":"";return`${e.session.filename}${B} ${e.session.size}\xD7${e.session.size}`},Md=()=>{switch(mt().state){case"connecting":return"connecting";case"connected":return"live";case"error":return"error";default:return"off"}},fa=K(()=>`Blender:${Md()} | ${o()}`),ga=K(()=>`C ${ue()?"2D":"3D"} \xB7 ${ue()?"R reset \xB7 ":""}`+"-/+ zoom \xB7 ? help \xB7 Ctrl+S save \xB7 Ctrl+E export \xB7 "+`${e.onBack?"Esc artworks \xB7 ":""}Q quit`),Ld=K(()=>fa().length+ga().length+1<=n().width-2);return(()=>{var B=S("box"),I=S("box"),G=S("text"),Ie=S("b"),_e=S("box"),pt=S("text"),st=S("box"),Pr=S("box"),Ht=S("pixel_grid"),jt=S("box"),Is=S("text");return k(B,I),k(B,st),k(B,jt),h(B,"width","100%"),h(B,"height","100%"),h(B,"flexDirection","column"),k(I,G),k(I,_e),k(I,pt),h(I,"height",3),h(I,"paddingX",1),h(I,"paddingY",1),h(I,"flexDirection","row"),h(I,"justifyContent","space-between"),k(G,Ie),L(Ie,Fi),h(_e,"height",1),h(_e,"flexBasis",0),h(_e,"flexGrow",1),h(_e,"flexDirection","row"),h(_e,"justifyContent","center"),L(_e,Q($r,{id:"dashboard-wordmark",width:14,height:1,get backgroundColor(){return x.panel},get foregroundColor(){return x.accent}})),L(pt,Nd),k(st,Pr),h(st,"flexGrow",1),h(st,"flexDirection","row"),h(st,"paddingLeft",1),h(st,"paddingY",1),h(st,"gap",1),k(Pr,Ht),h(Pr,"flexGrow",1),h(Pr,"overflow","hidden"),L(Pr,Q(ke,{when:ie,get children(){return Q(ke,{get when(){return r()},get fallback(){return(()=>{var H=S("voxel_preview");return h(H,"id","voxel-preview"),h(H,"width","100%"),h(H,"height","100%"),h(H,"flexGrow",1),h(H,"onInitError",Aa),de((Ne)=>{var er=ue(),tr=hr();return er!==Ne.e&&(Ne.e=h(H,"visible",er,Ne.e)),tr!==Ne.t&&(Ne.t=h(H,"model",tr,Ne.t)),Ne},{e:void 0,t:void 0}),H})()},get children(){var H=S("voxel_raster");return h(H,"id","voxel-preview"),h(H,"width","100%"),h(H,"height","100%"),h(H,"flexGrow",1),h(H,"onInitError",Aa),de((Ne)=>{var er=ue(),tr=hr();return er!==Ne.e&&(Ne.e=h(H,"visible",er,Ne.e)),tr!==Ne.t&&(Ne.t=h(H,"model",tr,Ne.t)),Ne},{e:void 0,t:void 0}),H}})}}),Ht),h(Ht,"id","pixel-grid"),h(Ht,"width","100%"),h(Ht,"height","100%"),h(Ht,"flexGrow",1),h(Ht,"onCell",Dd),L(st,Q(ke,{get when(){return lt(()=>!!he())()&&!ue()},get children(){return Q(Qg,{get session(){return e.session},get colors(){return Lt()},refresh:it,visible:!0})}}),null),L(B,Q(ke,{get when(){return lt(()=>!he())()&&!ue()},get children(){return Q(Jg,{get session(){return e.session},get colors(){return Lt()},refresh:it,visible:!0})}}),jt),k(jt,Is),h(jt,"height",1),h(jt,"paddingX",1),h(jt,"flexDirection","row"),h(jt,"justifyContent","space-between"),L(Is,fa),L(jt,Q(ke,{get when(){return Ld()},get children(){var H=S("text");return L(H,ga),de((Ne)=>h(H,"fg",x.muted,Ne)),H}}),null),L(B,Q(Zg,{get width(){return n().width},get height(){return n().height},get visible(){return l()},get canGoBack(){return Boolean(e.onBack)}}),null),L(B,Q(ke,{get when(){return w()},get children(){return Q(qg,{get width(){return n().width},get height(){return n().height},get formats(){return O()},get cursor(){return P()},get focus(){return U()},get path(){return V()},get error(){return ge()},onPathInput:(H)=>{if(te(H),ge())z("")},onSubmit:()=>void ne(),onCancel:xe})}}),null),L(B,Q(ke,{get when(){return p()},get children(){return Q(Xg,{get width(){return n().width},get height(){return n().height},get value(){return y()},get error(){return _()},onInput:(H)=>{if(E(H),_())b("")},onSubmit:Ye,onCancel:Pe})}}),null),de((H)=>{var{background:Ne,panel:er}=x,tr=mt().state==="error"?x.warning:x.accentText,ma=Xe()?x.warning:x.muted,pa=he()&&!ue()?0:1,ba=x.background,ya=x.background,wa=!ue(),va=Ft(),_a=x.panelActive,Ca=o().startsWith("Save failed")||mt().state==="error"?x.warning:x.textPink;return Ne!==H.e&&(H.e=h(B,"backgroundColor",Ne,H.e)),er!==H.t&&(H.t=h(I,"backgroundColor",er,H.t)),tr!==H.a&&(H.a=h(G,"fg",tr,H.a)),ma!==H.o&&(H.o=h(pt,"fg",ma,H.o)),pa!==H.i&&(H.i=h(st,"paddingRight",pa,H.i)),ba!==H.n&&(H.n=h(st,"backgroundColor",ba,H.n)),ya!==H.s&&(H.s=h(Pr,"backgroundColor",ya,H.s)),wa!==H.h&&(H.h=h(Ht,"visible",wa,H.h)),va!==H.r&&(H.r=h(Ht,"model",va,H.r)),_a!==H.d&&(H.d=h(jt,"backgroundColor",_a,H.d)),Ca!==H.l&&(H.l=h(Is,"fg",Ca,H.l)),H},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0}),B})()}import{chmod as Yp,mkdir as Qp,readFile as Jp,rename as Vp,unlink as $p,writeFile as Zp}from"fs/promises";import{homedir as Xp}from"os";import{dirname as zp,join as ad}from"path";var Qc=Yd(Yc(),1),{__extends:Ax,__assign:fx,__rest:_r,__decorate:gx,__param:mx,__esDecorate:px,__runInitializers:bx,__propKey:yx,__setFunctionName:wx,__metadata:vx,__awaiter:Jc,__generator:_x,__exportStar:Cx,__createBinding:xx,__values:Ex,__read:Sx,__spread:Ix,__spreadArrays:kx,__spreadArray:Rx,__await:Tx,__asyncGenerator:Bx,__asyncDelegator:Ox,__asyncValues:Px,__makeTemplateObject:Dx,__importStar:Nx,__importDefault:Mx,__classPrivateFieldGet:Lx,__classPrivateFieldSet:Fx,__classPrivateFieldIn:Gx,__addDisposableResource:Ux,__disposeResources:Hx,__rewriteRelativeImportExtension:jx}=Qc.default;var Vc=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)};class Kn extends Error{constructor(e,t="FunctionsError",r){super(e);this.name=t,this.context=r}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class Ki extends Kn{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Wn extends Kn{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Yn extends Kn{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var jn;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(jn||(jn={}));class Wi{constructor(e,{headers:t={},customFetch:r,region:n=jn.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=Vc(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Jc(this,arguments,void 0,function*(t,r={}){var n;let i,s;try{let{headers:o,method:a,body:l,signal:c,timeout:u}=r,d={},{region:A}=r;if(!A)A=this.region;let f=new URL(`${this.url}/${t}`);if(A&&A!=="any")d["x-region"]=A,f.searchParams.set("forceFunctionRegion",A);let g;if(l&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o))if(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer)d["Content-Type"]="application/octet-stream",g=l;else if(typeof l==="string")d["Content-Type"]="text/plain",g=l;else if(typeof FormData<"u"&&l instanceof FormData)g=l;else d["Content-Type"]="application/json",g=JSON.stringify(l);else if(l&&typeof l!=="string"&&!(typeof Blob<"u"&&l instanceof Blob)&&!(l instanceof ArrayBuffer)&&!(typeof FormData<"u"&&l instanceof FormData))g=JSON.stringify(l);else g=l;let m=c;if(u)if(s=new AbortController,i=setTimeout(()=>s.abort(),u),c)m=s.signal,c.addEventListener("abort",()=>s.abort());else m=s.signal;let p=yield this.fetch(f.toString(),{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),o),body:g,signal:m}).catch((_)=>{throw new Ki(_)}),v=p.headers.get("x-relay-error");if(v&&v==="true")throw new Wn(p);if(!p.ok)throw new Yn(p);let y=((n=p.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),E;if(y==="application/json")E=yield p.json();else if(y==="application/octet-stream"||y==="application/pdf")E=yield p.blob();else if(y==="text/event-stream")E=p;else if(y==="multipart/form-data")E=yield p.formData();else E=yield p.text();return{data:E,error:null,response:p}}catch(o){return{data:null,error:o,response:o instanceof Yn||o instanceof Wn?o.context:void 0}}finally{if(i)clearTimeout(i)}})}}var $c=(e)=>Math.min(1000*2**e,30000),em=[520,503],qc=["GET","HEAD","OPTIONS"],eu=class extends Error{constructor(e){super(e.message);this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Zc(e,t){return new Promise((r)=>{if(t===null||t===void 0?void 0:t.aborted){r();return}let n=setTimeout(()=>{t===null||t===void 0||t.removeEventListener("abort",i),r()},e);function i(){clearTimeout(n),r()}t===null||t===void 0||t.addEventListener("abort",i)})}function tm(e,t,r,n){if(!n||r>=3)return!1;if(!qc.includes(e))return!1;if(!em.includes(t))return!1;return!0}var rm=class{constructor(e){var t,r,n,i,s;if(this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(r=e.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(n=e.shouldStripNulls)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(i=e.urlLengthLimit)!==null&&i!==void 0?i:8000,this.retryEnabled=(s=e.retry)!==null&&s!==void 0?s:!0,e.fetch)this.fetch=e.fetch;else this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var r=this;if(this.schema===void 0);else if(["GET","HEAD"].includes(this.method))this.headers.set("Accept-Profile",this.schema);else this.headers.set("Content-Profile",this.schema);if(this.method!=="GET"&&this.method!=="HEAD")this.headers.set("Content-Type","application/json");if(this.shouldStripNulls){let o=this.headers.get("Accept");if(o==="application/vnd.pgrst.object+json")this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped");else if(!o||o==="application/json")this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let n=this.fetch,s=(async()=>{let o=0;while(!0){let c=new Headers(r.headers);if(o>0)c.set("X-Retry-Count",String(o));let u;try{u=await n(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body),signal:r.signal})}catch(d){if((d===null||d===void 0?void 0:d.name)==="AbortError"||(d===null||d===void 0?void 0:d.code)==="ABORT_ERR")throw d;if(!qc.includes(r.method))throw d;if(r.retryEnabled&&o<3){let A=$c(o);o++,await Zc(A,r.signal);continue}throw d}if(tm(r.method,u.status,o,r.retryEnabled)){var a,l;let d=(a=(l=u.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&a!==void 0?a:null,A=d!==null?Math.max(0,parseInt(d,10)||0)*1000:$c(o);await u.text(),o++,await Zc(A,r.signal);continue}return await r.processResponse(u)}})();if(!this.shouldThrowOnError)s=s.catch((o)=>{var a;let l="",c="",u="",d=o===null||o===void 0?void 0:o.cause;if(d){var A,f,g,m;let y=(A=d===null||d===void 0?void 0:d.message)!==null&&A!==void 0?A:"",E=(f=d===null||d===void 0?void 0:d.code)!==null&&f!==void 0?f:"";if(l=`${(g=o===null||o===void 0?void 0:o.name)!==null&&g!==void 0?g:"FetchError"}: ${o===null||o===void 0?void 0:o.message}`,l+=`
15
+ `}}function Do(e,t){let r=new Uint8Array(12+t.length),n=new DataView(r.buffer);return n.setUint32(0,t.length),r.set(new TextEncoder().encode(e),4),r.set(t,8),n.setUint32(8+t.length,Bun.hash.crc32(r.subarray(4,8+t.length))),r}function bg(e,t){let r=e.length,n=hc(e),{width:i,height:s}=t===void 0?fc(n,r,fg):{width:n*t,height:r*t},o=i*4+1,a=new Uint8Array(o*s),l=e.map((A)=>A.map((m)=>Ac(m)?Pt(m.color):null));for(let A=0;A<s;A++){let m=Math.min(r-1,Math.floor(A*r/s)),b=A*o+1;for(let w=0;w<i;w++){let p=Math.min(n-1,Math.floor(w*n/i)),C=l[m]?.[p];if(!C)continue;let _=b+w*4;a[_]=C.r,a[_+1]=C.g,a[_+2]=C.b,a[_+3]=Math.round(C.a*255)}}let c=new Uint8Array(13),u=new DataView(c.buffer);u.setUint32(0,i),u.setUint32(4,s),c[8]=8,c[9]=6;let d=[Ag,Do("IHDR",c),Do("IDAT",new Uint8Array(dg(a))),Do("IEND",new Uint8Array(0))],f=new Uint8Array(d.reduce((A,m)=>A+m.length,0)),g=0;for(let A of d)f.set(A,g),g+=A.length;return f}function yg(e,t,r=Mt){let n=[],{saturation:i,lightness:s}=e.paletteColorAdjustment??{saturation:0,lightness:0},o=Qt(e.grid,i,s);for(let a of r)if(a==="svg")n.push({path:`${t}.svg`,content:gg(o)});else if(a==="obj"){let l=`${t}.mtl`,{obj:c,mtl:u}=pg(o,cg(l));n.push({path:`${t}.obj`,content:c}),n.push({path:l,content:u})}else n.push({path:`${t}.png`,content:bg(o)});return n}async function Hi(e,t,r=Mt,n=(i,s)=>Bun.write(i,s)){let i=yg(e,t,r);for(let s of i)await n(s.path,s.content);return i.map((s)=>s.path)}import{mkdir as wg,readFile as vg,writeFile as _g}from"fs/promises";import{homedir as Cg}from"os";import{dirname as xg,join as gc}from"path";function mc(e=process.env){if(e.FLATBLOX_TUI_EXPORT_FILE)return e.FLATBLOX_TUI_EXPORT_FILE;let t=e.XDG_CONFIG_HOME||gc(Cg(),".config");return gc(t,"flatblox","tui-export.json")}async function pc(e=mc()){try{let t=JSON.parse(await vg(e,"utf8")),r=typeof t==="object"&&t!==null?t.directory:void 0;return typeof r==="string"&&r.length>0?r:null}catch{return null}}async function bc(e,t=mc()){await wg(xg(t),{recursive:!0,mode:448}),await _g(t,`${JSON.stringify({directory:e},null,2)}
16
+ `)}function hr(e){let t=e.name.toLowerCase();return t==="return"||t==="enter"||t==="space"||e.sequence===" "}function xr(e){switch(e){case"left":case"h":return{dx:-1,dy:0};case"right":case"l":return{dx:1,dy:0};case"up":case"k":return{dx:0,dy:-1};case"down":case"j":return{dx:0,dy:1};default:return}}import{MouseButton as Mo,NativeImage as Ki,parseColor as Dg,Renderable as Mg,RGBA as jn,TextAttributes as yc}from"@opentui/core";import{RGBA as Eg}from"@opentui/core";var Sg={r:88,g:88,b:88,a:1},Ig={r:108,g:108,b:108,a:1},ji=new Map;function kg(e){let t=ji.get(e);if(t!==void 0)return t;let r=Pt(e);if(ji.size>=4096)ji.clear();return ji.set(e,r),r}function Rg(e,t){return(e+t)%2===0?Sg:Ig}function Tg(e,t){let r=Math.max(0,Math.min(1,e.a));return{r:Math.round(e.r*r+t.r*(1-r)),g:Math.round(e.g*r+t.g*(1-r)),b:Math.round(e.b*r+t.b*(1-r)),a:1}}function Og(e,t,r){let n=Rg(t,r),i=e?.active&&e.color?kg(e.color):null;return i?Tg(i,n):n}var Bg=[new Map,new Map],Pg=4096;function Zt(e,t,r){let n=Bg[(t+r)%2],i=e?.active&&e.color?e.color:"",s=n.get(i);if(!s){if(n.size>=Pg)n.clear();let o=Og(e,t,r);s=Eg.fromInts(o.r,o.g,o.b),n.set(i,s)}return s}var Wi=jn.fromInts(52,48,58),wc=jn.fromInts(68,63,74),Ng=2,Ji=jn.fromInts(255,255,255),Vi=jn.fromInts(8,10,16),Lg=0.25,No=3,Lo=5,Fg=[[],[2,6,2,2,7],[7,1,7,4,7],[7,1,7,1,7],[5,5,7,1,1],[7,4,7,1,7],[7,4,7,5,7],[7,1,1,1,1],[7,5,7,5,7]],Yi=512,Zi=16384,Cc=25000000;function vc(e,t){if(!e||e.points.length===0)return null;let r=new Set;for(let n of e.points)r.add(n.y*t+n.x);return{cells:r,color:Dg(e.color)}}function Qi(e){let[t,r,n]=e.toInts(),i=(0.2126*t+0.7152*r+0.0722*n)/255,[s,o,a]=i>0.55?Vi.toInts():Ji.toInts(),l=(c,u)=>Math.round(c+(u-c)*Lg);return jn.fromInts(l(t,s),l(r,o),l(n,a))}function _c(e,t,r){return Math.max(0,Math.min(r-t,e-Math.floor(t/2)))}function Gg(e,t){let r=Math.ceil(e/Yi)*Yi,n=Math.ceil(t/Yi)*Yi;if(r>Zi||n>Zi||r*n>Cc)return null;return{width:r,height:n}}function Ug(e,t,r,n,i){let o=Math.max(1,Math.floor(n)),a=Math.max(1,Math.round(o*2/i)),l=Math.min(r,Math.floor(e/o)),c=Math.min(r,Math.floor(t*2/a)),u=l*o,d=c*a;return{columns:l,pixelRows:c,columnZoom:o,subrowZoom:a,renderedColumns:u,renderedSubrows:d,terminalRows:Math.ceil(d/2)}}function Hg(e,t,r,n,i,s){let o=Math.max(1,Math.floor(n)),a=Math.max(1,Math.round(o*i)),l=Math.min(r,Math.floor(e/o)),c=Math.min(r,Math.floor(t*s/a)),u=l*a,d=c*a,f=d*2/s;return{columns:l,pixelRows:c,columnZoom:o,subrowZoom:a*2/s,renderedColumns:l*o,renderedSubrows:f,terminalRows:Math.ceil(d/s),pixelWidth:u,pixelHeight:d}}class Fo extends Mg{textFrame=null;artworkImage=null;artworkImageCache=null;worldImage=null;worldImageSide=0;worldImageWidth=0;worldImageHeight=0;currentModel={grid:[],cursor:{x:0,y:0},zoom:1};cellHandler;viewport={originX:0,originY:0,startX:0,startY:0,columns:0,pixelRows:0,columnZoom:1,subrowZoom:1,renderedSubrows:0};constructor(e,t){super(e,{...t,buffered:!0});if(t.model)this.currentModel=t.model;this.cellHandler=t.onCell,this.onMouseDown=(r)=>this.handleMouse(r)}set model(e){if(!e)return;this.currentModel=e,this.requestRender()}set onCell(e){this.cellHandler=e}sameTextFrame(e){let t=this.currentModel,r=this.textFrame;if(r&&r.grid===t.grid&&r.revision===t.revision&&r.preview===t.preview&&r.cursorX===t.cursor.x&&r.cursorY===t.cursor.y&&r.zoom===t.zoom&&r.depthLabels===!!t.depthLabels&&r.width===this.width&&r.height===this.height&&r.cellAspect===e)return!0;return this.textFrame={grid:t.grid,revision:t.revision,preview:t.preview,cursorX:t.cursor.x,cursorY:t.cursor.y,zoom:t.zoom,depthLabels:!!t.depthLabels,width:this.width,height:this.height,cellAspect:e},!1}renderSelf(e){let t=this.currentModel.grid.length,r=Ni(this._ctx),n=Et(this._ctx),i=n!==null&&Li(this._ctx);if(i)this.textFrame=null;else if(this.sameTextFrame(r))return;if(e.clear(Wi),t===0||this.width<=0||this.height<=0){this.viewport.columns=0,this.viewport.pixelRows=0;return}let s=n&&i?Hg(this.width,this.height,t,this.currentModel.zoom,n.width,n.height):null;if(s&&(s.pixelWidth>Zi||s.pixelHeight>Zi||s.pixelWidth*s.pixelHeight>Cc))s=null;let o=s??Ug(this.width,this.height,t,this.currentModel.zoom,r),{columns:a,pixelRows:l}=o;if(a===0||l===0){this.viewport.columns=0,this.viewport.pixelRows=0,this.viewport.columnZoom=o.columnZoom,this.viewport.subrowZoom=o.subrowZoom,this.viewport.renderedSubrows=0;return}let{renderedColumns:c,renderedSubrows:u,terminalRows:d}=o,f=_c(this.currentModel.cursor.x,a,t),g=_c(this.currentModel.cursor.y,l,t),A=Math.floor((this.width-c)/2),m=Math.floor((this.height-d)/2);if(s&&n){if(!this.drawWorldGridImage(e,A,m,n.width,n.height,o.columnZoom))this.drawWorldGrid(e,A,m,r,o.columnZoom)}else this.releaseWorldImage(),this.drawWorldGrid(e,A,m,r,o.columnZoom);if(this.viewport={originX:A,originY:m,startX:f,startY:g,columns:a,pixelRows:l,columnZoom:o.columnZoom,subrowZoom:o.subrowZoom,renderedSubrows:u},s){this.drawArtworkImage(e,s,A,m,f,g);return}this.releaseArtworkImage();let{grid:b,cursor:w}=this.currentModel,p=vc(this.currentModel.preview,t),{subrowZoom:C,columnZoom:_}=o;for(let y=0;y<d;y++){let v=y*2,x=v+1,B=g+Math.floor(v/C),M=g+Math.floor(x/C),P=b[B],O=b[M];for(let W=0;W<c;W++){let Q=f+Math.floor(W/_),j=p?.cells.has(B*t+Q)?p.color:Zt(P?.[Q],Q,B),ee=x<u&&M<t?p?.cells.has(M*t+Q)?p.color:Zt(O?.[Q],Q,M):Wi,ie=w.x===Q&&w.y===B,z=w.x===Q&&w.y===M;e.setCell(A+W,m+y,"\u2580",ie?Qi(j):j,z?Qi(ee):ee)}}if(this.currentModel.depthLabels)this.drawDepthLabels(e,A,m,f,g)}drawDepthLabels(e,t,r,n,i){let{grid:s,cursor:o}=this.currentModel,{columns:a,pixelRows:l,columnZoom:c,subrowZoom:u}=this.viewport;if(u<2)return;for(let d=0;d<l;d++){let f=i+d,g=Math.ceil(d*u/2),A=Math.floor((d+1)*u/2)-1;if(A<g)continue;let m=g+Math.floor((A-g)/2);for(let b=0;b<a;b++){let w=n+b,p=s[f]?.[w];if(!p?.active)continue;let C=Zt(p,w,f);if(o.x===w&&o.y===f)C=Qi(C);let[_,y,v]=C.toInts(),x=_*0.299+y*0.587+v*0.114>140;e.setCell(t+b*c+Math.floor((c-1)/2),r+m,String(We(p.depth)),x?Vi:Ji,C)}}}drawArtworkImage(e,t,r,n,i,s){let o=this.currentModel.cursor,a=this.artworkImageCache;if(!(this.artworkImage&&a&&a.grid===this.currentModel.grid&&a.revision===this.currentModel.revision&&a.preview===this.currentModel.preview&&a.columns===t.columns&&a.pixelRows===t.pixelRows&&a.pixelWidth===t.pixelWidth&&a.pixelHeight===t.pixelHeight&&a.startX===i&&a.startY===s&&a.cursorX===o.x&&a.cursorY===o.y&&a.depthLabels===!!this.currentModel.depthLabels)){let c=this.currentModel.grid.length,u=vc(this.currentModel.preview,c),d=new Uint8Array(t.columns*t.pixelRows*4);for(let g=0;g<t.pixelRows;g++){let A=s+g;for(let m=0;m<t.columns;m++){let b=i+m,w=u?.cells.has(A*c+b)?u.color:Zt(this.currentModel.grid[A]?.[b],b,A);if(o.x===b&&o.y===A)w=Qi(w);let[p,C,_]=w.toInts(),y=(g*t.columns+m)*4;d[y]=p,d[y+1]=C,d[y+2]=_,d[y+3]=255}}let f;if(this.currentModel.depthLabels)f=this.imageWithDepthLabels(d,t,i,s);else{let g=Ki.fromRgba(d,t.columns,t.pixelRows);try{f=g.resize({width:t.pixelWidth,height:t.pixelHeight,kernel:"nearest"})}finally{g.dispose()}}this.releaseArtworkImage(),this.artworkImage=f,this.artworkImageCache={grid:this.currentModel.grid,revision:this.currentModel.revision,preview:this.currentModel.preview,columns:t.columns,pixelRows:t.pixelRows,pixelWidth:t.pixelWidth,pixelHeight:t.pixelHeight,startX:i,startY:s,cursorX:o.x,cursorY:o.y,depthLabels:!!this.currentModel.depthLabels}}if(!this.artworkImage)return;e.drawImage(this.artworkImage,r,n,t.renderedColumns,t.terminalRows,t.pixelWidth,t.pixelHeight,0,0,t.pixelWidth,t.pixelHeight,"auto")}imageWithDepthLabels(e,t,r,n){let{columns:i,pixelRows:s,pixelWidth:o,pixelHeight:a}=t,l=o/i,c=new Uint8Array(o*a*4);for(let A=0;A<a;A++){let m=Math.min(s-1,Math.floor(A/l));for(let b=0;b<o;b++){let w=Math.min(i-1,Math.floor(b/l)),p=(m*i+w)*4,C=(A*o+b)*4;c[C]=e[p],c[C+1]=e[p+1],c[C+2]=e[p+2],c[C+3]=255}}let u=Math.max(1,Math.floor(l/(Lo+3))),d=No*u,f=Lo*u;if(d>l||f>l)return Ki.fromRgba(c,o,a);let{grid:g}=this.currentModel;for(let A=0;A<s;A++)for(let m=0;m<i;m++){let b=g[n+A]?.[r+m];if(!b?.active)continue;let w=(A*i+m)*4,p=e[w]*0.299+e[w+1]*0.587+e[w+2]*0.114,C=p>140?Vi:Ji,_=p>140?Ji:Vi,y=Fg[We(b.depth)],v=Math.floor(m*l+(l-d)/2),x=Math.floor(A*l+(l-f)/2);for(let B of[_,C]){let[M,P,O]=B.toInts(),W=B===_?[-1,0,1]:[0];for(let Q=0;Q<Lo;Q++)for(let j=0;j<No;j++){if(!(y[Q]&1<<No-1-j))continue;for(let ee=0;ee<u;ee++)for(let ie=0;ie<u;ie++)for(let z of W)for(let Be of W){let Pe=v+j*u+ie+Be,Je=x+Q*u+ee+z;if(Pe<0||Je<0||Pe>=o||Je>=a)continue;let ze=(Je*o+Pe)*4;c[ze]=M,c[ze+1]=P,c[ze+2]=O}}}}return Ki.fromRgba(c,o,a)}releaseArtworkImage(){this.artworkImage?.dispose(),this.artworkImage=null,this.artworkImageCache=null}drawWorldGridImage(e,t,r,n,i,s){let o=Math.max(1,Math.round(this.width*n)),a=Math.max(1,Math.round(this.height*i)),l=Math.max(1,Math.round(s*n)),c=Math.round(t*n),u=Math.round(r*i),d=o+l,f=a+l,g=Gg(d,f);if(!g)return this.releaseWorldImage(),!1;if(!this.worldImage||l!==this.worldImageSide||d>this.worldImageWidth||f>this.worldImageHeight){let{width:b,height:w}=g,p=new Uint8Array(b*w*4),[C,_,y]=Wi.toInts(),[v,x,B]=wc.toInts(),M=b*4,P=new Uint8Array(M),O=new Uint8Array(M);for(let W=0;W<b;W++){let Q=W*4,j=W%l===0;P[Q]=j?v:C,P[Q+1]=j?x:_,P[Q+2]=j?B:y,P[Q+3]=255,O[Q]=v,O[Q+1]=x,O[Q+2]=B,O[Q+3]=255}for(let W=0;W<w;W++)p.set(W%l===0?O:P,W*M);this.releaseWorldImage(),this.worldImage=Ki.fromRgba(p,b,w),this.worldImageSide=l,this.worldImageWidth=b,this.worldImageHeight=w}if(!this.worldImage)return!1;let A=(-c%l+l)%l,m=(-u%l+l)%l;return e.drawImage(this.worldImage,0,0,this.width,this.height,o,a,A,m,o,a,"auto"),!0}releaseWorldImage(){this.worldImage?.dispose(),this.worldImage=null,this.worldImageSide=0,this.worldImageWidth=0,this.worldImageHeight=0}drawWorldGrid(e,t,r,n,i){let s=Math.max(Ng,i),o=Math.max(1,Math.round(s/n));for(let a=0;a<this.height;a++){let l=a+1-r,c=Math.floor(l/o)!==Math.floor((l-1)/o);for(let u=0;u<this.width;u++){let d=u>0&&(u-t)%s===0;if(!c&&!d)continue;e.setCell(u,a,d?"\u258F":" ",wc,Wi,c?yc.UNDERLINE:yc.NONE)}}}destroySelf(){this.releaseArtworkImage(),this.releaseWorldImage(),super.destroySelf()}handleMouse(e){if(e.button!==Mo.LEFT&&e.button!==Mo.RIGHT)return;let t=e.x-this.screenX-this.viewport.originX,r=e.y-this.screenY-this.viewport.originY;if(t<0||t>=this.viewport.columns*this.viewport.columnZoom||r<0||r>=Math.ceil(this.viewport.renderedSubrows/2))return;let n=this.viewport.startX+Math.floor(t/this.viewport.columnZoom),i=e.modifiers.shift?1:0,s=r*2+i;if(s>=this.viewport.renderedSubrows)return;let o=this.viewport.startY+Math.floor(s/this.viewport.subrowZoom);if(o>=this.currentModel.grid.length)return;this.cellHandler?.({x:n,y:o,...e.button===Mo.RIGHT?{tool:"erase"}:{}})}}import{CliRenderEvents as zg,RGBA as qg}from"@opentui/core";import{SuperSampleType as em,ThreeRenderable as tm}from"@opentui/three";import{RGBA as jg}from"@opentui/core";var Go="Loading voxel preview\u2026",Kg=jg.fromInts(175,129,202);function $i(e,t,r,n){if(t<1||r<1)return;let i=t>=Go.length?Go:Go.slice(0,t),s=Math.max(0,Math.floor((t-i.length)/2)),o=Math.floor((r-1)/2);e.drawText(i,s,o,Kg,n)}import{THREE as oe}from"@opentui/three";var Wg=1.12,Yg=[0.76,0.64,1,0.42,0.9,0.72],Uo=128,Qg=1,xc=4472650,Jg="hsl(355, 40%, 58%)",Vg="hsl(105, 23%, 50%)",Zg=0.55,$g=new Uint8Array([88,88,88,255,108,108,108,255,108,108,108,255,88,88,88,255]);function Xg(e,t){let r=[];for(let n of Yg){let i=t?n**2.2:n;for(let s=0;s<4;s+=1)r.push(i,i,i)}e.setAttribute("color",new oe.Float32BufferAttribute(r,3))}class Kn{scene=new oe.Scene;camera=new oe.OrthographicCamera(-1,1,1,-1,0.1,1000);boxGeometry=new oe.BoxGeometry(1,1,1);boxMaterial;sceneHalfExtents=new oe.Vector3(2,2,2);groundGeometry;groundMaterial;groundTexture;ground;worldGrid;axes;mesh=null;model;aspect=1;sceneCenterY=0;disposed=!1;constructor(e,t){if(this.model=e,Xg(this.boxGeometry,t==="raster"),this.boxMaterial=new oe.MeshBasicMaterial({toneMapped:!1,vertexColors:!0}),t==="raster"){this.groundGeometry=new oe.PlaneGeometry(1,1),this.groundTexture=new oe.DataTexture($g,2,2),this.groundTexture.colorSpace=oe.SRGBColorSpace,this.groundTexture.magFilter=oe.NearestFilter,this.groundTexture.minFilter=oe.NearestFilter,this.groundTexture.wrapS=oe.RepeatWrapping,this.groundTexture.wrapT=oe.RepeatWrapping,this.groundTexture.needsUpdate=!0,this.groundMaterial=new oe.MeshBasicMaterial({map:this.groundTexture,toneMapped:!1}),this.ground=new oe.Mesh(this.groundGeometry,this.groundMaterial),this.ground.rotation.x=-Math.PI/2,this.scene.add(this.ground),this.worldGrid=new oe.GridHelper(Uo,Uo/Qg,xc,xc);let r=Array.isArray(this.worldGrid.material)?this.worldGrid.material:[this.worldGrid.material];for(let s of r)s.toneMapped=!1;this.scene.add(this.worldGrid),this.axes=new oe.Group;let n=Uo/2,i=(s,o,a)=>new oe.Line(new oe.BufferGeometry().setFromPoints([o,a]),new oe.LineBasicMaterial({color:s,transparent:!0,opacity:Zg,toneMapped:!1}));this.axes.add(i(Jg,new oe.Vector3(-n,0,0),new oe.Vector3(n,0,0)),i(Vg,new oe.Vector3(0,0,-n),new oe.Vector3(0,0,n))),this.scene.add(this.axes)}this.rebuildMesh(),this.updateCamera()}update(e,t=this.aspect){if(this.disposed)return;let r=e.grid!==this.model.grid||e.revision!==this.model.revision;if(this.model=e,this.aspect=Math.max(0.25,t),r)this.rebuildMesh();this.updateCamera()}setAspect(e){this.aspect=Math.max(0.25,e),this.updateCamera()}dispose(){if(this.disposed)return;this.disposed=!0,this.mesh?.dispose(),this.boxGeometry.dispose(),this.boxMaterial.dispose(),this.groundGeometry?.dispose(),this.groundMaterial?.dispose(),this.groundTexture?.dispose(),this.worldGrid?.dispose(),this.axes?.traverse((e)=>{if(!(e instanceof oe.Line))return;e.geometry.dispose();let t=Array.isArray(e.material)?e.material:[e.material];for(let r of t)r.dispose()}),this.scene.clear(),this.mesh=null}rebuildMesh(){let e=Gi(this.model.grid),t=this.model.grid.length,r=this.model.grid.reduce((c,u)=>Math.max(c,u.length),0),n=e.reduce((c,u)=>Math.min(c,u.y-u.height/2),0),i=e.reduce((c,u)=>Math.max(c,u.y+u.height/2),0);if(this.sceneCenterY=0.5,this.sceneHalfExtents.set(Math.max(1,r)/2,Math.max(0.5,i-this.sceneCenterY,this.sceneCenterY-n),Math.max(1,t)/2),this.ground)this.ground.position.y=n-0.04,this.ground.scale.set(Math.max(1,r),Math.max(1,t),1),this.groundTexture?.repeat.set(Math.max(1,r)/2,Math.max(1,t)/2);if(this.worldGrid)this.worldGrid.position.y=n-0.08;if(this.axes)this.axes.position.y=n-0.06;if(e.length===0){if(this.mesh)this.mesh.visible=!1;return}let s=2**Math.ceil(Math.log2(e.length));if(this.mesh&&this.mesh.count<s)this.scene.remove(this.mesh),this.mesh.dispose(),this.boxMaterial.dispose(),this.boxGeometry.dispose(),this.mesh=null;if(!this.mesh)this.mesh=new oe.InstancedMesh(this.boxGeometry,this.boxMaterial,s),this.mesh.instanceMatrix.setUsage(oe.DynamicDrawUsage),this.scene.add(this.mesh);let o=this.mesh;o.instanceMatrix.array.fill(0);for(let c=e.length;c<o.count;c++)o.instanceMatrix.array[c*16+15]=1;o.visible=!0,o.boundingBox=null,o.boundingSphere=null;let a=new oe.Object3D,l=new oe.Color;for(let c=0;c<e.length;c+=1){let u=e[c];a.position.set(u.x,u.y,u.z),a.scale.set(1,u.height,1),a.updateMatrix(),o.setMatrixAt(c,a.matrix);let d=cr(u.color)??{r:255,g:255,b:255};o.setColorAt(c,l.setRGB(d.r/255,d.g/255,d.b/255,oe.SRGBColorSpace))}if(o.instanceMatrix.needsUpdate=!0,o.instanceColor)o.instanceColor.needsUpdate=!0}updateCamera(){let e=new oe.Vector3(Math.sin(this.model.yaw)*Math.cos(this.model.pitch),Math.sin(this.model.pitch),Math.cos(this.model.yaw)*Math.cos(this.model.pitch)),t=new oe.Vector3(0,this.sceneCenterY,0);this.camera.position.copy(t).addScaledVector(e,100),this.camera.lookAt(t);let r=new oe.Vector3(Math.sin(Vt)*Math.cos(dr),Math.sin(dr),Math.cos(Vt)*Math.cos(dr)),n=new oe.Vector3(Math.cos(Vt),0,-Math.sin(Vt)),i=r.clone().cross(n).normalize(),s=Math.abs(n.x)*this.sceneHalfExtents.x+Math.abs(n.z)*this.sceneHalfExtents.z,o=Math.abs(i.x)*this.sceneHalfExtents.x+Math.abs(i.y)*this.sceneHalfExtents.y+Math.abs(i.z)*this.sceneHalfExtents.z,a=Math.sqrt(2/this.model.zoom),l=Math.max(1,o,s/this.aspect)*Wg*a;this.camera.left=-l*this.aspect,this.camera.right=l*this.aspect,this.camera.top=l,this.camera.bottom=-l,this.camera.updateProjectionMatrix()}}function Xi(){return{grid:[],yaw:Vt,pitch:dr,zoom:1}}var Ec=qg.fromInts(52,48,58);class Ho extends tm{currentModel;sceneController;initErrorHandler;initializing=!1;initializationFailed=!1;firstFrameDrawn=!1;destroyRequested=!1;sceneDisposed=!1;rendererDestroyed=!1;constructor(e,t){let{model:r,onInitError:n,renderer:i,...s}=t,o=r??Xi(),a=new Kn(o,"terminal");super(e,{...s,scene:a.scene,camera:a.camera,autoAspect:!1,live:!1,renderer:{backgroundColor:Ec,superSample:em.GPU,...i}});this.currentModel=o,this.sceneController=a,this.initErrorHandler=n,this.sceneController.setAspect(this.aspectRatio);let l=this.renderer.destroy.bind(this.renderer);this.renderer.destroy=()=>{if(this.destroyRequested=!0,this.initializing||this.rendererDestroyed)return;this.rendererDestroyed=!0,this.disposeScene();let d=this.renderer,f=d.device;e.off(zg.DESTROY,d.destroyHandler);try{l()}catch(g){if(!this.initializationFailed)throw g}finally{d.device=null,d.canvas=void 0,d.threeRenderer=void 0,f?.destroy()}};let c=this.renderer.drawScene.bind(this.renderer);this.renderer.drawScene=async(...d)=>{if(this.destroyRequested)return;if(await c(...d),!this.firstFrameDrawn)this.firstFrameDrawn=!0,this.requestRender()};let u=this.renderer.init.bind(this.renderer);this.renderer.init=async()=>{this.initializing=!0;try{await u()}catch(d){this.initializationFailed=!0;let f=d instanceof Error?d.message:String(d);throw this.initErrorHandler?.(f),d}finally{if(this.initializing=!1,this.destroyRequested||this.initializationFailed)this.renderer.destroy()}}}get model(){return this.currentModel}set model(e){if(this.currentModel=e,this.visible)this.sceneController?.update(e,this.aspectRatio);this.requestRender()}set onInitError(e){this.initErrorHandler=e}set visible(e){if(super.visible=e,e&&this.sceneController)this.sceneController.update(this.currentModel,this.aspectRatio)}get visible(){return super.visible}renderSelf(e,t){if(super.renderSelf(e,t),!this.firstFrameDrawn&&this.visible)$i(e,this.width,this.height,Ec)}onResize(e,t){super.onResize(e,t),this.sceneController?.setAspect(this.aspectRatio)}destroySelf(){this.destroyRequested=!0,super.destroySelf()}disposeScene(){if(this.sceneDisposed)return;this.sceneDisposed=!0,this.sceneController?.dispose()}}import{NativeImage as nm,Renderable as im,RGBA as sm}from"@opentui/core";import{CLICanvas as om,SuperSampleType as am,THREE as zi}from"@opentui/three";import{createWebGPUDevice as lm,setupGlobals as cm}from"bun-webgpu";import{WebGPURenderer as um}from"three/webgpu";import{appendFileSync as rm}from"fs";var Sc=process.env.FLATBLOX_TUI_TIMING;function jo(e,t){if(!Sc)return;let r=(performance.now()-t).toFixed(0);rm(Sc,`${e} ${r}ms
17
+ `)}var qi=[52,48,58],Ic=sm.fromInts(...qi),dm=250,hm=150,fm=0.4;class Ko extends im{currentModel;sceneController;initErrorHandler;frame=null;device=null;canvas=null;context=null;webgpuRenderer=null;readbackBuffer=null;readbackSize=0;renderWidth=0;renderHeight=0;pending=!1;scheduled=!1;rendering=!1;failed=!1;destroyRequested=!1;lowDetail=!1;lastModelUpdate=0;refineTimer=null;constructor(e,t){let{model:r,onInitError:n,...i}=t;super(e,{...i,buffered:!0,live:!1});this.currentModel=r??Xi(),this.sceneController=new Kn(this.currentModel,"raster"),this.initErrorHandler=n,this.scheduleRender()}get model(){return this.currentModel}set model(e){this.currentModel=e;let t=performance.now();if(this.lowDetail=t-this.lastModelUpdate<dm,this.lastModelUpdate=t,this.refineTimer)clearTimeout(this.refineTimer);this.refineTimer=setTimeout(()=>{if(this.refineTimer=null,!this.lowDetail)return;this.lowDetail=!1,this.scheduleRender()},hm),this.scheduleRender()}set onInitError(e){this.initErrorHandler=e}renderSelf(e){if(this.pending)this.scheduleRender();e.clear(Ic);let t=this.frame,r=Et(this._ctx);if(!t||!r||!ur(this._ctx.capabilities)){if(!t&&!this.failed)$i(e,this.width,this.height,Ic);return}let n=Math.max(1,Math.round(this.width*r.width)),i=Math.max(1,Math.round(this.height*r.height)),s=Math.min(n/t.width,i/t.height),o=Math.max(1,Math.round(t.width*s)),a=Math.max(1,Math.round(t.height*s)),l=Math.max(1,Math.round(o/r.width)),c=Math.max(1,Math.round(a/r.height));e.drawImage(t,Math.floor((this.width-l)/2),Math.floor((this.height-c)/2),l,c,o,a,0,0,t.width,t.height,"auto")}onResize(e,t){if(super.onResize(e,t),this.sceneController)this.scheduleRender()}set visible(e){if(super.visible=e,e&&this.sceneController)this.scheduleRender()}get visible(){return super.visible}destroySelf(){if(this.destroyRequested=!0,this.refineTimer)clearTimeout(this.refineTimer);if(this.releaseFrame(),!this.rendering)this.releaseGpu();super.destroySelf()}scheduleRender(){if(this.pending=!0,this.scheduled||this.rendering||this.failed||this.destroyRequested||!this.visible||!this.dimensions())return;this.scheduled=!0,queueMicrotask(()=>{this.scheduled=!1,this.flushRender()})}async flushRender(){if(this.rendering||this.failed||this.destroyRequested)return;this.rendering=!0;try{while(this.pending&&!this.destroyRequested){if(!this.visible||!this.dimensions())break;this.pending=!1,await this.renderFrame()}}catch(e){this.failed=!0;let t=e instanceof Error?e.message:String(e);this.initErrorHandler?.(t)}finally{if(this.rendering=!1,this.destroyRequested||this.failed)this.releaseGpu();else if(this.pending)this.scheduleRender()}}dimensions(){let e=Et(this._ctx);if(!e||this.width<=0||this.height<=0)return null;return cc(this.width,this.height,e.width,e.height,this.lowDetail?{density:fm}:void 0)}async renderFrame(){let e=this.dimensions();if(!e)return;if(await this.ensureRenderer(e.width,e.height),this.destroyRequested)return;this.resizeRenderer(e.width,e.height),this.sceneController.update(this.currentModel,e.width/e.height),await this.webgpuRenderer.render(this.sceneController.scene,this.sceneController.camera);let t=await this.captureFrame(e.width,e.height);if(!t)return;this.releaseFrame(),this.frame=t,this.requestRender()}async ensureRenderer(e,t){if(this.webgpuRenderer)return;let r=performance.now();await cm();let n=await lm();this.device=n,jo("voxel raster device",r);let i=new om(n,e,t,am.NONE);this.canvas=i;let s=new um({canvas:i,device:n,alpha:!0});this.webgpuRenderer=s,s.outputColorSpace=zi.SRGBColorSpace,s.toneMapping=zi.NoToneMapping,s.setClearColor(new zi.Color().setRGB(qi[0]/255,qi[1]/255,qi[2]/255,zi.SRGBColorSpace),1),s.setSize(e,t,!1),await s.init(),jo("voxel raster renderer init",r),this.context=i.getContext("webgpu"),this.renderWidth=e,this.renderHeight=t}resizeRenderer(e,t){if(e===this.renderWidth&&t===this.renderHeight)return;this.canvas.setSize(e,t),this.webgpuRenderer.setSize(e,t,!1),this.renderWidth=e,this.renderHeight=t,this.releaseReadback()}async captureFrame(e,t){let r=this.device,n=this.context,i=Math.ceil(e*4/256)*256,s=i*t;if(!this.readbackBuffer||this.readbackSize!==s)this.releaseReadback(),this.readbackBuffer=r.createBuffer({label:"Flatblox voxel image readback",size:s,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.readbackSize=s;let o=n.getCurrentTexture();n.switchTextures();let a=r.createCommandEncoder({label:"Flatblox voxel image capture"});if(a.copyTextureToBuffer({texture:o},{buffer:this.readbackBuffer,bytesPerRow:i,rowsPerImage:t},{width:e,height:t}),r.queue.submit([a.finish()]),await this.readbackBuffer.mapAsync(GPUMapMode.READ),this.destroyRequested)return this.readbackBuffer.unmap(),null;let l=new Uint8Array(this.readbackBuffer.getMappedRange().slice(0));this.readbackBuffer.unmap();let c=o.format,u=nm.fromPixels(l,e,t,{stride:i,format:c==="bgra8unorm"?"bgra8":"rgba8",alpha:"opaque"});return u.ensureEncodedPng(),u}releaseFrame(){this.frame?.dispose(),this.frame=null}releaseReadback(){this.readbackBuffer?.destroy(),this.readbackBuffer=null,this.readbackSize=0}releaseGpu(){this.releaseReadback(),this.sceneController.dispose();try{this.webgpuRenderer?.dispose()}catch(e){if(!this.failed)console.error("Could not dispose voxel renderer:",e)}this.canvas?.destroy(),this.device?.destroy(),this.webgpuRenderer=null,this.canvas=null,this.context=null,this.device=null}}var kc={name:"flatblox-tui",version:"0.2.11",description:"Flatblox pixel art editor for the terminal",homepage:"https://flatblox.com",keywords:["pixel-art","pixel art","voxel","tui","terminal","cli","editor","sprite","bun","opentui","solid","three"],author:{name:"Nico Pellerin",email:"hello@nicopellerin.io"},license:"MIT",type:"module",bin:{"flatblox-tui":"dist/index.js"},files:["dist","README.md"],publishConfig:{access:"public"},scripts:{build:"bun --env-file=../web/.env scripts/build.ts",dev:"bun --env-file=../web/.env --watch src/index.tsx",prepack:"bun run build",start:"bun --env-file=../web/.env src/index.tsx",typecheck:"tsc --noEmit",test:"bun test --preload ./scripts/preload.ts"},dependencies:{"@opentui/core":"^0.5.10","@opentui/solid":"^0.5.10","@opentui/three":"^0.5.10",bun:"^1.4.0","bun-webgpu":"0.1.7","solid-js":"1.9.12",three:"0.177.0"},devDependencies:{"@flatblox/editor-core":"workspace:*","@flatblox/shared":"workspace:*","@supabase/supabase-js":"^2.49.4","@types/bun":"latest","@types/three":"0.177.0",typescript:"~5.9.3"}};var es=`v${kc.version}`;import{NativeImage as Rc,parseColor as gm}from"@opentui/core";Yt({fitted_image:Gn});var mm=new URL("./flatblox-logo.png",import.meta.url),pm=Rc.load(mm),Wo=new Map;function bm(e){let t=Wo.get(e);if(!t)t=pm.then((r)=>{let[n,i,s]=gm(e).toInts(),o=new Uint8Array(r.width*r.height*4);for(let l=0;l<o.length;l+=4)o[l]=n,o[l+1]=i,o[l+2]=s,o[l+3]=255;let a=Rc.fromRgba(o,r.width,r.height);try{return a.composite(r)}finally{a.dispose()}}),t.catch(()=>Wo.delete(e)),Wo.set(e,t);return t}function zr(e){let t=gt(),r=Xr(),[n,i]=Y(),s=!1;return br(()=>{bm(e.backgroundColor).then((o)=>{if(!s)i(o),t.requestRender()},()=>{})}),je(()=>{s=!0}),Z(Ie,{get when(){return ut(()=>!!r())()&&n()},get fallback(){return(()=>{var o=I("box");return h(o,"alignItems","center"),h(o,"justifyContent","center"),L(o,Z(Ie,{get when(){return e.height>=2},get fallback(){return(()=>{var a=I("text"),l=I("b");return T(a,l),T(l,Ee("FLATBLOX")),he((c)=>h(a,"fg",e.foregroundColor,c)),a})()},get children(){var a=I("ascii_font");return h(a,"text","FLATBLOX"),h(a,"font","tiny"),he((l)=>{var c=`${e.id}-ascii`,u=e.foregroundColor,d=e.backgroundColor;return c!==l.e&&(l.e=h(a,"id",c,l.e)),u!==l.t&&(l.t=h(a,"color",u,l.t)),d!==l.a&&(l.a=h(a,"backgroundColor",d,l.a)),l},{e:void 0,t:void 0,a:void 0}),a}})),he((a)=>{var{id:l,width:c,height:u,backgroundColor:d}=e;return l!==a.e&&(a.e=h(o,"id",l,a.e)),c!==a.t&&(a.t=h(o,"width",c,a.t)),u!==a.a&&(a.a=h(o,"height",u,a.a)),d!==a.o&&(a.o=h(o,"backgroundColor",d,a.o)),a},{e:void 0,t:void 0,a:void 0,o:void 0}),o})()},get children(){var o=I("fitted_image");return he((a)=>{var l=e.id,c=n(),u=e.width,d=e.height,f=e.backgroundColor;return l!==a.e&&(a.e=h(o,"id",l,a.e)),c!==a.t&&(a.t=h(o,"source",c,a.t)),u!==a.a&&(a.a=h(o,"width",u,a.a)),d!==a.o&&(a.o=h(o,"height",d,a.o)),f!==a.i&&(a.i=h(o,"background",f,a.i)),a},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),o}})}Yt({pixel_grid:Fo,voxel_raster:Ko,voxel_preview:Ho});var E={background:Ye("hsl(275 45% 12%)"),panel:Ye("hsl(275 45% 14%)"),panelActive:Ye("hsl(275 45% 17%)"),card:Ye("hsl(275 45% 19%)"),border:Ye("hsl(275 45% 31%)"),text:Ye("hsl(278 100% 80%)"),muted:Ye("hsl(278 41% 65%)"),accent:Ye("hsl(315 68% 71%)"),accentText:Ye("hsl(278 70% 80%)"),warning:Ye("hsl(37 100% 71%)"),textPink:Ye("hsl(308, 50%, 75%)"),orangeActive:Ye("hsl(28, 80%, 38%)")};function Ye(e){let t=cr(e);return t?In(t):"#ffffff"}function $t(e){return e[0].toUpperCase()+e.slice(1)}function wm(e){let t=e.depthAt(e.cursor.x,e.cursor.y);return t===null?"-":String(t)}function vm(e){return(()=>{var t=I("box");return h(t,"flexDirection","column"),h(t,"gap",0),L(t,Z(vt,{get each(){return e.colors.slice(0,10)},children:(r,n)=>{let i=J(()=>(e.refresh(),e.session.selectedColorIndex===n())),s=n()===9?"0":String(n()+1);return(()=>{var o=I("box"),a=I("text"),l=Ee(" ");return T(o,a),h(o,"height",1),h(o,"flexDirection","row"),h(o,"paddingX",1),L(o,Z(Un,{get color(){return Ye(r)},get background(){return ut(()=>!!i())()?E.panelActive:E.panel}}),a),T(a,l),L(a,()=>i()?" \u203A ":" ",l),L(a,s,l),L(a,()=>Ye(r),null),he((c)=>{var u=i()?E.panelActive:E.panel,d=i()?E.text:E.muted;return u!==c.e&&(c.e=h(o,"backgroundColor",u,c.e)),d!==c.t&&(c.t=h(a,"fg",d,c.t)),c},{e:void 0,t:void 0}),o})()}})),t})()}function _m(e){let t=J(()=>(e.refresh(),{tool:$t(e.session.tool),mirrorX:e.session.mirrorX?"on":"off",mirrorY:e.session.mirrorY?"on":"off",cursor:`${e.session.cursor.x+1}, ${e.session.cursor.y+1}`,depth:wm(e.session)}));return(()=>{var r=I("box"),n=I("box"),i=I("box"),s=I("text"),o=Ee("Tool: "),a=I("text"),l=Ee("Cursor: "),c=I("text"),u=Ee("Depth: "),d=I("box"),f=I("box"),g=I("box"),A=I("text"),m=Ee("Mirror X: "),b=I("text"),w=Ee("Mirror Y: ");return T(r,n),h(r,"id","sidebar"),h(r,"flexDirection","column"),h(r,"paddingY",1),T(n,i),T(n,d),T(n,f),T(n,g),h(n,"width","100%"),h(n,"flexDirection","column"),h(n,"paddingX",1),T(i,s),T(i,a),T(i,c),h(i,"flexDirection","column"),T(s,o),L(s,()=>t().tool,null),T(a,l),L(a,()=>t().cursor,null),T(c,u),L(c,()=>t().depth,null),h(d,"height",1),L(n,Z(vm,{get session(){return e.session},get colors(){return e.colors},get refresh(){return e.refresh}}),f),h(f,"height",1),T(g,A),T(g,b),h(g,"flexDirection","column"),T(A,m),L(A,()=>t().mirrorX,null),T(b,w),L(b,()=>t().mirrorY,null),he((p)=>{var C=e.visible?28:0,_=e.visible,y=E.panel,v=E.textPink,x=E.textPink,B=E.textPink,M=E.muted,P=E.muted;return C!==p.e&&(p.e=h(r,"width",C,p.e)),_!==p.t&&(p.t=h(r,"visible",_,p.t)),y!==p.a&&(p.a=h(r,"backgroundColor",y,p.a)),v!==p.o&&(p.o=h(s,"fg",v,p.o)),x!==p.i&&(p.i=h(a,"fg",x,p.i)),B!==p.n&&(p.n=h(c,"fg",B,p.n)),M!==p.s&&(p.s=h(A,"fg",M,p.s)),P!==p.h&&(p.h=h(b,"fg",P,p.h)),p},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),r})()}function Cm(e){let t=J(()=>{e.refresh();let r=`${e.session.mirrorX?"X":"-"}${e.session.mirrorY?"Y":"-"}`;return{tool:$t(e.session.tool),color:Ye(e.colors[e.session.selectedColorIndex]??e.session.activeColor),mirror:r}});return(()=>{var r=I("box"),n=I("text"),i=Ee("Tool "),s=Ee(" Color "),o=I("text"),a=Ee(" "),l=Ee(" Mirror ");return T(r,n),T(r,o),h(r,"border",!0),h(r,"borderStyle","rounded"),h(r,"paddingX",1),h(r,"flexDirection","row"),T(n,i),T(n,s),L(n,()=>t().tool,s),L(r,Z(Un,{get color(){return t().color},get background(){return E.panel}}),o),T(o,a),T(o,l),L(o,()=>t().color,l),L(o,()=>t().mirror,null),he((c)=>{var u=e.visible?3:0,d=e.visible,f=E.border,g=E.panel,A=E.textPink,m=E.textPink;return u!==c.e&&(c.e=h(r,"height",u,c.e)),d!==c.t&&(c.t=h(r,"visible",d,c.t)),f!==c.a&&(c.a=h(r,"borderColor",f,c.a)),g!==c.o&&(c.o=h(r,"backgroundColor",g,c.o)),A!==c.i&&(c.i=h(n,"fg",A,c.i)),m!==c.n&&(c.n=h(o,"fg",m,c.n)),c},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),r})()}var xm=11;function Em(e){return[["Move","Arrow keys or H J K L"],["Paint","Space or Enter"],["Tools","D draw | E erase | F fill | R rectangle | O circle"],["Shapes","Space sets a corner, Space again draws, Esc cancels"],["Extrude","X toggle | Space or S raise | A lower | shows depths"],["Palette","1\u20130 direct | [ and ] cycle"],["Mirroring","Shift+X horizontal | Shift+Y vertical"],["Blender","B connect / disconnect"],["History","U undo | Ctrl+Z undo | Ctrl+Y redo"],["View","C toggle 2D / 3D | P split view | arrows orbit | R reset"],["Zoom","- / +"],["Save","Ctrl+S"],["Export","Ctrl+E choose SVG / OBJ / PNG and a destination"],["Help","?"],...e?[["Artworks","Escape"],["Quit","Q"]]:[["Quit","Q or Escape"]],["",""],["Mouse","Click to paint | right-click to erase"],["","Shift+click targets the lower half-cell"],["",""],["","Press ? or Escape to close help."]]}function Sm(e){let t=J(()=>Em(e.canGoBack)),r=J(()=>Math.max(1,Math.min(70,e.width-2))),n=J(()=>Math.max(1,Math.min(t().length+4,e.height-2)));return(()=>{var i=I("box");return h(i,"id","help-overlay"),h(i,"position","absolute"),h(i,"zIndex",20),h(i,"border",!0),h(i,"title"," Keyboard & mouse "),h(i,"padding",1),L(i,Z(vt,{get each(){return t()},children:([s,o])=>(()=>{var a=I("box"),l=I("text"),c=I("text");return T(a,l),T(a,c),h(a,"flexDirection","row"),L(l,()=>s.padEnd(xm)),L(c,o),he((u)=>{var{textPink:d,accentText:f}=E;return d!==u.e&&(u.e=h(l,"fg",d,u.e)),f!==u.t&&(u.t=h(c,"fg",f,u.t)),u},{e:void 0,t:void 0}),a})()})),he((s)=>{var o=Math.max(0,Math.floor((e.width-r())/2)),a=Math.max(0,Math.floor((e.height-n())/2)),l=r(),c=n(),u=e.visible,d=E.border,f=E.panel,g=E.accent;return o!==s.e&&(s.e=h(i,"left",o,s.e)),a!==s.t&&(s.t=h(i,"top",a,s.t)),l!==s.a&&(s.a=h(i,"width",l,s.a)),c!==s.o&&(s.o=h(i,"height",c,s.o)),u!==s.i&&(s.i=h(i,"visible",u,s.i)),d!==s.n&&(s.n=h(i,"borderColor",d,s.n)),f!==s.s&&(s.s=h(i,"backgroundColor",f,s.s)),g!==s.h&&(s.h=h(i,"titleColor",g,s.h)),s},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),i})()}function Im(e){let t=J(()=>Math.max(1,Math.min(48,e.width-4))),r=J(()=>Math.max(1,Math.min(7,e.height-2))),n=J(()=>r()>=7?1:0);return(()=>{var i=I("box"),s=I("box"),o=I("input"),a=I("box"),l=I("text");return T(i,s),h(i,"id","filename-modal"),h(i,"position","absolute"),h(i,"zIndex",30),h(i,"border",!0),h(i,"title"," Save artwork "),h(i,"flexDirection","column"),T(s,o),T(s,a),T(s,l),h(s,"flexGrow",1),h(s,"width","100%"),h(s,"padding",1),h(s,"flexDirection","column"),h(o,"id","artwork-name-input"),h(o,"width","100%"),h(o,"maxLength",mo),h(o,"focused",!0),h(o,"onKeyDown",(c)=>{if(c.eventType!=="release"&&c.name==="escape")c.preventDefault(),e.onCancel()}),L(l,()=>e.error||"Enter save \xB7 Esc cancel"),he((c)=>{var u=Math.max(0,Math.floor((e.width-t())/2)),d=Math.max(0,Math.floor((e.height-r())/2)),f=t(),g=r(),A=E.border,m=E.panel,b=E.accent,w=E.panel,p=e.value,C=E.panelActive,_=E.panelActive,y=E.text,v=E.text,x=e.onInput,B=e.onSubmit,M=n(),P=e.error?E.warning:E.accentText;return u!==c.e&&(c.e=h(i,"left",u,c.e)),d!==c.t&&(c.t=h(i,"top",d,c.t)),f!==c.a&&(c.a=h(i,"width",f,c.a)),g!==c.o&&(c.o=h(i,"height",g,c.o)),A!==c.i&&(c.i=h(i,"borderColor",A,c.i)),m!==c.n&&(c.n=h(i,"backgroundColor",m,c.n)),b!==c.s&&(c.s=h(i,"titleColor",b,c.s)),w!==c.h&&(c.h=h(s,"backgroundColor",w,c.h)),p!==c.r&&(c.r=h(o,"value",p,c.r)),C!==c.d&&(c.d=h(o,"backgroundColor",C,c.d)),_!==c.l&&(c.l=h(o,"focusedBackgroundColor",_,c.l)),y!==c.u&&(c.u=h(o,"textColor",y,c.u)),v!==c.c&&(c.c=h(o,"focusedTextColor",v,c.c)),x!==c.w&&(c.w=h(o,"onInput",x,c.w)),B!==c.m&&(c.m=h(o,"on:enter",B,c.m)),M!==c.f&&(c.f=h(a,"height",M,c.f)),P!==c.y&&(c.y=h(l,"fg",P,c.y)),c},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0,m:void 0,f:void 0,y:void 0}),i})()}var km={svg:"SVG flat vector",obj:"OBJ voxel mesh (+ .mtl)",png:"PNG 16px per cell"};function Rm(e){let t=J(()=>Math.max(1,Math.min(66,e.width-4))),r=J(()=>Math.max(1,Math.min(12,e.height-2)));return(()=>{var n=I("box"),i=I("box"),s=I("box"),o=I("text"),a=I("input"),l=I("box"),c=I("text");return T(n,i),h(n,"id","export-modal"),h(n,"position","absolute"),h(n,"zIndex",30),h(n,"border",!0),h(n,"title"," Export artwork "),h(n,"flexDirection","column"),T(i,s),T(i,o),T(i,a),T(i,l),T(i,c),h(i,"flexGrow",1),h(i,"width","100%"),h(i,"padding",1),h(i,"flexDirection","column"),L(i,Z(vt,{each:Mt,children:(u,d)=>(()=>{var f=I("box"),g=I("text");return T(f,g),h(f,"flexDirection","row"),L(g,()=>e.focus==="formats"&&e.cursor===d()?"\u203A ":" ",null),L(g,()=>e.formats.includes(u)?"[x] ":"[ ] ",null),L(g,()=>km[u],null),he((A)=>h(g,"fg",e.focus==="formats"&&e.cursor===d()?E.accent:E.text,A)),f})()}),s),h(s,"height",1),T(o,Ee("Destination")),h(a,"id","export-path-input"),h(a,"width","100%"),h(a,"onKeyDown",(u)=>{if(u.name==="escape"||u.name==="tab")u.preventDefault()}),h(l,"height",1),L(c,()=>e.error||(e.focus==="formats"?"Space toggle \xB7 Tab destination \xB7 Enter export \xB7 Esc cancel":"Tab formats \xB7 Enter export \xB7 Esc cancel")),he((u)=>{var d=Math.max(0,Math.floor((e.width-t())/2)),f=Math.max(0,Math.floor((e.height-r())/2)),g=t(),A=r(),m=E.border,b=E.panel,w=E.accent,p=E.panel,C=E.textPink,_=e.path,y=E.panelActive,v=E.panelActive,x=E.text,B=E.text,M=e.focus==="path",P=e.onPathInput,O=e.onSubmit,W=e.error?E.warning:E.accentText;return d!==u.e&&(u.e=h(n,"left",d,u.e)),f!==u.t&&(u.t=h(n,"top",f,u.t)),g!==u.a&&(u.a=h(n,"width",g,u.a)),A!==u.o&&(u.o=h(n,"height",A,u.o)),m!==u.i&&(u.i=h(n,"borderColor",m,u.i)),b!==u.n&&(u.n=h(n,"backgroundColor",b,u.n)),w!==u.s&&(u.s=h(n,"titleColor",w,u.s)),p!==u.h&&(u.h=h(i,"backgroundColor",p,u.h)),C!==u.r&&(u.r=h(o,"fg",C,u.r)),_!==u.d&&(u.d=h(a,"value",_,u.d)),y!==u.l&&(u.l=h(a,"backgroundColor",y,u.l)),v!==u.u&&(u.u=h(a,"focusedBackgroundColor",v,u.u)),x!==u.c&&(u.c=h(a,"textColor",x,u.c)),B!==u.w&&(u.w=h(a,"focusedTextColor",B,u.w)),M!==u.m&&(u.m=h(a,"focused",M,u.m)),P!==u.f&&(u.f=h(a,"onInput",P,u.f)),O!==u.y&&(u.y=h(a,"on:enter",O,u.y)),W!==u.g&&(u.g=h(c,"fg",W,u.g)),u},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0,m:void 0,f:void 0,y:void 0,g:void 0}),n})()}function qr(e){let t=gt(),r=Xr(),n=Hr(),[i,s]=Y(0),[o,a]=Y("Ready"),[l,c]=Y(!1),[u,d]=Y(null),[f,g]=Y(null),[A,m]=Y(!1),[b,w]=Y(!1),[p,C]=Y(""),[_,y]=Y(""),[v,x]=Y(!1),[B,M]=Y(["svg"]),[P,O]=Y(0),[W,Q]=Y("formats"),[j,ee]=Y(""),[ie,z]=Y(""),[Be,Pe]=Y(null),[Je,ze]=Y(2),[pe,te]=Y(!1),[q,F]=Y(!1),[U,ae]=Y(""),se=uc(),[Ne,be]=Y(Vt),[rt,qe]=Y(dr),[Le,Fe]=Y(null),Rt=!e.blenderLive,H=e.blenderLive??new Ro(()=>e.session.toDocument()),[S,fe]=Y(H.getStatus()),Ge=H.onStatus(fe);je(()=>{if(Ge(),Rt)H.dispose()});let At=J(()=>n().width>=88&&n().height>=19),De=()=>i(),lt=()=>q()&&!pe()?"50%":"100%",et=J(()=>{let R=Be();if(R!==null)return R;let{width:k,height:N}=n(),me=At()?k-30:k-2,Ae=N-(At()?6:9);return lc(e.session.size,q()?Math.floor((me-1)/2):me,Ae)}),[pt,re]=Y(0),Oe=(R=!1)=>{if(s((k)=>k+1),R)re((k)=>k+1),H.sync()},Tt=()=>(i(),e.session.dirty),qt=J(()=>(i(),kn(e.session.palette,e.session.paletteColorAdjustment.saturation,e.session.paletteColorAdjustment.lightness))),Mr=J(()=>(pt(),Qt(e.session.grid,e.session.paletteColorAdjustment.saturation,e.session.paletteColorAdjustment.lightness))),er=J(()=>{i();let R=u(),k=e.session.tool;if(!R||!Zr(k))return;let N=e.session;return{points:N.shapePreview(k,R,N.cursor).flatMap((Ae)=>Ln(N.size,Ae,N.mirrorX,N.mirrorY)),color:Ye(qt()[N.selectedColorIndex]??N.activeColor)}}),tr=J(()=>(i(),{grid:Mr(),revision:pt(),cursor:e.session.cursor,zoom:et(),preview:er(),depthLabels:e.session.tool==="extrude"})),Nr=J(()=>({grid:Mr(),revision:pt(),yaw:Ne(),pitch:rt(),zoom:Je()})),Ot=()=>{if(f())g(null)},An=(R,k)=>{if(!Zr(R))return!1;let N=u();if(!N)return d({...k}),a(`${$t(R)} from ${k.x+1}, ${k.y+1} \xB7 Space or click to finish \xB7 Esc cancels`),Oe(),!0;let me=e.session.applyShape(R,N,k);return d(null),Oe(me),a(me?`${$t(R)} drawn`:"No change"),!0},Ai=()=>{if(!u())return!1;return d(null),a(`${$t(e.session.tool)} cancelled`),Oe(),!0},gi=(R=e.session.tool)=>{if(Ot(),An(R,e.session.cursor))return;let k=e.session.applyAtCursor(R);Oe(k),a(k?`${$t(R)} applied`:"No change")},ge=(R,k)=>{Ot(),e.session.moveCursor(R,k);let N=Le(),me=N?e.session.applyAtCursor(N):!1;Oe(me),a(N&&me?`${$t(N)} at ${e.session.cursor.x+1}, ${e.session.cursor.y+1}`:`Cell ${e.session.cursor.x+1}, ${e.session.cursor.y+1}`)},ye=(R)=>{let k=R==="undo"?e.session.undo():e.session.redo();a(k?R==="undo"?"Undo":"Redo":`Nothing to ${R}`),Oe(k)},Ue=(R)=>{e.session.selectNextColor(R),Ot(),a(`Color ${e.session.selectedColorIndex+1}`),Oe()},Ce=async()=>{if(A())return;let R=e.session.revision,k=e.session.toDocument();m(!0),a("Saving\u2026");try{let N;if(e.saveDocument)N=await e.saveDocument(k);else{let Ae=e.filePath??`${e.session.filename}.flatblox.json`,bt=Nn(k);if(e.writeFile)await e.writeFile(Ae,bt);else await $r(Ae,bt);N=`Saved ${Ae}`}let me=e.session.markSaved(R);g(null),a(me?N||"Saved":`${N||"Saved"}; newer edits remain unsaved`),Oe()}catch(N){let me=N instanceof Error?N.message:String(N);a(`Save failed: ${me}`)}finally{m(!1)}},de=()=>Ui("",e.session.filename,Hn(e.filePath,e.session.filename)),ne="",le=async()=>{if(A())return;let R=await pc();ne=R?Ui(`${R}/`,e.session.filename,de()):de(),ee(ne),z(""),O(0),Q("formats"),x(!0),a("Choose export formats and destination")},Me=()=>{x(!1),a("Export cancelled")},Ve=(R)=>{M((k)=>k.includes(R)?k.filter((N)=>N!==R):Mt.filter((N)=>N===R||k.includes(N))),z("")},Se=async()=>{let R=B();if(R.length===0){z("Select at least one format");return}let k=Ui(j(),e.session.filename,de());x(!1),m(!0),a("Exporting\u2026");try{let me=(await Hi(e.session.toDocument(),k,R,e.writeFile)).map((Ae)=>ym(Ae));if(a(`Exported ${me.join(", ")} to ${ts(k)}`),ts(k)!==ts(ne))await bc(ts(k)).catch(()=>{})}catch(N){let me=N instanceof Error?N.message:String(N);a(`Export failed: ${me}`)}finally{m(!1)}},nt=(R)=>{let k=R.name.toLowerCase();if(k==="escape")Me();else if(k==="tab")Q((N)=>N==="path"?"formats":"path");else if(W()==="path")return;else if(k==="return"||k==="enter")Se();else if(k==="up"||k==="k")O((N)=>(N+Mt.length-1)%Mt.length);else if(k==="down"||k==="j")O((N)=>(N+1)%Mt.length);else if(hr(R))Ve(Mt[P()])},it=()=>{if(e.promptForFilenameOnSave){C(""),y(""),w(!0),a("Name artwork before saving");return}Ce()},xt=(R)=>{let k=Rn(R);if(!k){y("Enter an artwork name");return}e.session.rename(k),y(""),w(!1),Oe(),Ce()},Us=()=>{w(!1),y(""),a("Save cancelled")},gn=(R)=>{if(!Tt()||f()===R){if(R==="back"&&e.onBack)e.onBack();else t.destroy();return}g(R),a(R==="back"?"Unsaved changes \u2014 press Escape again to return":"Unsaved changes \u2014 press Q again to quit")},mi=(R)=>{Ot();let{x:k,y:N}=e.session.cursor,me=e.session.extrudeAt(k,N,R);Oe(me);let Ae=e.session.depthAt(k,N);a(Ae===null?"No cell to extrude":me?`Depth ${Ae}`:`Depth ${Ae} (${R>0?"max":"min"})`)},Lr=(R)=>{e.session.setTool(R),d(null),Ot(),a(`${$t(R)} tool`),Oe()},pi=(R)=>{let k=pe(),N=k?Je():et(),me=k?0.25:1,Ae=k&&R>0&&N<1?1:N+R,bt=Math.max(me,Math.min(8,Ae));if(k)ze(bt);else Pe(bt);a(`Zoom ${bt}\xD7`)},Zd=()=>{if(!pe()&&!se){a("3D preview is unavailable on this platform");return}if(!pe()&&U()){a(`3D unavailable: ${U()}`);return}Fe(null),d(null),te((R)=>(a(R?"2D editor":"Voxel preview"),!R))},$d=()=>{if(!q()&&!se){a("3D preview is unavailable on this platform");return}if(!q()&&U()){a(`3D unavailable: ${U()}`);return}te(!1),F((R)=>(a(R?"2D editor":"Split view"),!R))},Xd=(R,k)=>{be((N)=>N+R*0.16),qe((N)=>Math.max(0.18,Math.min(1.15,N-k*0.12))),a("3D orbit")},zd=()=>{be(Vt),qe(dr),a("Rotation reset")},Ta=(R)=>{if(ae(R),F(!1),!pe())return;te(!1),a(`3D unavailable: ${R}`)},qd=async()=>{let R=H.getStatus();if(R.state==="connected"||R.state==="connecting"){H.disconnect(),a("Blender Live disconnected");return}a("Connecting to Blender\u2026");let k=await H.connect();a(k.state==="connected"?"Drawing live in Blender":k.message??"Blender Live disconnected")},eh=(R)=>{if(b()||v()||l())return;e.session.setCursor(R.x,R.y);let k=R.tool??e.session.tool;if(Ot(),An(k,{x:R.x,y:R.y}))return;let N=e.session.applyAt(R.x,R.y,k);a(N?`${$t(k)} at ${R.x+1}, ${R.y+1}`:`Cell ${R.x+1}, ${R.y+1}`),Oe(N)};jr((R)=>{let k=R.name.toLowerCase(),N=R.sequence,me=hr(R),Ae=xr(k);if(R.eventType==="release"){if(me)Fe(null);return}if(b())return;if(v()){nt(R);return}if(l()){if(k==="escape"||N==="?")c(!1);return}let bt=k==="q"||k==="escape"||R.ctrl&&k==="c";if(f()&&!bt)g(null);if(R.ctrl){if(k==="s")it();else if(k==="e")le();else if(k==="z"&&R.shift)ye("redo");else if(k==="z")ye("undo");else if(k==="y")ye("redo");else if(k==="c")gn("quit");return}if(N==="?"){c(!0);return}if(k==="escape"&&Ai())return;if(k==="escape"&&e.onBack){gn("back");return}if(k==="q"||k==="escape"){gn("quit");return}if(k==="c"){Zd();return}if(k==="p"){$d();return}if(pe()){if(k==="r")zd();else if(Ae)Xd(Ae.dx,Ae.dy);else if(N==="+"||k==="+"||k==="=")pi(1);else if(N==="-"||k==="-")pi(-1);return}if(Ae)ge(Ae.dx,Ae.dy);else if(me){let ct=e.session.tool;Fe(R.source==="kitty"&&(ct==="draw"||ct==="erase")?ct:null),gi(ct)}else if(k==="b")qd();else if(k==="d")Lr("draw");else if(k==="e")Lr("erase");else if(k==="f")Lr("fill");else if(k==="r")Lr("rectangle");else if(k==="o")Lr("circle");else if(k==="x"&&(R.shift||N==="X"))e.session.toggleMirrorX(),a(`Mirror X ${e.session.mirrorX?"on":"off"}`),Oe();else if(k==="y"&&(R.shift||N==="Y"))e.session.toggleMirrorY(),a(`Mirror Y ${e.session.mirrorY?"on":"off"}`),Oe();else if(k==="x")Lr(e.session.tool==="extrude"?"draw":"extrude");else if(k==="s")mi(1);else if(k==="a")mi(-1);else if(k==="u")ye("undo");else if(N==="+"||k==="+"||k==="=")pi(1);else if(N==="-"||k==="-")pi(-1);else if(N==="[")Ue(-1);else if(N==="]")Ue(1);else if(/^[0-9]$/.test(k))e.session.selectColor(k==="0"?9:Number(k)-1),a(`Color ${e.session.selectedColorIndex+1}`),Oe()},{release:!0});let th=()=>{i();let R=e.session.dirty?" \u25CF":"";return`${e.session.filename}${R} ${e.session.size}\xD7${e.session.size}`},rh=()=>{switch(S().state){case"connecting":return"connecting";case"connected":return"live";case"error":return"error";default:return"off"}},Oa=J(()=>`Blender:${rh()} | ${o()}`),Ba=J(()=>`C ${pe()?"2D":"3D"} \xB7 P split \xB7 ${pe()?"R reset \xB7 ":""}`+"-/+ zoom \xB7 ? help \xB7 Ctrl+S save \xB7 Ctrl+E export \xB7 "+`${e.onBack?"Esc artworks \xB7 ":""}Q quit`),nh=J(()=>Oa().length+Ba().length+1<=n().width-2);return(()=>{var R=I("box"),k=I("box"),N=I("text"),me=I("b"),Ae=I("box"),bt=I("text"),ct=I("box"),rr=I("box"),nr=I("pixel_grid"),jt=I("box"),Hs=I("text");return T(R,k),T(R,ct),T(R,jt),h(R,"width","100%"),h(R,"height","100%"),h(R,"flexDirection","column"),T(k,N),T(k,Ae),T(k,bt),h(k,"height",3),h(k,"paddingX",1),h(k,"paddingY",1),h(k,"flexDirection","row"),h(k,"justifyContent","space-between"),T(N,me),L(me,es),h(Ae,"height",1),h(Ae,"flexBasis",0),h(Ae,"flexGrow",1),h(Ae,"flexDirection","row"),h(Ae,"justifyContent","center"),L(Ae,Z(zr,{id:"dashboard-wordmark",width:14,height:1,get backgroundColor(){return E.panel},get foregroundColor(){return E.accent}})),L(bt,th),T(ct,rr),h(ct,"flexGrow",1),h(ct,"flexDirection","row"),h(ct,"paddingLeft",1),h(ct,"paddingY",1),h(ct,"gap",1),T(rr,nr),h(rr,"flexGrow",1),h(rr,"flexDirection","row"),h(rr,"gap",1),h(rr,"overflow","hidden"),h(nr,"id","pixel-grid"),h(nr,"height","100%"),h(nr,"flexGrow",1),h(nr,"onCell",eh),L(rr,Z(Ie,{when:se,get children(){return Z(Ie,{get when(){return r()},get fallback(){return(()=>{var K=I("voxel_preview");return h(K,"id","voxel-preview"),h(K,"height","100%"),h(K,"flexGrow",1),h(K,"onInitError",Ta),he((we)=>{var ir=lt(),sr=pe()||q(),or=Nr();return ir!==we.e&&(we.e=h(K,"width",ir,we.e)),sr!==we.t&&(we.t=h(K,"visible",sr,we.t)),or!==we.a&&(we.a=h(K,"model",or,we.a)),we},{e:void 0,t:void 0,a:void 0}),K})()},get children(){var K=I("voxel_raster");return h(K,"id","voxel-preview"),h(K,"height","100%"),h(K,"flexGrow",1),h(K,"onInitError",Ta),he((we)=>{var ir=lt(),sr=pe()||q(),or=Nr();return ir!==we.e&&(we.e=h(K,"width",ir,we.e)),sr!==we.t&&(we.t=h(K,"visible",sr,we.t)),or!==we.a&&(we.a=h(K,"model",or,we.a)),we},{e:void 0,t:void 0,a:void 0}),K}})}}),null),L(ct,Z(Ie,{get when(){return ut(()=>!!At())()&&!pe()},get children(){return Z(_m,{get session(){return e.session},get colors(){return qt()},refresh:De,visible:!0})}}),null),L(R,Z(Ie,{get when(){return ut(()=>!At())()&&!pe()},get children(){return Z(Cm,{get session(){return e.session},get colors(){return qt()},refresh:De,visible:!0})}}),jt),T(jt,Hs),h(jt,"height",1),h(jt,"paddingX",1),h(jt,"flexDirection","row"),h(jt,"justifyContent","space-between"),L(Hs,Oa),L(jt,Z(Ie,{get when(){return nh()},get children(){var K=I("text");return L(K,Ba),he((we)=>h(K,"fg",E.muted,we)),K}}),null),L(R,Z(Sm,{get width(){return n().width},get height(){return n().height},get visible(){return l()},get canGoBack(){return Boolean(e.onBack)}}),null),L(R,Z(Ie,{get when(){return v()},get children(){return Z(Rm,{get width(){return n().width},get height(){return n().height},get formats(){return B()},get cursor(){return P()},get focus(){return W()},get path(){return j()},get error(){return ie()},onPathInput:(K)=>{if(ee(K),ie())z("")},onSubmit:()=>void Se(),onCancel:Me})}}),null),L(R,Z(Ie,{get when(){return b()},get children(){return Z(Im,{get width(){return n().width},get height(){return n().height},get value(){return p()},get error(){return _()},onInput:(K)=>{if(C(K),_())y("")},onSubmit:xt,onCancel:Us})}}),null),he((K)=>{var{background:we,panel:ir}=E,sr=S().state==="error"?E.warning:E.accentText,or=Tt()?E.warning:E.muted,Pa=At()&&!pe()?0:1,Da=E.background,Ma=E.background,Na=lt(),La=!pe(),Fa=tr(),Ga=E.panelActive,Ua=o().startsWith("Save failed")||S().state==="error"?E.warning:E.textPink;return we!==K.e&&(K.e=h(R,"backgroundColor",we,K.e)),ir!==K.t&&(K.t=h(k,"backgroundColor",ir,K.t)),sr!==K.a&&(K.a=h(N,"fg",sr,K.a)),or!==K.o&&(K.o=h(bt,"fg",or,K.o)),Pa!==K.i&&(K.i=h(ct,"paddingRight",Pa,K.i)),Da!==K.n&&(K.n=h(ct,"backgroundColor",Da,K.n)),Ma!==K.s&&(K.s=h(rr,"backgroundColor",Ma,K.s)),Na!==K.h&&(K.h=h(nr,"width",Na,K.h)),La!==K.r&&(K.r=h(nr,"visible",La,K.r)),Fa!==K.d&&(K.d=h(nr,"model",Fa,K.d)),Ga!==K.l&&(K.l=h(jt,"backgroundColor",Ga,K.l)),Ua!==K.u&&(K.u=h(Hs,"fg",Ua,K.u)),K},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0}),R})()}import{readFile as v0,unlink as _0}from"fs/promises";import{homedir as C0}from"os";import{join as wd,resolve as xd}from"path";var su=dh(iu(),1),{__extends:Kx,__assign:Wx,__rest:Er,__decorate:Yx,__param:Qx,__esDecorate:Jx,__runInitializers:Vx,__propKey:Zx,__setFunctionName:$x,__metadata:Xx,__awaiter:ou,__generator:zx,__exportStar:qx,__createBinding:eE,__values:tE,__read:rE,__spread:nE,__spreadArrays:iE,__spreadArray:sE,__await:oE,__asyncGenerator:aE,__asyncDelegator:lE,__asyncValues:cE,__makeTemplateObject:uE,__importStar:dE,__importDefault:hE,__classPrivateFieldGet:fE,__classPrivateFieldSet:AE,__classPrivateFieldIn:gE,__addDisposableResource:mE,__disposeResources:pE,__rewriteRelativeImportExtension:bE}=su.default;var au=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)};class Yn extends Error{constructor(e,t="FunctionsError",r){super(e);this.name=t,this.context=r}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class ss extends Yn{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Qn extends Yn{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Jn extends Yn{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Wn;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(Wn||(Wn={}));class os{constructor(e,{headers:t={},customFetch:r,region:n=Wn.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=au(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return ou(this,arguments,void 0,function*(t,r={}){var n;let i,s;try{let{headers:o,method:a,body:l,signal:c,timeout:u}=r,d={},{region:f}=r;if(!f)f=this.region;let g=new URL(`${this.url}/${t}`);if(f&&f!=="any")d["x-region"]=f,g.searchParams.set("forceFunctionRegion",f);let A;if(l&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o))if(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer)d["Content-Type"]="application/octet-stream",A=l;else if(typeof l==="string")d["Content-Type"]="text/plain",A=l;else if(typeof FormData<"u"&&l instanceof FormData)A=l;else d["Content-Type"]="application/json",A=JSON.stringify(l);else if(l&&typeof l!=="string"&&!(typeof Blob<"u"&&l instanceof Blob)&&!(l instanceof ArrayBuffer)&&!(typeof FormData<"u"&&l instanceof FormData))A=JSON.stringify(l);else A=l;let m=c;if(u)if(s=new AbortController,i=setTimeout(()=>s.abort(),u),c)m=s.signal,c.addEventListener("abort",()=>s.abort());else m=s.signal;let b=yield this.fetch(g.toString(),{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),o),body:A,signal:m}).catch((_)=>{throw new ss(_)}),w=b.headers.get("x-relay-error");if(w&&w==="true")throw new Qn(b);if(!b.ok)throw new Jn(b);let p=((n=b.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),C;if(p==="application/json")C=yield b.json();else if(p==="application/octet-stream"||p==="application/pdf")C=yield b.blob();else if(p==="text/event-stream")C=b;else if(p==="multipart/form-data")C=yield b.formData();else C=yield b.text();return{data:C,error:null,response:b}}catch(o){return{data:null,error:o,response:o instanceof Jn||o instanceof Qn?o.context:void 0}}finally{if(i)clearTimeout(i)}})}}var lu=(e)=>Math.min(1000*2**e,30000),Tm=[520,503],hu=["GET","HEAD","OPTIONS"],fu=class extends Error{constructor(e){super(e.message);this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function cu(e,t){return new Promise((r)=>{if(t===null||t===void 0?void 0:t.aborted){r();return}let n=setTimeout(()=>{t===null||t===void 0||t.removeEventListener("abort",i),r()},e);function i(){clearTimeout(n),r()}t===null||t===void 0||t.addEventListener("abort",i)})}function Om(e,t,r,n){if(!n||r>=3)return!1;if(!hu.includes(e))return!1;if(!Tm.includes(t))return!1;return!0}var Bm=class{constructor(e){var t,r,n,i,s;if(this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(r=e.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(n=e.shouldStripNulls)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(i=e.urlLengthLimit)!==null&&i!==void 0?i:8000,this.retryEnabled=(s=e.retry)!==null&&s!==void 0?s:!0,e.fetch)this.fetch=e.fetch;else this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var r=this;if(this.schema===void 0);else if(["GET","HEAD"].includes(this.method))this.headers.set("Accept-Profile",this.schema);else this.headers.set("Content-Profile",this.schema);if(this.method!=="GET"&&this.method!=="HEAD")this.headers.set("Content-Type","application/json");if(this.shouldStripNulls){let o=this.headers.get("Accept");if(o==="application/vnd.pgrst.object+json")this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped");else if(!o||o==="application/json")this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let n=this.fetch,s=(async()=>{let o=0;while(!0){let c=new Headers(r.headers);if(o>0)c.set("X-Retry-Count",String(o));let u;try{u=await n(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body),signal:r.signal})}catch(d){if((d===null||d===void 0?void 0:d.name)==="AbortError"||(d===null||d===void 0?void 0:d.code)==="ABORT_ERR")throw d;if(!hu.includes(r.method))throw d;if(r.retryEnabled&&o<3){let f=lu(o);o++,await cu(f,r.signal);continue}throw d}if(Om(r.method,u.status,o,r.retryEnabled)){var a,l;let d=(a=(l=u.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&a!==void 0?a:null,f=d!==null?Math.max(0,parseInt(d,10)||0)*1000:lu(o);await u.text(),o++,await cu(f,r.signal);continue}return await r.processResponse(u)}})();if(!this.shouldThrowOnError)s=s.catch((o)=>{var a;let l="",c="",u="",d=o===null||o===void 0?void 0:o.cause;if(d){var f,g,A,m;let p=(f=d===null||d===void 0?void 0:d.message)!==null&&f!==void 0?f:"",C=(g=d===null||d===void 0?void 0:d.code)!==null&&g!==void 0?g:"";if(l=`${(A=o===null||o===void 0?void 0:o.name)!==null&&A!==void 0?A:"FetchError"}: ${o===null||o===void 0?void 0:o.message}`,l+=`
18
18
 
19
- Caused by: ${(m=d===null||d===void 0?void 0:d.name)!==null&&m!==void 0?m:"Error"}: ${y}`,E)l+=` (${E})`;if(d===null||d===void 0?void 0:d.stack)l+=`
20
- ${d.stack}`}else{var p;l=(p=o===null||o===void 0?void 0:o.stack)!==null&&p!==void 0?p:""}let v=this.url.toString().length;if((o===null||o===void 0?void 0:o.name)==="AbortError"||(o===null||o===void 0?void 0:o.code)==="ABORT_ERR"){if(u="",c="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit)c+=`. Note: Your request URL is ${v} 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.`}else if((d===null||d===void 0?void 0:d.name)==="HeadersOverflowError"||(d===null||d===void 0?void 0:d.code)==="UND_ERR_HEADERS_OVERFLOW"){if(u="",c="HTTP headers exceeded server limits (typically 16KB)",v>this.urlLengthLimit)c+=`. Your request URL is ${v} 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.`}return{success:!1,error:{message:`${(a=o===null||o===void 0?void 0:o.name)!==null&&a!==void 0?a:"FetchError"}: ${o===null||o===void 0?void 0:o.message}`,details:l,hint:c,code:u},data:null,count:null,status:0,statusText:""}});return s.then(e,t)}async processResponse(e){var t=this;let r=null,n=null,i=null,s=e.status,o=e.statusText;if(e.ok){var a,l;if(t.method!=="HEAD"){var c;let A=await e.text();if(A==="");else if(t.headers.get("Accept")==="text/csv")n=A;else if(t.headers.get("Accept")&&((c=t.headers.get("Accept"))===null||c===void 0?void 0:c.includes("application/vnd.pgrst.plan+text")))n=A;else n=JSON.parse(A)}let u=(a=t.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),d=(l=e.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");if(u&&d&&d.length>1)i=parseInt(d[1]);if(t.isMaybeSingle&&Array.isArray(n))if(n.length>1)r={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,i=null,s=406,o="Not Acceptable";else if(n.length===1)n=n[0];else n=null}else{let u=await e.text();try{if(r=JSON.parse(u),Array.isArray(r)&&e.status===404)n=[],r=null,s=200,o="OK"}catch(d){if(e.status===404&&u==="")s=204,o="No Content";else r={message:u}}if(r&&t.shouldThrowOnError)throw new eu(r)}return{success:r===null,error:r,data:n,count:i,status:s,statusText:o}}returns(){return this}overrideTypes(){return this}},nm=class extends rm{select(e){let t=!1,r=(e!==null&&e!==void 0?e:"*").split("").map((n)=>{if(/\s/.test(n)&&!t)return"";if(n==='"')t=!t;return n}).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!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},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{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,`${e}`),this.url.searchParams.set(s,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:n=!1,wal:i=!1,format:s="text"}={}){var o;let a=[e?"analyze":null,t?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";if(this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json")return this;else return this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}},Xc=new RegExp("[,()]"),zr=class extends nm{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map((n)=>{if(typeof n==="string"&&Xc.test(n))return`"${n}"`;else return`${n}`}).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){let r=Array.from(new Set(t)).map((n)=>{if(typeof n==="string"&&Xc.test(n))return`"${n}"`;else return`${n}`}).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){if(typeof t==="string")this.url.searchParams.append(e,`cs.${t}`);else if(Array.isArray(t))this.url.searchParams.append(e,`cs.{${t.join(",")}}`);else this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`);return this}containedBy(e,t){if(typeof t==="string")this.url.searchParams.append(e,`cd.${t}`);else if(Array.isArray(t))this.url.searchParams.append(e,`cd.{${t.join(",")}}`);else this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`);return this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){if(typeof t==="string")this.url.searchParams.append(e,`ov.${t}`);else this.url.searchParams.append(e,`ov.{${t.join(",")}}`);return this}textSearch(e,t,{config:r,type:n}={}){let i="";if(n==="plain")i="pl";else if(n==="phrase")i="ph";else if(n==="websearch")i="w";let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${s}.${t}`),this}match(e){return Object.entries(e).filter(([t,r])=>r!==void 0).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},im=class{constructor(e,{headers:t={},schema:r,fetch:n,urlLengthLimit:i=8000,retry:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=n,this.urlLengthLimit=i,this.retry=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:n}=t!==null&&t!==void 0?t:{},i=r?"HEAD":"GET",s=!1,o=(e!==null&&e!==void 0?e:"*").split("").map((c)=>{if(/\s/.test(c)&&!s)return"";if(c==='"')s=!s;return c}).join(""),{url:a,headers:l}=this.cloneRequestState();if(a.searchParams.set("select",o),n)l.append("Prefer",`count=${n}`);return new zr({method:i,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:r=!0}={}){var n;let i="POST",{url:s,headers:o}=this.cloneRequestState();if(t)o.append("Prefer",`count=${t}`);if(!r)o.append("Prefer","missing=default");if(Array.isArray(e)){let a=e.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map((c)=>`"${c}"`);s.searchParams.set("columns",l.join(","))}}return new zr({method:"POST",url:s,headers:o,schema:this.schema,body:e,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){var s;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),t!==void 0)a.searchParams.set("on_conflict",t);if(n)l.append("Prefer",`count=${n}`);if(!i)l.append("Prefer","missing=default");if(Array.isArray(e)){let c=e.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){let u=[...new Set(c)].map((d)=>`"${d}"`);a.searchParams.set("columns",u.join(","))}}return new zr({method:"POST",url:a,headers:l,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var r;let n="PATCH",{url:i,headers:s}=this.cloneRequestState();if(t)s.append("Prefer",`count=${t}`);return new zr({method:"PATCH",url:i,headers:s,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;let r="DELETE",{url:n,headers:i}=this.cloneRequestState();if(e)i.append("Prefer",`count=${e}`);return new zr({method:"DELETE",url:n,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function Qn(e){return Qn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qn(e)}function sm(e,t){if(Qn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Qn(n)!="object")return n;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function om(e){var t=sm(e,"string");return Qn(t)=="symbol"?t:t+""}function am(e,t,r){return(t=om(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function zc(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Yi(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?zc(Object(r),!0).forEach(function(n){am(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):zc(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var tu=class e{constructor(t,{headers:r={},schema:n,fetch:i,timeout:s,urlLengthLimit:o=8000,retry:a}={}){this.url=t,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let l=i!==null&&i!==void 0?i:globalThis.fetch;if(s!==void 0&&s>0)this.fetch=(c,u)=>{let d=new AbortController,A=setTimeout(()=>d.abort(),s),f=u===null||u===void 0?void 0:u.signal;if(f){if(f.aborted)return clearTimeout(A),l(c,u);let g=()=>{clearTimeout(A),d.abort()};return f.addEventListener("abort",g,{once:!0}),l(c,Yi(Yi({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(A),f.removeEventListener("abort",g)})}return l(c,Yi(Yi({},u),{},{signal:d.signal})).finally(()=>clearTimeout(A))};else this.fetch=l;this.retry=a}from(t){if(!t||typeof t!=="string"||t.trim()==="")throw Error("Invalid relation name: relation must be a non-empty string.");return new im(new URL(`${this.url}/${t}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(t,r={},{head:n=!1,get:i=!1,count:s}={}){var o;let a,l=new URL(`${this.url}/rpc/${t}`),c,u=(f)=>f!==null&&typeof f==="object"&&(!Array.isArray(f)||f.some(u)),d=n&&Object.values(r).some(u);if(d)a="POST",c=r;else if(n||i)a=n?"HEAD":"GET",Object.entries(r).filter(([f,g])=>g!==void 0).map(([f,g])=>[f,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([f,g])=>{l.searchParams.append(f,g)});else a="POST",c=r;let A=new Headers(this.headers);if(d)A.set("Prefer",s?`count=${s},return=minimal`:"return=minimal");else if(s)A.set("Prefer",`count=${s}`);return new zr({method:a,url:l,headers:A,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class ru{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?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 t=globalThis.process;if(t){let r=t.versions;if(r&&r.node){let n=r.node,i=parseInt(n.replace(/^v/,"").split(".")[0]);if(i>=22){if(typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};return{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
19
+ Caused by: ${(m=d===null||d===void 0?void 0:d.name)!==null&&m!==void 0?m:"Error"}: ${p}`,C)l+=` (${C})`;if(d===null||d===void 0?void 0:d.stack)l+=`
20
+ ${d.stack}`}else{var b;l=(b=o===null||o===void 0?void 0:o.stack)!==null&&b!==void 0?b:""}let w=this.url.toString().length;if((o===null||o===void 0?void 0:o.name)==="AbortError"||(o===null||o===void 0?void 0:o.code)==="ABORT_ERR"){if(u="",c="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit)c+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`}else if((d===null||d===void 0?void 0:d.name)==="HeadersOverflowError"||(d===null||d===void 0?void 0:d.code)==="UND_ERR_HEADERS_OVERFLOW"){if(u="",c="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit)c+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`}return{success:!1,error:{message:`${(a=o===null||o===void 0?void 0:o.name)!==null&&a!==void 0?a:"FetchError"}: ${o===null||o===void 0?void 0:o.message}`,details:l,hint:c,code:u},data:null,count:null,status:0,statusText:""}});return s.then(e,t)}async processResponse(e){var t=this;let r=null,n=null,i=null,s=e.status,o=e.statusText;if(e.ok){var a,l;if(t.method!=="HEAD"){var c;let f=await e.text();if(f==="");else if(t.headers.get("Accept")==="text/csv")n=f;else if(t.headers.get("Accept")&&((c=t.headers.get("Accept"))===null||c===void 0?void 0:c.includes("application/vnd.pgrst.plan+text")))n=f;else n=JSON.parse(f)}let u=(a=t.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),d=(l=e.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");if(u&&d&&d.length>1)i=parseInt(d[1]);if(t.isMaybeSingle&&Array.isArray(n))if(n.length>1)r={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,i=null,s=406,o="Not Acceptable";else if(n.length===1)n=n[0];else n=null}else{let u=await e.text();try{if(r=JSON.parse(u),Array.isArray(r)&&e.status===404)n=[],r=null,s=200,o="OK"}catch(d){if(e.status===404&&u==="")s=204,o="No Content";else r={message:u}}if(r&&t.shouldThrowOnError)throw new fu(r)}return{success:r===null,error:r,data:n,count:i,status:s,statusText:o}}returns(){return this}overrideTypes(){return this}},Pm=class extends Bm{select(e){let t=!1,r=(e!==null&&e!==void 0?e:"*").split("").map((n)=>{if(/\s/.test(n)&&!t)return"";if(n==='"')t=!t;return n}).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!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},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{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,`${e}`),this.url.searchParams.set(s,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:n=!1,wal:i=!1,format:s="text"}={}){var o;let a=[e?"analyze":null,t?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";if(this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json")return this;else return this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}},uu=new RegExp("[,()]"),tn=class extends Pm{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map((n)=>{if(typeof n==="string"&&uu.test(n))return`"${n}"`;else return`${n}`}).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){let r=Array.from(new Set(t)).map((n)=>{if(typeof n==="string"&&uu.test(n))return`"${n}"`;else return`${n}`}).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){if(typeof t==="string")this.url.searchParams.append(e,`cs.${t}`);else if(Array.isArray(t))this.url.searchParams.append(e,`cs.{${t.join(",")}}`);else this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`);return this}containedBy(e,t){if(typeof t==="string")this.url.searchParams.append(e,`cd.${t}`);else if(Array.isArray(t))this.url.searchParams.append(e,`cd.{${t.join(",")}}`);else this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`);return this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){if(typeof t==="string")this.url.searchParams.append(e,`ov.${t}`);else this.url.searchParams.append(e,`ov.{${t.join(",")}}`);return this}textSearch(e,t,{config:r,type:n}={}){let i="";if(n==="plain")i="pl";else if(n==="phrase")i="ph";else if(n==="websearch")i="w";let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${s}.${t}`),this}match(e){return Object.entries(e).filter(([t,r])=>r!==void 0).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},Dm=class{constructor(e,{headers:t={},schema:r,fetch:n,urlLengthLimit:i=8000,retry:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=n,this.urlLengthLimit=i,this.retry=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:n}=t!==null&&t!==void 0?t:{},i=r?"HEAD":"GET",s=!1,o=(e!==null&&e!==void 0?e:"*").split("").map((c)=>{if(/\s/.test(c)&&!s)return"";if(c==='"')s=!s;return c}).join(""),{url:a,headers:l}=this.cloneRequestState();if(a.searchParams.set("select",o),n)l.append("Prefer",`count=${n}`);return new tn({method:i,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:r=!0}={}){var n;let i="POST",{url:s,headers:o}=this.cloneRequestState();if(t)o.append("Prefer",`count=${t}`);if(!r)o.append("Prefer","missing=default");if(Array.isArray(e)){let a=e.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map((c)=>`"${c}"`);s.searchParams.set("columns",l.join(","))}}return new tn({method:"POST",url:s,headers:o,schema:this.schema,body:e,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){var s;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),t!==void 0)a.searchParams.set("on_conflict",t);if(n)l.append("Prefer",`count=${n}`);if(!i)l.append("Prefer","missing=default");if(Array.isArray(e)){let c=e.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){let u=[...new Set(c)].map((d)=>`"${d}"`);a.searchParams.set("columns",u.join(","))}}return new tn({method:"POST",url:a,headers:l,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var r;let n="PATCH",{url:i,headers:s}=this.cloneRequestState();if(t)s.append("Prefer",`count=${t}`);return new tn({method:"PATCH",url:i,headers:s,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;let r="DELETE",{url:n,headers:i}=this.cloneRequestState();if(e)i.append("Prefer",`count=${e}`);return new tn({method:"DELETE",url:n,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function Vn(e){return Vn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Vn(e)}function Mm(e,t){if(Vn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(Vn(n)!="object")return n;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Nm(e){var t=Mm(e,"string");return Vn(t)=="symbol"?t:t+""}function Lm(e,t,r){return(t=Nm(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function du(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function as(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?du(Object(r),!0).forEach(function(n){Lm(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):du(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var Au=class e{constructor(t,{headers:r={},schema:n,fetch:i,timeout:s,urlLengthLimit:o=8000,retry:a}={}){this.url=t,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let l=i!==null&&i!==void 0?i:globalThis.fetch;if(s!==void 0&&s>0)this.fetch=(c,u)=>{let d=new AbortController,f=setTimeout(()=>d.abort(),s),g=u===null||u===void 0?void 0:u.signal;if(g){if(g.aborted)return clearTimeout(f),l(c,u);let A=()=>{clearTimeout(f),d.abort()};return g.addEventListener("abort",A,{once:!0}),l(c,as(as({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(f),g.removeEventListener("abort",A)})}return l(c,as(as({},u),{},{signal:d.signal})).finally(()=>clearTimeout(f))};else this.fetch=l;this.retry=a}from(t){if(!t||typeof t!=="string"||t.trim()==="")throw Error("Invalid relation name: relation must be a non-empty string.");return new Dm(new URL(`${this.url}/${t}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(t,r={},{head:n=!1,get:i=!1,count:s}={}){var o;let a,l=new URL(`${this.url}/rpc/${t}`),c,u=(g)=>g!==null&&typeof g==="object"&&(!Array.isArray(g)||g.some(u)),d=n&&Object.values(r).some(u);if(d)a="POST",c=r;else if(n||i)a=n?"HEAD":"GET",Object.entries(r).filter(([g,A])=>A!==void 0).map(([g,A])=>[g,Array.isArray(A)?`{${A.join(",")}}`:`${A}`]).forEach(([g,A])=>{l.searchParams.append(g,A)});else a="POST",c=r;let f=new Headers(this.headers);if(d)f.set("Prefer",s?`count=${s},return=minimal`:"return=minimal");else if(s)f.set("Prefer",`count=${s}`);return new tn({method:a,url:l,headers:f,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class gu{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?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 t=globalThis.process;if(t){let r=t.versions;if(r&&r.node){let n=r.node,i=parseInt(n.replace(/^v/,"").split(".")[0]);if(i>=22){if(typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};return{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
21
21
  import ws from "ws"
22
22
  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 t=e.error||"WebSocket not supported in this environment.";if(e.workaround)t+=`
23
23
 
24
- Suggested solution: ${e.workaround}`;throw Error(t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch(e){return!1}}}var Bo=ru;var nu="2.103.0";var iu=`realtime-js/${nu}`,su="1.0.0",Oo="2.0.0",ou=Oo;var au=1e4;var lu=100;var Bt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Qi={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var Jn={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};class Ji{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!==null&&e!==void 0?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event==="string")return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;if(this._isArrayBuffer((t=e.payload)===null||t===void 0?void 0:t.payload))return this._encodeBinaryUserBroadcastPush(e);else return this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;let n=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var t,r;let n=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:{},s=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,s)}_encodeUserBroadcastPush(e,t,r){var n,i;let s=e.topic,o=(n=e.ref)!==null&&n!==void 0?n:"",a=(i=e.join_ref)!==null&&i!==void 0?i:"",l=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},u=Object.keys(c).length===0?"":JSON.stringify(c);if(a.length>255)throw Error(`joinRef length ${a.length} exceeds maximum of 255`);if(o.length>255)throw Error(`ref length ${o.length} exceeds maximum of 255`);if(s.length>255)throw Error(`topic length ${s.length} exceeds maximum of 255`);if(l.length>255)throw Error(`userEvent length ${l.length} exceeds maximum of 255`);if(u.length>255)throw Error(`metadata length ${u.length} exceeds maximum of 255`);let d=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+o.length+s.length+l.length+u.length,A=new ArrayBuffer(this.HEADER_LENGTH+d),f=new DataView(A),g=0;f.setUint8(g++,this.KINDS.userBroadcastPush),f.setUint8(g++,a.length),f.setUint8(g++,o.length),f.setUint8(g++,s.length),f.setUint8(g++,l.length),f.setUint8(g++,u.length),f.setUint8(g++,t),Array.from(a,(p)=>f.setUint8(g++,p.charCodeAt(0))),Array.from(o,(p)=>f.setUint8(g++,p.charCodeAt(0))),Array.from(s,(p)=>f.setUint8(g++,p.charCodeAt(0))),Array.from(l,(p)=>f.setUint8(g++,p.charCodeAt(0))),Array.from(u,(p)=>f.setUint8(g++,p.charCodeAt(0)));var m=new Uint8Array(A.byteLength+r.byteLength);return m.set(new Uint8Array(A),0),m.set(new Uint8Array(r),A.byteLength),m.buffer}decode(e,t){if(this._isArrayBuffer(e)){let r=this._binaryDecode(e);return t(r)}if(typeof e==="string"){let r=JSON.parse(e),[n,i,s,o,a]=r;return t({join_ref:n,ref:i,topic:s,event:o,payload:a})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,n)}}_decodeUserBroadcast(e,t,r){let n=t.getUint8(1),i=t.getUint8(2),s=t.getUint8(3),o=t.getUint8(4),a=this.HEADER_LENGTH+4,l=r.decode(e.slice(a,a+n));a=a+n;let c=r.decode(e.slice(a,a+i));a=a+i;let u=r.decode(e.slice(a,a+s));a=a+s;let d=e.slice(a,e.byteLength),A=o===this.JSON_ENCODING?JSON.parse(r.decode(d)):d,f={type:this.BROADCAST_EVENT,event:c,payload:A};if(s>0)f.meta=JSON.parse(u);return{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e===null||e===void 0?void 0:e.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}_pick(e,t){if(!e||typeof e!=="object")return{};return Object.fromEntries(Object.entries(e).filter(([r])=>t.includes(r)))}}var ye;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(ye||(ye={}));var Do=(e,t,r={})=>{var n;let i=(n=r.skipTypes)!==null&&n!==void 0?n:[];if(!t)return{};return Object.keys(t).reduce((s,o)=>(s[o]=lm(o,e,t,i),s),{})},lm=(e,t,r,n)=>{let i=t.find((a)=>a.name===e),s=i===null||i===void 0?void 0:i.type,o=r[e];if(s&&!n.includes(s))return cu(s,o);return Po(o)},cu=(e,t)=>{if(e.charAt(0)==="_"){let r=e.slice(1,e.length);return hm(t,r)}switch(e){case ye.bool:return cm(t);case ye.float4:case ye.float8:case ye.int2:case ye.int4:case ye.int8:case ye.numeric:case ye.oid:return um(t);case ye.json:case ye.jsonb:return dm(t);case ye.timestamp:return Am(t);case ye.abstime:case ye.date:case ye.daterange:case ye.int4range:case ye.int8range:case ye.money:case ye.reltime:case ye.text:case ye.time:case ye.timestamptz:case ye.timetz:case ye.tsrange:case ye.tstzrange:return Po(t);default:return Po(t)}},Po=(e)=>e,cm=(e)=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},um=(e)=>{if(typeof e==="string"){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},dm=(e)=>{if(typeof e==="string")try{return JSON.parse(e)}catch(t){return e}return e},hm=(e,t)=>{if(typeof e!=="string")return e;let r=e.length-1,n=e[r];if(e[0]==="{"&&n==="}"){let s,o=e.slice(1,r);try{s=JSON.parse("["+o+"]")}catch(a){s=o?o.split(","):[]}return s.map((a)=>cu(t,a))}return e},Am=(e)=>{if(typeof e==="string")return e.replace(" ","T");return e},Vi=(e)=>{let t=new URL(e);if(t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),t.pathname===""||t.pathname==="/")t.pathname="/api/broadcast";else t.pathname=t.pathname+"/api/broadcast";return t.href};var Vn=(e)=>{if(typeof e==="function")return e;else return function(){return e}},gm=typeof self<"u"?self:null,en=typeof window<"u"?window:null,Ot=gm||en||globalThis,mm="2.0.0",pm=1e4,bm=1000,Pt={connecting:0,open:1,closing:2,closed:3},dt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Xt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},No={longpoll:"longpoll",websocket:"websocket"},ym={complete:4},Mo="base64url.bearer.phx.",$i=class{constructor(e,t,r,n){this.channel=e,this.event=t,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){if(this.hasReceived("timeout"))return;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(e,t){if(this.hasReceived(e))t(this.receivedResp.response);return this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:r}){this.recHooks.filter((n)=>n.status===e).forEach((n)=>n.callback(t))}cancelRefEvent(){if(!this.refEvent)return;this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){if(this.timeoutTimer)this.cancelTimeout();this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,(e)=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},uu=class{constructor(e,t){this.callback=e,this.timerCalc=t,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))}},wm=class{constructor(e,t,r){this.state=dt.closed,this.topic=e,this.params=Vn(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new $i(this,Xt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new uu(()=>{if(this.socket.isConnected())this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{if(this.rejoinTimer.reset(),this.isErrored())this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=dt.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach((n)=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",(n)=>{if(this.state=dt.errored,this.socket.hasLogger())this.socket.log("channel",`error ${this.topic}`,n);if(this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{if(this.rejoinTimer.reset(),this.socket.hasLogger())this.socket.log("channel",`close ${this.topic}`);this.state=dt.closed,this.socket.remove(this)}),this.onError((n)=>{if(this.socket.hasLogger())this.socket.log("channel",`error ${this.topic}`,n);if(this.isJoining())this.joinPush.reset();if(this.state=dt.errored,this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{if(this.socket.hasLogger())this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout);if(new $i(this,Xt.leave,Vn({}),this.timeout).send(),this.state=dt.errored,this.joinPush.reset(),this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.on(Xt.reply,(n,i)=>{this.trigger(this.replyEventName(i),n)})}join(e=this.timeout){if(this.joinedOnce)throw Error("tried to join multiple times. 'join' can only be called a single time per channel instance");else return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach((e)=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=dt.closed,this.bindings=[]}onClose(e){this.on(Xt.close,e)}onError(e){return this.on(Xt.error,(t)=>e(t))}on(e,t){let r=this.bindingRef++;return this.bindings.push({event:e,ref:r,callback:t}),r}off(e,t){this.bindings=this.bindings.filter((r)=>!(r.event===e&&(typeof t>"u"||t===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,r=this.timeout){if(t=t||{},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new $i(this,e,function(){return t},r);if(this.canPush())n.send();else n.startTimeout(),this.pushBuffer.push(n);return n}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=dt.leaving;let t=()=>{if(this.socket.hasLogger())this.socket.log("channel",`leave ${this.topic}`);this.trigger(Xt.close,"leave")},r=new $i(this,Xt.leave,Vn({}),e);if(r.receive("ok",()=>t()).receive("timeout",()=>t()),r.send(),!this.canPush())r.trigger("ok",{});return r}onMessage(e,t,r){return t}filterBindings(e,t,r){return!0}isMember(e,t,r,n){if(this.topic!==e)return!1;if(n&&n!==this.joinRef()){if(this.socket.hasLogger())this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:r,joinRef:n});return!1}else return!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){if(this.isLeaving())return;this.socket.leaveOpenTopic(this.topic),this.state=dt.joining,this.joinPush.resend(e)}trigger(e,t,r,n){let i=this.onMessage(e,t,r,n);if(t&&!i)throw Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter((o)=>o.event===e&&this.filterBindings(o,t,r));for(let o=0;o<s.length;o++)s[o].callback(i,r,n||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===dt.closed}isErrored(){return this.state===dt.errored}isJoined(){return this.state===dt.joined}isJoining(){return this.state===dt.joining}isLeaving(){return this.state===dt.leaving}},Xi=class{static request(e,t,r,n,i,s,o){if(Ot.XDomainRequest){let a=new Ot.XDomainRequest;return this.xdomainRequest(a,e,t,n,i,s,o)}else if(Ot.XMLHttpRequest){let a=new Ot.XMLHttpRequest;return this.xhrRequest(a,e,t,r,n,i,s,o)}else if(Ot.fetch&&Ot.AbortController)return this.fetchRequest(e,t,r,n,i,s,o);else throw Error("No suitable XMLHttpRequest implementation found")}static fetchRequest(e,t,r,n,i,s,o){let a={method:e,headers:r,body:n},l=null;if(i){l=new AbortController;let c=setTimeout(()=>l.abort(),i);a.signal=l.signal}return Ot.fetch(t,a).then((c)=>c.text()).then((c)=>this.parseJSON(c)).then((c)=>o&&o(c)).catch((c)=>{if(c.name==="AbortError"&&s)s();else o&&o(null)}),l}static xdomainRequest(e,t,r,n,i,s,o){if(e.timeout=i,e.open(t,r),e.onload=()=>{let a=this.parseJSON(e.responseText);o&&o(a)},s)e.ontimeout=s;return e.onprogress=()=>{},e.send(n),e}static xhrRequest(e,t,r,n,i,s,o,a){e.open(t,r,!0),e.timeout=s;for(let[l,c]of Object.entries(n))e.setRequestHeader(l,c);if(e.onerror=()=>a&&a(null),e.onreadystatechange=()=>{if(e.readyState===ym.complete&&a){let l=this.parseJSON(e.responseText);a(l)}},o)e.ontimeout=o;return e.send(i),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let r=[];for(var n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let i=t?`${t}[${n}]`:n,s=e[n];if(typeof s==="object")r.push(this.serialize(s,i));else r.push(encodeURIComponent(i)+"="+encodeURIComponent(s))}return r.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?";return`${e}${r}${this.serialize(t)}`}},vm=(e)=>{let t="",r=new Uint8Array(e),n=r.byteLength;for(let i=0;i<n;i++)t+=String.fromCharCode(r[i]);return btoa(t)},qr=class{constructor(e,t){if(t&&t.length===2&&t[1].startsWith(Mo))this.authToken=atob(t[1].slice(Mo.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(e),this.readyState=Pt.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+No.websocket),"$1/"+No.longpoll)}endpointURL(){return Xi.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=Pt.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Pt.open||this.readyState===Pt.connecting}poll(){let e={Accept:"application/json"};if(this.authToken)e["X-Phoenix-AuthToken"]=this.authToken;this.ajax("GET",e,null,()=>this.ontimeout(),(t)=>{if(t){var{status:r,token:n,messages:i}=t;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=Pt.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 Error(`unhandled poll status ${r}`)}})}send(e){if(typeof e!=="string")e=vm(e);if(this.currentBatch)this.currentBatch.push(e);else if(this.awaitingBatchAck)this.batchBuffer.push(e);else this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0)}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join(`
25
- `),()=>this.onerror("timeout"),(t)=>{if(this.awaitingBatchAck=!1,!t||t.status!==200)this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1);else if(this.batchBuffer.length>0)this.batchSend(this.batchBuffer),this.batchBuffer=[]})}close(e,t,r){for(let i of this.reqs)i.abort();this.readyState=Pt.closed;let n=Object.assign({code:1000,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});if(this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u")this.onclose(new CloseEvent("close",n));else this.onclose(n)}ajax(e,t,r,n,i){let s,o=()=>{this.reqs.delete(s),n()};s=Xi.request(e,this.endpointURL(),t,r,this.timeout,o,(a)=>{if(this.reqs.delete(s),this.isActive())i(a)}),this.reqs.add(s)}},du=class e{constructor(t,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,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=e.syncState(this.state,i,s,o),this.pendingDiffs.forEach((l)=>{this.state=e.syncDiff(this.state,l,s,o)}),this.pendingDiffs=[],a()}),this.channel.on(n.diff,(i)=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;if(this.inPendingSyncState())this.pendingDiffs.push(i);else this.state=e.syncDiff(this.state,i,s,o),a()})}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(t,r,n,i){let s=this.clone(t),o={},a={};return this.map(s,(l,c)=>{if(!r[l])a[l]=c}),this.map(r,(l,c)=>{let u=s[l];if(u){let d=c.metas.map((m)=>m.phx_ref),A=u.metas.map((m)=>m.phx_ref),f=c.metas.filter((m)=>A.indexOf(m.phx_ref)<0),g=u.metas.filter((m)=>d.indexOf(m.phx_ref)<0);if(f.length>0)o[l]=c,o[l].metas=f;if(g.length>0)a[l]=this.clone(u),a[l].metas=g}else o[l]=c}),this.syncDiff(s,{joins:o,leaves:a},n,i)}static syncDiff(t,r,n,i){let{joins:s,leaves:o}=this.clone(r);if(!n)n=function(){};if(!i)i=function(){};return this.map(s,(a,l)=>{let c=t[a];if(t[a]=this.clone(l),c){let u=t[a].metas.map((A)=>A.phx_ref),d=c.metas.filter((A)=>u.indexOf(A.phx_ref)<0);t[a].metas.unshift(...d)}n(a,c,l)}),this.map(o,(a,l)=>{let c=t[a];if(!c)return;let u=l.metas.map((d)=>d.phx_ref);if(c.metas=c.metas.filter((d)=>u.indexOf(d.phx_ref)<0),i(a,c,l),c.metas.length===0)delete t[a]}),t}static list(t,r){if(!r)r=function(n,i){return i};return this.map(t,(n,i)=>r(n,i))}static map(t,r){return Object.getOwnPropertyNames(t).map((n)=>r(n,t[n]))}static clone(t){return JSON.parse(JSON.stringify(t))}},Zi={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));else{let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));else{let[r,n,i,s,o]=JSON.parse(e);return t({join_ref:r,ref:n,topic:i,event:s,payload:o})}},binaryEncode(e){let{join_ref:t,ref:r,event:n,topic:i,payload:s}=e,o=this.META_LENGTH+t.length+r.length+i.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),l=new DataView(a),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,t.length),l.setUint8(c++,r.length),l.setUint8(c++,i.length),l.setUint8(c++,n.length),Array.from(t,(d)=>l.setUint8(c++,d.charCodeAt(0))),Array.from(r,(d)=>l.setUint8(c++,d.charCodeAt(0))),Array.from(i,(d)=>l.setUint8(c++,d.charCodeAt(0))),Array.from(n,(d)=>l.setUint8(c++,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(e){let t=new DataView(e),r=t.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(e,t,n);case this.KINDS.reply:return this.decodeReply(e,t,n);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,n)}},decodePush(e,t,r){let n=t.getUint8(1),i=t.getUint8(2),s=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(e.slice(o,o+n));o=o+n;let l=r.decode(e.slice(o,o+i));o=o+i;let c=r.decode(e.slice(o,o+s));o=o+s;let u=e.slice(o,e.byteLength);return{join_ref:a,ref:null,topic:l,event:c,payload:u}},decodeReply(e,t,r){let n=t.getUint8(1),i=t.getUint8(2),s=t.getUint8(3),o=t.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(e.slice(a,a+n));a=a+n;let c=r.decode(e.slice(a,a+i));a=a+i;let u=r.decode(e.slice(a,a+s));a=a+s;let d=r.decode(e.slice(a,a+o));a=a+o;let A=e.slice(a,e.byteLength),f={status:d,response:A};return{join_ref:l,ref:c,topic:u,event:Xt.reply,payload:f}},decodeBroadcast(e,t,r){let n=t.getUint8(1),i=t.getUint8(2),s=this.HEADER_LENGTH+2,o=r.decode(e.slice(s,s+n));s=s+n;let a=r.decode(e.slice(s,s+i));s=s+i;let l=e.slice(s,e.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:l}}},hu=class{constructor(e,t={}){if(this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||pm,this.transport=t.transport||Ot.WebSocket||qr,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||Ot&&Ot.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Zi.encode.bind(Zi),this.defaultDecoder=Zi.decode.bind(Zi),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==qr)this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder;else this.encode=this.defaultEncoder,this.decode=this.defaultDecoder;let r=null;if(en&&en.addEventListener)en.addEventListener("pagehide",(n)=>{if(this.conn)this.disconnect(),r=this.connectClock}),en.addEventListener("pageshow",(n)=>{if(r===this.connectClock)r=null,this.connect()}),en.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")this.pageHidden=!0;else if(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean)this.teardown(()=>this.connect())});if(this.heartbeatIntervalMs=t.heartbeatIntervalMs||30000,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=(n)=>{if(t.rejoinAfterMs)return t.rejoinAfterMs(n);else return[1000,2000,5000][n-1]||1e4},this.reconnectAfterMs=(n)=>{if(t.reconnectAfterMs)return t.reconnectAfterMs(n);else return[10,50,100,150,200,250,500,1000,2000][n-1]||5000},this.logger=t.logger||null,!this.logger&&t.debug)this.logger=(n,i,s)=>{console.log(`${n}: ${i}`,s)};this.longpollerTimeout=t.longpollerTimeout||20000,this.params=Vn(t.params||{}),this.endPoint=`${e}/${No.websocket}`,this.vsn=t.vsn||mm,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new uu(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{if(t.beforeReconnect)await t.beforeReconnect();this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return qr}replaceTransport(e){if(this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn)this.conn.close(),this.conn=null;this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=Xi.appendParams(Xi.appendParams(this.endPoint,this.params()),{vsn:this.vsn});if(e.charAt(0)!=="/")return e;if(e.charAt(1)==="/")return`${this.protocol()}:${e}`;return`${this.protocol()}://${location.host}${e}`}disconnect(e,t,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,r)}connect(e){if(e)console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Vn(e);if(this.conn&&!this.disconnecting)return;if(this.longPollFallbackMs&&this.transport!==qr)this.connectWithFallback(qr,this.longPollFallbackMs);else this.transportConnect()}log(e,t,r){this.logger&&this.logger(e,t,r)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let n=this.onMessage((i)=>{if(i.ref===t)this.off([n]),e(Date.now()-r)});return!0}transportName(e){switch(e){case qr:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e=void 0;if(this.authToken)e=["phoenix",`${Mo}${btoa(this.authToken).replace(/=/g,"")}`];this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=(t)=>this.onConnError(t),this.conn.onmessage=(t)=>this.onConnMessage(t),this.conn.onclose=(t)=>this.onConnClose(t)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let r=!1,n=!0,i,s,o=this.transportName(e),a=(l)=>{this.log("transport",`falling back to ${o}...`,l),this.off([i,s]),n=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return a("memorized");if(this.fallbackTimer=setTimeout(a,t),s=this.onError((l)=>{if(this.log("transport","error",l),n&&!r)clearTimeout(this.fallbackTimer),a(l)}),this.fallbackRef)this.off([this.fallbackRef]);this.fallbackRef=this.onOpen(()=>{if(r=!0,!n){let l=this.transportName(e);if(!this.primaryPassedHealthCheck)this.storeSession(`phx:fallback:${l}`,"true");return this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,t),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(){if(this.hasLogger())this.log("transport",`connected to ${this.endPointURL()}`);if(this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat)this.resetHeartbeat();this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){if(this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger())this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),bm,"heartbeat timeout")}}resetHeartbeat(){if(this.conn&&this.conn.skipHeartbeat)return;this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}teardown(e,t,r){if(!this.conn)return e&&e();let n=this.conn;this.waitForBufferDone(n,()=>{if(t)n.close(t,r||"");else n.close();this.waitForSocketClosed(n,()=>{if(this.conn===n)this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null;e&&e()})})}waitForBufferDone(e,t,r=1){if(r===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r)}waitForSocketClosed(e,t,r=1){if(r===5||e.readyState===Pt.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,r+1)},150*r)}onConnClose(e){if(this.conn)this.conn.onclose=()=>{};if(this.hasLogger())this.log("transport","close",e);if(this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean)this.reconnectTimer.scheduleTimeout();this.triggerStateCallbacks("close",e)}onConnError(e){if(this.hasLogger())this.log("transport",e);let t=this.transport,r=this.establishedConnections;if(this.triggerStateCallbacks("error",e,t,r),t===this.transport||r>0)this.triggerChanError()}triggerChanError(){this.channels.forEach((e)=>{if(!(e.isErrored()||e.isLeaving()||e.isClosed()))e.trigger(Xt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Pt.connecting:return"connecting";case Pt.open:return"open";case Pt.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter((t)=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([r])=>e.indexOf(r)===-1)}channel(e,t={}){let r=new wm(e,t,this);return this.channels.push(r),r}push(e){if(this.hasLogger()){let{topic:t,event:r,payload:n,ref:i,join_ref:s}=e;this.log("push",`${t} ${r} (${s}, ${i})`,n)}if(this.isConnected())this.encode(e,(t)=>this.conn.send(t));else this.sendBuffer.push(()=>this.encode(e,(t)=>this.conn.send(t)))}makeRef(){let e=this.ref+1;if(e===this.ref)this.ref=0;else this.ref=e;return this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}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(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){if(this.isConnected()&&this.sendBuffer.length>0)this.sendBuffer.forEach((e)=>e()),this.sendBuffer=[]}onConnMessage(e){this.decode(e.data,(t)=>{let{topic:r,event:n,payload:i,ref:s,join_ref:o}=t;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(l){this.log("error","error in heartbeat callback",l)}if(this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat)this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}if(this.hasLogger())this.log("receive",`${i.status||""} ${r} ${n} ${s&&"("+s+")"||""}`.trim(),i);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];if(!l.isMember(r,n,i,o))continue;l.trigger(n,i,s,o)}this.triggerStateCallbacks("message",t)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([r,n])=>{try{n(...t)}catch(i){this.log("error",`error in ${e} callback`,i)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}leaveOpenTopic(e){let t=this.channels.find((r)=>r.topic===e&&(r.isJoined()||r.isJoining()));if(t){if(this.hasLogger())this.log("transport",`leaving duplicate topic "${e}"`);t.leave()}}};class Cr{constructor(e,t){let r=Cm(t);this.presence=new du(e.getChannel(),r),this.presence.onJoin((n,i,s)=>{let o=Cr.onJoinPayload(n,i,s);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,i,s)=>{let o=Cr.onLeavePayload(n,i,s);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Cr.transformState(this.presence.state)}static transformState(e){return e=_m(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let n=e[r];return t[r]=zi(n),t},{})}static onJoinPayload(e,t,r){let n=Au(t),i=zi(r);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,t,r){let n=Au(t),i=zi(r);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function zi(e){return e.metas.map((t)=>(t.presence_ref=t.phx_ref,delete t.phx_ref,delete t.phx_ref_prev,t))}function _m(e){return JSON.parse(JSON.stringify(e))}function Cm(e){return(e===null||e===void 0?void 0:e.events)&&{events:e.events}}function Au(e){return(e===null||e===void 0?void 0:e.metas)?zi(e):[]}var Lo;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(Lo||(Lo={}));class $n{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new Cr(this.channel.channelAdapter,t)}}class qi{constructor(e,t,r){let n=xm(r);this.channel=e.getSocket().channel(t,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,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}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,t,r){let n;try{n=this.channel.push(e,t,r)}catch(i){throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>lu){let i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===Bt.joined}isJoined(){return this.state===Bt.joined}isJoining(){return this.state===Bt.joining}isClosed(){return this.state===Bt.closed}isLeaving(){return this.state===Bt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function xm(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}var Fo;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(Fo||(Fo={}));var xr;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(xr||(xr={}));var Dt;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(Dt||(Dt={}));class lr{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,t={config:{}},r){var n,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.channelAdapter=new qi(this.socket.socketAdapter,e,this.params),this.presence=new $n(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Vi(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0?void 0:i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,n,i;if(!this.socket.isConnected())this.socket.connect();if(this.channelAdapter.isClosed()){let{config:{broadcast:s,presence:o,private:a}}=this.params,l=(n=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map((A)=>A.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[xr.PRESENCE]&&this.bindings[xr.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,u={},d={broadcast:s,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:l,private:a};if(this.socket.accessTokenValue)u.access_token=this.socket.accessTokenValue;this._onError((A)=>{e===null||e===void 0||e(Dt.CHANNEL_ERROR,A)}),this._onClose(()=>e===null||e===void 0?void 0:e(Dt.CLOSED)),this.updateJoinPayload(Object.assign({config:d},u)),this._updateFilterMessage(),this.channelAdapter.subscribe(t).receive("ok",async({postgres_changes:A})=>{if(!this.socket._isManualToken())this.socket.setAuth();if(A===void 0){e===null||e===void 0||e(Dt.SUBSCRIBED);return}this._updatePostgresBindings(A,e)}).receive("error",(A)=>{this.state=Bt.errored,e===null||e===void 0||e(Dt.CHANNEL_ERROR,Error(JSON.stringify(Object.values(A).join(", ")||"error")))}).receive("timeout",()=>{e===null||e===void 0||e(Dt.TIMED_OUT)})}return this}_updatePostgresBindings(e,t){var r;let n=this.bindings.postgres_changes,i=(r=n===null||n===void 0?void 0:n.length)!==null&&r!==void 0?r:0,s=[];for(let o=0;o<i;o++){let a=n[o],{filter:{event:l,schema:c,table:u,filter:d}}=a,A=e&&e[o];if(A&&A.event===l&&lr.isFilterValueEqual(A.schema,c)&&lr.isFilterValueEqual(A.table,u)&&lr.isFilterValueEqual(A.filter,d))s.push(Object.assign(Object.assign({},a),{id:A.id}));else{this.unsubscribe(),this.state=Bt.errored,t===null||t===void 0||t(Dt.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}if(this.bindings.postgres_changes=s,this.state!=Bt.errored&&t)t(Dt.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){let n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===xr.PRESENCE||e===xr.POSTGRES_CHANGES;if(n&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,t,r)}async httpSend(e,t,r={}){var n;if(t===void 0||t===null)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};if(this.socket.accessTokenValue)i.Authorization=`Bearer ${this.socket.accessTokenValue}`;let s={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,s,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);if(o.status===202)return{success:!0};let a=o.statusText;try{let l=await o.json();a=l.error||l.message||a}catch(l){}return Promise.reject(Error(a))}async send(e,t={}){var r,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:i,payload:s}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};if(this.socket.accessTokenValue)o.Authorization=`Bearer ${this.socket.accessTokenValue}`;let a={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:s,private:this.private}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((n=l.body)===null||n===void 0?void 0:n.cancel()),l.ok?"ok":"error"}catch(l){if(l.name==="AbortError")return"timed out";else return"error"}}else return new Promise((i)=>{var s,o,a;let l=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);if(e.type==="broadcast"&&!((a=(o=(s=this.params)===null||s===void 0?void 0:s.config)===null||o===void 0?void 0:o.broadcast)===null||a===void 0?void 0:a.ack))i("ok");l.receive("ok",()=>i("ok")),l.receive("error",()=>i("error")),l.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise((t)=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>t("ok")).receive("timeout",()=>t("timed out")).receive("error",()=>t("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r),s=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(i),s}_on(e,t,r){let n=e.toLocaleLowerCase(),i=this.channelAdapter.on(e,r),s={type:n,filter:t,callback:r,ref:i};if(this.bindings[n])this.bindings[n].push(s);else this.bindings[n]=[s];return this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,t,r)=>{var n,i,s,o,a,l,c;let u=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(u,r))return!1;let d=(n=this.bindings[u])===null||n===void 0?void 0:n.find((A)=>A.ref===e.ref);if(!d)return!0;if(["broadcast","presence","postgres_changes"].includes(u))if("id"in d){let A=d.id,f=(i=d.filter)===null||i===void 0?void 0:i.event;return A&&((s=t.ids)===null||s===void 0?void 0:s.includes(A))&&(f==="*"||(f===null||f===void 0?void 0:f.toLocaleLowerCase())===((o=t.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{let A=(l=(a=d===null||d===void 0?void 0:d.filter)===null||a===void 0?void 0:a.event)===null||l===void 0?void 0:l.toLocaleLowerCase();return A==="*"||A===((c=t===null||t===void 0?void 0:t.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return d.type.toLocaleLowerCase()===u})}_notThisChannelEvent(e,t){let{close:r,error:n,leave:i,join:s}=Qi;return t&&[r,n,i,s].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,t,r)=>{if(typeof t==="object"&&"ids"in t){let n=t.data,{schema:i,table:s,commit_timestamp:o,type:a,errors:l}=n;return Object.assign(Object.assign({},{schema:i,table:s,commit_timestamp:o,eventType:a,new:{},old:{},errors:l}),this._getPayloadRecords(n))}return t})}copyBindings(e){if(this.joinedOnce)throw Error("cannot copy bindings into joined channel");for(let t in e.bindings)for(let r of e.bindings[t])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(e,t){return(e!==null&&e!==void 0?e:void 0)===(t!==null&&t!==void 0?t:void 0)}_getPayloadRecords(e){let t={new:{},old:{}};if(e.type==="INSERT"||e.type==="UPDATE")t.new=Do(e.columns,e.record);if(e.type==="UPDATE"||e.type==="DELETE")t.old=Do(e.columns,e.old_record);return t}}class es{constructor(e,t){this.socket=new hu(e,t)}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,t,r,n=1e4){return new Promise((i)=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},t,r)})}push(e){this.socket.push(e)}log(e,t,r){this.socket.log(e,t,r)}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()==Jn.connecting}isDisconnecting(){return this.socket.connectionState()==Jn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}var Em={HEARTBEAT_INTERVAL:25000,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Sm=[1000,2000,5000,1e4],Im=1e4,km=`
24
+ Suggested solution: ${e.workaround}`;throw Error(t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch(e){return!1}}}var Qo=gu;var mu="2.103.0";var pu=`realtime-js/${mu}`,bu="1.0.0",Jo="2.0.0",yu=Jo;var wu=1e4;var vu=100;var Nt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ls={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"};class cs{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!==null&&e!==void 0?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event==="string")return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;if(this._isArrayBuffer((t=e.payload)===null||t===void 0?void 0:t.payload))return this._encodeBinaryUserBroadcastPush(e);else return this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;let n=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var t,r;let n=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:{},s=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,s)}_encodeUserBroadcastPush(e,t,r){var n,i;let s=e.topic,o=(n=e.ref)!==null&&n!==void 0?n:"",a=(i=e.join_ref)!==null&&i!==void 0?i:"",l=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},u=Object.keys(c).length===0?"":JSON.stringify(c);if(a.length>255)throw Error(`joinRef length ${a.length} exceeds maximum of 255`);if(o.length>255)throw Error(`ref length ${o.length} exceeds maximum of 255`);if(s.length>255)throw Error(`topic length ${s.length} exceeds maximum of 255`);if(l.length>255)throw Error(`userEvent length ${l.length} exceeds maximum of 255`);if(u.length>255)throw Error(`metadata length ${u.length} exceeds maximum of 255`);let d=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+o.length+s.length+l.length+u.length,f=new ArrayBuffer(this.HEADER_LENGTH+d),g=new DataView(f),A=0;g.setUint8(A++,this.KINDS.userBroadcastPush),g.setUint8(A++,a.length),g.setUint8(A++,o.length),g.setUint8(A++,s.length),g.setUint8(A++,l.length),g.setUint8(A++,u.length),g.setUint8(A++,t),Array.from(a,(b)=>g.setUint8(A++,b.charCodeAt(0))),Array.from(o,(b)=>g.setUint8(A++,b.charCodeAt(0))),Array.from(s,(b)=>g.setUint8(A++,b.charCodeAt(0))),Array.from(l,(b)=>g.setUint8(A++,b.charCodeAt(0))),Array.from(u,(b)=>g.setUint8(A++,b.charCodeAt(0)));var m=new Uint8Array(f.byteLength+r.byteLength);return m.set(new Uint8Array(f),0),m.set(new Uint8Array(r),f.byteLength),m.buffer}decode(e,t){if(this._isArrayBuffer(e)){let r=this._binaryDecode(e);return t(r)}if(typeof e==="string"){let r=JSON.parse(e),[n,i,s,o,a]=r;return t({join_ref:n,ref:i,topic:s,event:o,payload:a})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,n)}}_decodeUserBroadcast(e,t,r){let n=t.getUint8(1),i=t.getUint8(2),s=t.getUint8(3),o=t.getUint8(4),a=this.HEADER_LENGTH+4,l=r.decode(e.slice(a,a+n));a=a+n;let c=r.decode(e.slice(a,a+i));a=a+i;let u=r.decode(e.slice(a,a+s));a=a+s;let d=e.slice(a,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(r.decode(d)):d,g={type:this.BROADCAST_EVENT,event:c,payload:f};if(s>0)g.meta=JSON.parse(u);return{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e===null||e===void 0?void 0:e.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}_pick(e,t){if(!e||typeof e!=="object")return{};return Object.fromEntries(Object.entries(e).filter(([r])=>t.includes(r)))}}var ve;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(ve||(ve={}));var Zo=(e,t,r={})=>{var n;let i=(n=r.skipTypes)!==null&&n!==void 0?n:[];if(!t)return{};return Object.keys(t).reduce((s,o)=>(s[o]=Fm(o,e,t,i),s),{})},Fm=(e,t,r,n)=>{let i=t.find((a)=>a.name===e),s=i===null||i===void 0?void 0:i.type,o=r[e];if(s&&!n.includes(s))return _u(s,o);return Vo(o)},_u=(e,t)=>{if(e.charAt(0)==="_"){let r=e.slice(1,e.length);return jm(t,r)}switch(e){case ve.bool:return Gm(t);case ve.float4:case ve.float8:case ve.int2:case ve.int4:case ve.int8:case ve.numeric:case ve.oid:return Um(t);case ve.json:case ve.jsonb:return Hm(t);case ve.timestamp:return Km(t);case ve.abstime:case ve.date:case ve.daterange:case ve.int4range:case ve.int8range:case ve.money:case ve.reltime:case ve.text:case ve.time:case ve.timestamptz:case ve.timetz:case ve.tsrange:case ve.tstzrange:return Vo(t);default:return Vo(t)}},Vo=(e)=>e,Gm=(e)=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Um=(e)=>{if(typeof e==="string"){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},Hm=(e)=>{if(typeof e==="string")try{return JSON.parse(e)}catch(t){return e}return e},jm=(e,t)=>{if(typeof e!=="string")return e;let r=e.length-1,n=e[r];if(e[0]==="{"&&n==="}"){let s,o=e.slice(1,r);try{s=JSON.parse("["+o+"]")}catch(a){s=o?o.split(","):[]}return s.map((a)=>_u(t,a))}return e},Km=(e)=>{if(typeof e==="string")return e.replace(" ","T");return e},us=(e)=>{let t=new URL(e);if(t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),t.pathname===""||t.pathname==="/")t.pathname="/api/broadcast";else t.pathname=t.pathname+"/api/broadcast";return t.href};var $n=(e)=>{if(typeof e==="function")return e;else return function(){return e}},Ym=typeof self<"u"?self:null,nn=typeof window<"u"?window:null,Lt=Ym||nn||globalThis,Qm="2.0.0",Jm=1e4,Vm=1000,Ft={connecting:0,open:1,closing:2,closed:3},ft={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Xt={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},$o={longpoll:"longpoll",websocket:"websocket"},Zm={complete:4},Xo="base64url.bearer.phx.",ds=class{constructor(e,t,r,n){this.channel=e,this.event=t,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){if(this.hasReceived("timeout"))return;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(e,t){if(this.hasReceived(e))t(this.receivedResp.response);return this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:r}){this.recHooks.filter((n)=>n.status===e).forEach((n)=>n.callback(t))}cancelRefEvent(){if(!this.refEvent)return;this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){if(this.timeoutTimer)this.cancelTimeout();this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,(e)=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},Cu=class{constructor(e,t){this.callback=e,this.timerCalc=t,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))}},$m=class{constructor(e,t,r){this.state=ft.closed,this.topic=e,this.params=$n(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new ds(this,Xt.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Cu(()=>{if(this.socket.isConnected())this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{if(this.rejoinTimer.reset(),this.isErrored())this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=ft.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach((n)=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",(n)=>{if(this.state=ft.errored,this.socket.hasLogger())this.socket.log("channel",`error ${this.topic}`,n);if(this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{if(this.rejoinTimer.reset(),this.socket.hasLogger())this.socket.log("channel",`close ${this.topic}`);this.state=ft.closed,this.socket.remove(this)}),this.onError((n)=>{if(this.socket.hasLogger())this.socket.log("channel",`error ${this.topic}`,n);if(this.isJoining())this.joinPush.reset();if(this.state=ft.errored,this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{if(this.socket.hasLogger())this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout);if(new ds(this,Xt.leave,$n({}),this.timeout).send(),this.state=ft.errored,this.joinPush.reset(),this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.on(Xt.reply,(n,i)=>{this.trigger(this.replyEventName(i),n)})}join(e=this.timeout){if(this.joinedOnce)throw Error("tried to join multiple times. 'join' can only be called a single time per channel instance");else return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach((e)=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ft.closed,this.bindings=[]}onClose(e){this.on(Xt.close,e)}onError(e){return this.on(Xt.error,(t)=>e(t))}on(e,t){let r=this.bindingRef++;return this.bindings.push({event:e,ref:r,callback:t}),r}off(e,t){this.bindings=this.bindings.filter((r)=>!(r.event===e&&(typeof t>"u"||t===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,r=this.timeout){if(t=t||{},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new ds(this,e,function(){return t},r);if(this.canPush())n.send();else n.startTimeout(),this.pushBuffer.push(n);return n}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=ft.leaving;let t=()=>{if(this.socket.hasLogger())this.socket.log("channel",`leave ${this.topic}`);this.trigger(Xt.close,"leave")},r=new ds(this,Xt.leave,$n({}),e);if(r.receive("ok",()=>t()).receive("timeout",()=>t()),r.send(),!this.canPush())r.trigger("ok",{});return r}onMessage(e,t,r){return t}filterBindings(e,t,r){return!0}isMember(e,t,r,n){if(this.topic!==e)return!1;if(n&&n!==this.joinRef()){if(this.socket.hasLogger())this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:r,joinRef:n});return!1}else return!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){if(this.isLeaving())return;this.socket.leaveOpenTopic(this.topic),this.state=ft.joining,this.joinPush.resend(e)}trigger(e,t,r,n){let i=this.onMessage(e,t,r,n);if(t&&!i)throw Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter((o)=>o.event===e&&this.filterBindings(o,t,r));for(let o=0;o<s.length;o++)s[o].callback(i,r,n||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===ft.closed}isErrored(){return this.state===ft.errored}isJoined(){return this.state===ft.joined}isJoining(){return this.state===ft.joining}isLeaving(){return this.state===ft.leaving}},fs=class{static request(e,t,r,n,i,s,o){if(Lt.XDomainRequest){let a=new Lt.XDomainRequest;return this.xdomainRequest(a,e,t,n,i,s,o)}else if(Lt.XMLHttpRequest){let a=new Lt.XMLHttpRequest;return this.xhrRequest(a,e,t,r,n,i,s,o)}else if(Lt.fetch&&Lt.AbortController)return this.fetchRequest(e,t,r,n,i,s,o);else throw Error("No suitable XMLHttpRequest implementation found")}static fetchRequest(e,t,r,n,i,s,o){let a={method:e,headers:r,body:n},l=null;if(i){l=new AbortController;let c=setTimeout(()=>l.abort(),i);a.signal=l.signal}return Lt.fetch(t,a).then((c)=>c.text()).then((c)=>this.parseJSON(c)).then((c)=>o&&o(c)).catch((c)=>{if(c.name==="AbortError"&&s)s();else o&&o(null)}),l}static xdomainRequest(e,t,r,n,i,s,o){if(e.timeout=i,e.open(t,r),e.onload=()=>{let a=this.parseJSON(e.responseText);o&&o(a)},s)e.ontimeout=s;return e.onprogress=()=>{},e.send(n),e}static xhrRequest(e,t,r,n,i,s,o,a){e.open(t,r,!0),e.timeout=s;for(let[l,c]of Object.entries(n))e.setRequestHeader(l,c);if(e.onerror=()=>a&&a(null),e.onreadystatechange=()=>{if(e.readyState===Zm.complete&&a){let l=this.parseJSON(e.responseText);a(l)}},o)e.ontimeout=o;return e.send(i),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let r=[];for(var n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let i=t?`${t}[${n}]`:n,s=e[n];if(typeof s==="object")r.push(this.serialize(s,i));else r.push(encodeURIComponent(i)+"="+encodeURIComponent(s))}return r.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?";return`${e}${r}${this.serialize(t)}`}},Xm=(e)=>{let t="",r=new Uint8Array(e),n=r.byteLength;for(let i=0;i<n;i++)t+=String.fromCharCode(r[i]);return btoa(t)},rn=class{constructor(e,t){if(t&&t.length===2&&t[1].startsWith(Xo))this.authToken=atob(t[1].slice(Xo.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(e),this.readyState=Ft.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+$o.websocket),"$1/"+$o.longpoll)}endpointURL(){return fs.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=Ft.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Ft.open||this.readyState===Ft.connecting}poll(){let e={Accept:"application/json"};if(this.authToken)e["X-Phoenix-AuthToken"]=this.authToken;this.ajax("GET",e,null,()=>this.ontimeout(),(t)=>{if(t){var{status:r,token:n,messages:i}=t;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=Ft.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 Error(`unhandled poll status ${r}`)}})}send(e){if(typeof e!=="string")e=Xm(e);if(this.currentBatch)this.currentBatch.push(e);else if(this.awaitingBatchAck)this.batchBuffer.push(e);else this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0)}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join(`
25
+ `),()=>this.onerror("timeout"),(t)=>{if(this.awaitingBatchAck=!1,!t||t.status!==200)this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1);else if(this.batchBuffer.length>0)this.batchSend(this.batchBuffer),this.batchBuffer=[]})}close(e,t,r){for(let i of this.reqs)i.abort();this.readyState=Ft.closed;let n=Object.assign({code:1000,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});if(this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u")this.onclose(new CloseEvent("close",n));else this.onclose(n)}ajax(e,t,r,n,i){let s,o=()=>{this.reqs.delete(s),n()};s=fs.request(e,this.endpointURL(),t,r,this.timeout,o,(a)=>{if(this.reqs.delete(s),this.isActive())i(a)}),this.reqs.add(s)}},xu=class e{constructor(t,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,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=e.syncState(this.state,i,s,o),this.pendingDiffs.forEach((l)=>{this.state=e.syncDiff(this.state,l,s,o)}),this.pendingDiffs=[],a()}),this.channel.on(n.diff,(i)=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;if(this.inPendingSyncState())this.pendingDiffs.push(i);else this.state=e.syncDiff(this.state,i,s,o),a()})}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(t,r,n,i){let s=this.clone(t),o={},a={};return this.map(s,(l,c)=>{if(!r[l])a[l]=c}),this.map(r,(l,c)=>{let u=s[l];if(u){let d=c.metas.map((m)=>m.phx_ref),f=u.metas.map((m)=>m.phx_ref),g=c.metas.filter((m)=>f.indexOf(m.phx_ref)<0),A=u.metas.filter((m)=>d.indexOf(m.phx_ref)<0);if(g.length>0)o[l]=c,o[l].metas=g;if(A.length>0)a[l]=this.clone(u),a[l].metas=A}else o[l]=c}),this.syncDiff(s,{joins:o,leaves:a},n,i)}static syncDiff(t,r,n,i){let{joins:s,leaves:o}=this.clone(r);if(!n)n=function(){};if(!i)i=function(){};return this.map(s,(a,l)=>{let c=t[a];if(t[a]=this.clone(l),c){let u=t[a].metas.map((f)=>f.phx_ref),d=c.metas.filter((f)=>u.indexOf(f.phx_ref)<0);t[a].metas.unshift(...d)}n(a,c,l)}),this.map(o,(a,l)=>{let c=t[a];if(!c)return;let u=l.metas.map((d)=>d.phx_ref);if(c.metas=c.metas.filter((d)=>u.indexOf(d.phx_ref)<0),i(a,c,l),c.metas.length===0)delete t[a]}),t}static list(t,r){if(!r)r=function(n,i){return i};return this.map(t,(n,i)=>r(n,i))}static map(t,r){return Object.getOwnPropertyNames(t).map((n)=>r(n,t[n]))}static clone(t){return JSON.parse(JSON.stringify(t))}},hs={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));else{let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));else{let[r,n,i,s,o]=JSON.parse(e);return t({join_ref:r,ref:n,topic:i,event:s,payload:o})}},binaryEncode(e){let{join_ref:t,ref:r,event:n,topic:i,payload:s}=e,o=this.META_LENGTH+t.length+r.length+i.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),l=new DataView(a),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,t.length),l.setUint8(c++,r.length),l.setUint8(c++,i.length),l.setUint8(c++,n.length),Array.from(t,(d)=>l.setUint8(c++,d.charCodeAt(0))),Array.from(r,(d)=>l.setUint8(c++,d.charCodeAt(0))),Array.from(i,(d)=>l.setUint8(c++,d.charCodeAt(0))),Array.from(n,(d)=>l.setUint8(c++,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(e){let t=new DataView(e),r=t.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(e,t,n);case this.KINDS.reply:return this.decodeReply(e,t,n);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,n)}},decodePush(e,t,r){let n=t.getUint8(1),i=t.getUint8(2),s=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(e.slice(o,o+n));o=o+n;let l=r.decode(e.slice(o,o+i));o=o+i;let c=r.decode(e.slice(o,o+s));o=o+s;let u=e.slice(o,e.byteLength);return{join_ref:a,ref:null,topic:l,event:c,payload:u}},decodeReply(e,t,r){let n=t.getUint8(1),i=t.getUint8(2),s=t.getUint8(3),o=t.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(e.slice(a,a+n));a=a+n;let c=r.decode(e.slice(a,a+i));a=a+i;let u=r.decode(e.slice(a,a+s));a=a+s;let d=r.decode(e.slice(a,a+o));a=a+o;let f=e.slice(a,e.byteLength),g={status:d,response:f};return{join_ref:l,ref:c,topic:u,event:Xt.reply,payload:g}},decodeBroadcast(e,t,r){let n=t.getUint8(1),i=t.getUint8(2),s=this.HEADER_LENGTH+2,o=r.decode(e.slice(s,s+n));s=s+n;let a=r.decode(e.slice(s,s+i));s=s+i;let l=e.slice(s,e.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:l}}},Eu=class{constructor(e,t={}){if(this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||Jm,this.transport=t.transport||Lt.WebSocket||rn,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||Lt&&Lt.sessionStorage,this.establishedConnections=0,this.defaultEncoder=hs.encode.bind(hs),this.defaultDecoder=hs.decode.bind(hs),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==rn)this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder;else this.encode=this.defaultEncoder,this.decode=this.defaultDecoder;let r=null;if(nn&&nn.addEventListener)nn.addEventListener("pagehide",(n)=>{if(this.conn)this.disconnect(),r=this.connectClock}),nn.addEventListener("pageshow",(n)=>{if(r===this.connectClock)r=null,this.connect()}),nn.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden")this.pageHidden=!0;else if(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean)this.teardown(()=>this.connect())});if(this.heartbeatIntervalMs=t.heartbeatIntervalMs||30000,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=(n)=>{if(t.rejoinAfterMs)return t.rejoinAfterMs(n);else return[1000,2000,5000][n-1]||1e4},this.reconnectAfterMs=(n)=>{if(t.reconnectAfterMs)return t.reconnectAfterMs(n);else return[10,50,100,150,200,250,500,1000,2000][n-1]||5000},this.logger=t.logger||null,!this.logger&&t.debug)this.logger=(n,i,s)=>{console.log(`${n}: ${i}`,s)};this.longpollerTimeout=t.longpollerTimeout||20000,this.params=$n(t.params||{}),this.endPoint=`${e}/${$o.websocket}`,this.vsn=t.vsn||Qm,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Cu(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{if(t.beforeReconnect)await t.beforeReconnect();this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return rn}replaceTransport(e){if(this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn)this.conn.close(),this.conn=null;this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=fs.appendParams(fs.appendParams(this.endPoint,this.params()),{vsn:this.vsn});if(e.charAt(0)!=="/")return e;if(e.charAt(1)==="/")return`${this.protocol()}:${e}`;return`${this.protocol()}://${location.host}${e}`}disconnect(e,t,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,r)}connect(e){if(e)console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=$n(e);if(this.conn&&!this.disconnecting)return;if(this.longPollFallbackMs&&this.transport!==rn)this.connectWithFallback(rn,this.longPollFallbackMs);else this.transportConnect()}log(e,t,r){this.logger&&this.logger(e,t,r)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let n=this.onMessage((i)=>{if(i.ref===t)this.off([n]),e(Date.now()-r)});return!0}transportName(e){switch(e){case rn:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e=void 0;if(this.authToken)e=["phoenix",`${Xo}${btoa(this.authToken).replace(/=/g,"")}`];this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=(t)=>this.onConnError(t),this.conn.onmessage=(t)=>this.onConnMessage(t),this.conn.onclose=(t)=>this.onConnClose(t)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let r=!1,n=!0,i,s,o=this.transportName(e),a=(l)=>{this.log("transport",`falling back to ${o}...`,l),this.off([i,s]),n=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return a("memorized");if(this.fallbackTimer=setTimeout(a,t),s=this.onError((l)=>{if(this.log("transport","error",l),n&&!r)clearTimeout(this.fallbackTimer),a(l)}),this.fallbackRef)this.off([this.fallbackRef]);this.fallbackRef=this.onOpen(()=>{if(r=!0,!n){let l=this.transportName(e);if(!this.primaryPassedHealthCheck)this.storeSession(`phx:fallback:${l}`,"true");return this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,t),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(){if(this.hasLogger())this.log("transport",`connected to ${this.endPointURL()}`);if(this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat)this.resetHeartbeat();this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){if(this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger())this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Vm,"heartbeat timeout")}}resetHeartbeat(){if(this.conn&&this.conn.skipHeartbeat)return;this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}teardown(e,t,r){if(!this.conn)return e&&e();let n=this.conn;this.waitForBufferDone(n,()=>{if(t)n.close(t,r||"");else n.close();this.waitForSocketClosed(n,()=>{if(this.conn===n)this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null;e&&e()})})}waitForBufferDone(e,t,r=1){if(r===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r)}waitForSocketClosed(e,t,r=1){if(r===5||e.readyState===Ft.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,r+1)},150*r)}onConnClose(e){if(this.conn)this.conn.onclose=()=>{};if(this.hasLogger())this.log("transport","close",e);if(this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean)this.reconnectTimer.scheduleTimeout();this.triggerStateCallbacks("close",e)}onConnError(e){if(this.hasLogger())this.log("transport",e);let t=this.transport,r=this.establishedConnections;if(this.triggerStateCallbacks("error",e,t,r),t===this.transport||r>0)this.triggerChanError()}triggerChanError(){this.channels.forEach((e)=>{if(!(e.isErrored()||e.isLeaving()||e.isClosed()))e.trigger(Xt.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Ft.connecting:return"connecting";case Ft.open:return"open";case Ft.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter((t)=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([r])=>e.indexOf(r)===-1)}channel(e,t={}){let r=new $m(e,t,this);return this.channels.push(r),r}push(e){if(this.hasLogger()){let{topic:t,event:r,payload:n,ref:i,join_ref:s}=e;this.log("push",`${t} ${r} (${s}, ${i})`,n)}if(this.isConnected())this.encode(e,(t)=>this.conn.send(t));else this.sendBuffer.push(()=>this.encode(e,(t)=>this.conn.send(t)))}makeRef(){let e=this.ref+1;if(e===this.ref)this.ref=0;else this.ref=e;return this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}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(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){if(this.isConnected()&&this.sendBuffer.length>0)this.sendBuffer.forEach((e)=>e()),this.sendBuffer=[]}onConnMessage(e){this.decode(e.data,(t)=>{let{topic:r,event:n,payload:i,ref:s,join_ref:o}=t;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(l){this.log("error","error in heartbeat callback",l)}if(this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat)this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}if(this.hasLogger())this.log("receive",`${i.status||""} ${r} ${n} ${s&&"("+s+")"||""}`.trim(),i);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];if(!l.isMember(r,n,i,o))continue;l.trigger(n,i,s,o)}this.triggerStateCallbacks("message",t)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([r,n])=>{try{n(...t)}catch(i){this.log("error",`error in ${e} callback`,i)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}leaveOpenTopic(e){let t=this.channels.find((r)=>r.topic===e&&(r.isJoined()||r.isJoining()));if(t){if(this.hasLogger())this.log("transport",`leaving duplicate topic "${e}"`);t.leave()}}};class Sr{constructor(e,t){let r=qm(t);this.presence=new xu(e.getChannel(),r),this.presence.onJoin((n,i,s)=>{let o=Sr.onJoinPayload(n,i,s);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,i,s)=>{let o=Sr.onLeavePayload(n,i,s);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Sr.transformState(this.presence.state)}static transformState(e){return e=zm(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let n=e[r];return t[r]=As(n),t},{})}static onJoinPayload(e,t,r){let n=Su(t),i=As(r);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,t,r){let n=Su(t),i=As(r);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function As(e){return e.metas.map((t)=>(t.presence_ref=t.phx_ref,delete t.phx_ref,delete t.phx_ref_prev,t))}function zm(e){return JSON.parse(JSON.stringify(e))}function qm(e){return(e===null||e===void 0?void 0:e.events)&&{events:e.events}}function Su(e){return(e===null||e===void 0?void 0:e.metas)?As(e):[]}var zo;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(zo||(zo={}));class Xn{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new Sr(this.channel.channelAdapter,t)}}class gs{constructor(e,t,r){let n=ep(r);this.channel=e.getSocket().channel(t,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,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}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,t,r){let n;try{n=this.channel.push(e,t,r)}catch(i){throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>vu){let i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===Nt.joined}isJoined(){return this.state===Nt.joined}isJoining(){return this.state===Nt.joining}isClosed(){return this.state===Nt.closed}isLeaving(){return this.state===Nt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function ep(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}var qo;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(qo||(qo={}));var Ir;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(Ir||(Ir={}));var Gt;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(Gt||(Gt={}));class fr{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,t={config:{}},r){var n,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.channelAdapter=new gs(this.socket.socketAdapter,e,this.params),this.presence=new Xn(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=us(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0?void 0:i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,n,i;if(!this.socket.isConnected())this.socket.connect();if(this.channelAdapter.isClosed()){let{config:{broadcast:s,presence:o,private:a}}=this.params,l=(n=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map((f)=>f.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[Ir.PRESENCE]&&this.bindings[Ir.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,u={},d={broadcast:s,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:l,private:a};if(this.socket.accessTokenValue)u.access_token=this.socket.accessTokenValue;this._onError((f)=>{e===null||e===void 0||e(Gt.CHANNEL_ERROR,f)}),this._onClose(()=>e===null||e===void 0?void 0:e(Gt.CLOSED)),this.updateJoinPayload(Object.assign({config:d},u)),this._updateFilterMessage(),this.channelAdapter.subscribe(t).receive("ok",async({postgres_changes:f})=>{if(!this.socket._isManualToken())this.socket.setAuth();if(f===void 0){e===null||e===void 0||e(Gt.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",(f)=>{this.state=Nt.errored,e===null||e===void 0||e(Gt.CHANNEL_ERROR,Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e===null||e===void 0||e(Gt.TIMED_OUT)})}return this}_updatePostgresBindings(e,t){var r;let n=this.bindings.postgres_changes,i=(r=n===null||n===void 0?void 0:n.length)!==null&&r!==void 0?r:0,s=[];for(let o=0;o<i;o++){let a=n[o],{filter:{event:l,schema:c,table:u,filter:d}}=a,f=e&&e[o];if(f&&f.event===l&&fr.isFilterValueEqual(f.schema,c)&&fr.isFilterValueEqual(f.table,u)&&fr.isFilterValueEqual(f.filter,d))s.push(Object.assign(Object.assign({},a),{id:f.id}));else{this.unsubscribe(),this.state=Nt.errored,t===null||t===void 0||t(Gt.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}if(this.bindings.postgres_changes=s,this.state!=Nt.errored&&t)t(Gt.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){let n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===Ir.PRESENCE||e===Ir.POSTGRES_CHANGES;if(n&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,t,r)}async httpSend(e,t,r={}){var n;if(t===void 0||t===null)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};if(this.socket.accessTokenValue)i.Authorization=`Bearer ${this.socket.accessTokenValue}`;let s={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,s,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);if(o.status===202)return{success:!0};let a=o.statusText;try{let l=await o.json();a=l.error||l.message||a}catch(l){}return Promise.reject(Error(a))}async send(e,t={}){var r,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:i,payload:s}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};if(this.socket.accessTokenValue)o.Authorization=`Bearer ${this.socket.accessTokenValue}`;let a={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:s,private:this.private}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((n=l.body)===null||n===void 0?void 0:n.cancel()),l.ok?"ok":"error"}catch(l){if(l.name==="AbortError")return"timed out";else return"error"}}else return new Promise((i)=>{var s,o,a;let l=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);if(e.type==="broadcast"&&!((a=(o=(s=this.params)===null||s===void 0?void 0:s.config)===null||o===void 0?void 0:o.broadcast)===null||a===void 0?void 0:a.ack))i("ok");l.receive("ok",()=>i("ok")),l.receive("error",()=>i("error")),l.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise((t)=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>t("ok")).receive("timeout",()=>t("timed out")).receive("error",()=>t("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r),s=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(i),s}_on(e,t,r){let n=e.toLocaleLowerCase(),i=this.channelAdapter.on(e,r),s={type:n,filter:t,callback:r,ref:i};if(this.bindings[n])this.bindings[n].push(s);else this.bindings[n]=[s];return this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,t,r)=>{var n,i,s,o,a,l,c;let u=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(u,r))return!1;let d=(n=this.bindings[u])===null||n===void 0?void 0:n.find((f)=>f.ref===e.ref);if(!d)return!0;if(["broadcast","presence","postgres_changes"].includes(u))if("id"in d){let f=d.id,g=(i=d.filter)===null||i===void 0?void 0:i.event;return f&&((s=t.ids)===null||s===void 0?void 0:s.includes(f))&&(g==="*"||(g===null||g===void 0?void 0:g.toLocaleLowerCase())===((o=t.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{let f=(l=(a=d===null||d===void 0?void 0:d.filter)===null||a===void 0?void 0:a.event)===null||l===void 0?void 0:l.toLocaleLowerCase();return f==="*"||f===((c=t===null||t===void 0?void 0:t.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return d.type.toLocaleLowerCase()===u})}_notThisChannelEvent(e,t){let{close:r,error:n,leave:i,join:s}=ls;return t&&[r,n,i,s].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,t,r)=>{if(typeof t==="object"&&"ids"in t){let n=t.data,{schema:i,table:s,commit_timestamp:o,type:a,errors:l}=n;return Object.assign(Object.assign({},{schema:i,table:s,commit_timestamp:o,eventType:a,new:{},old:{},errors:l}),this._getPayloadRecords(n))}return t})}copyBindings(e){if(this.joinedOnce)throw Error("cannot copy bindings into joined channel");for(let t in e.bindings)for(let r of e.bindings[t])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(e,t){return(e!==null&&e!==void 0?e:void 0)===(t!==null&&t!==void 0?t:void 0)}_getPayloadRecords(e){let t={new:{},old:{}};if(e.type==="INSERT"||e.type==="UPDATE")t.new=Zo(e.columns,e.record);if(e.type==="UPDATE"||e.type==="DELETE")t.old=Zo(e.columns,e.old_record);return t}}class ms{constructor(e,t){this.socket=new Eu(e,t)}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,t,r,n=1e4){return new Promise((i)=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},t,r)})}push(e){this.socket.push(e)}log(e,t,r){this.socket.log(e,t,r)}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 tp={HEARTBEAT_INTERVAL:25000,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},rp=[1000,2000,5000,1e4],np=1e4,ip=`
26
26
  addEventListener("message", (e) => {
27
27
  if (e.data.event === "start") {
28
28
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
29
29
  }
30
- });`;class Zn{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(){if(this.worker)return this._workerHeartbeatTimer;return this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){if(this.worker)return this._pendingWorkerHeartbeatRef;return 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,t){var r;if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new Ji,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=(i)=>{if(i)return(...s)=>i(...s);return(...s)=>fetch(...s)},!((r=t===null||t===void 0?void 0:t.params)===null||r===void 0?void 0:r.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey;let n=this._initializeOptions(t);this.socketAdapter=new es(e,n),this.httpEndpoint=Vi(e),this.fetch=this._resolveFetch(t===null||t===void 0?void 0:t.fetch)}connect(){if(this.isConnecting()||this.isDisconnecting()||this.isConnected())return;if(this.accessToken&&!this._authPromise)this._setAuthSafely("connect");this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let t=e.message;if(t.includes("Node.js"))throw Error(`${t}
30
+ });`;class zn{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(){if(this.worker)return this._workerHeartbeatTimer;return this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){if(this.worker)return this._pendingWorkerHeartbeatRef;return 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,t){var r;if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new cs,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=(i)=>{if(i)return(...s)=>i(...s);return(...s)=>fetch(...s)},!((r=t===null||t===void 0?void 0:t.params)===null||r===void 0?void 0:r.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey;let n=this._initializeOptions(t);this.socketAdapter=new ms(e,n),this.httpEndpoint=us(e),this.fetch=this._resolveFetch(t===null||t===void 0?void 0:t.fetch)}connect(){if(this.isConnecting()||this.isDisconnecting()||this.isConnected())return;if(this.accessToken&&!this._authPromise)this._setAuthSafely("connect");this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let t=e.message;if(t.includes("Node.js"))throw Error(`${t}
31
31
 
32
32
  To use Realtime in Node.js, you need to provide a WebSocket implementation:
33
33
 
@@ -40,25 +40,25 @@ Option 2: Install and provide the "ws" package:
40
40
  const client = new RealtimeClient(url, {
41
41
  ...options,
42
42
  transport: ws
43
- })`);throw Error(`WebSocket not available: ${t}`)}this._handleNodeJsRaceCondition()}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){if(this.isDisconnecting())return"ok";return await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();if(t==="ok")e.teardown();if(this.channels.length===0)this.disconnect();return t}async removeAllChannels(){let e=this.channels.map(async(r)=>{let n=await r.unsubscribe();return r.teardown(),n}),t=await Promise.all(e);return this.disconnect(),t}log(e,t,r){this.socketAdapter.log(e,t,r)}connectionState(){return this.socketAdapter.connectionState()||Jn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){let r=`realtime:${e}`,n=this.getChannels().find((i)=>i.topic===r);if(!n){let i=new lr(`realtime:${e}`,t,this);return this.channels.push(i),i}else return n}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((t)=>t.topic!==e.topic)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),t=this.accessTokenValue}else t=this.accessTokenValue;if(r)this._manuallySetToken=!0;else if(this.accessToken)this._manuallySetToken=!1;if(this.accessTokenValue!=t)this.accessTokenValue=t,this.channels.forEach((n)=>{let i={access_token:t,version:iu};if(t&&n.updateJoinPayload(i),n.joinedOnce&&n.channelAdapter.isJoined())n.channelAdapter.push(Qi.access_token,{access_token:t})})}async _waitForAuthIfNeeded(){if(this._authPromise)await this._authPromise}_setAuthSafely(e="general"){if(!this._isManualToken())this.setAuth().catch((t)=>{this.log("error",`Error setting auth in ${e}`,t)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{if((this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch((t)=>{this.log("error","error waiting for auth on connect",t)}),this.worker&&!this.workerRef)this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{if(this.worker&&this.workerRef)this._terminateWorker()}),this.socketAdapter.onMessage((e)=>{if(e.ref&&e.ref===this._pendingWorkerHeartbeatRef)this._pendingWorkerHeartbeatRef=null})}_handleNodeJsRaceCondition(){if(this.socketAdapter.isConnected())this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,r)=>{if(t=="sent")this._setAuthSafely();if(e)e(t,r)}}_startWorkerHeartbeat(){if(this.workerUrl)this.log("worker",`starting worker for from ${this.workerUrl}`);else this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=(t)=>{this.log("worker","worker error",t.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=(t)=>{if(t.data.event==="keepAlive")this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){if(this.workerRef)this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0}_workerObjectUrl(e){let t;if(e)t=e;else{let r=new Blob([km],{type:"application/javascript"});t=URL.createObjectURL(r)}return t}_initializeOptions(e){var t,r,n,i,s,o,a,l,c;this.worker=(t=e===null||e===void 0?void 0:e.worker)!==null&&t!==void 0?t:!1,this.accessToken=(r=e===null||e===void 0?void 0:e.accessToken)!==null&&r!==void 0?r:null;let u={};u.timeout=(n=e===null||e===void 0?void 0:e.timeout)!==null&&n!==void 0?n:au,u.heartbeatIntervalMs=(i=e===null||e===void 0?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:Em.HEARTBEAT_INTERVAL,u.transport=(s=e===null||e===void 0?void 0:e.transport)!==null&&s!==void 0?s:Bo.getWebSocketConstructor(),u.params=e===null||e===void 0?void 0:e.params,u.logger=e===null||e===void 0?void 0:e.logger,u.heartbeatCallback=this._wrapHeartbeatCallback(e===null||e===void 0?void 0:e.heartbeatCallback),u.reconnectAfterMs=(o=e===null||e===void 0?void 0:e.reconnectAfterMs)!==null&&o!==void 0?o:(g)=>Sm[g-1]||Im;let d,A,f=(a=e===null||e===void 0?void 0:e.vsn)!==null&&a!==void 0?a:ou;switch(f){case su:d=(g,m)=>m(JSON.stringify(g)),A=(g,m)=>m(JSON.parse(g));break;case Oo:d=this.serializer.encode.bind(this.serializer),A=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${u.vsn}`)}if(u.vsn=f,u.encode=(l=e===null||e===void 0?void 0:e.encode)!==null&&l!==void 0?l:d,u.decode=(c=e===null||e===void 0?void 0:e.decode)!==null&&c!==void 0?c:A,u.beforeReconnect=this._reconnectAuth.bind(this),(e===null||e===void 0?void 0:e.logLevel)||(e===null||e===void 0?void 0:e.log_level))this.logLevel=e.logLevel||e.log_level,u.params=Object.assign(Object.assign({},u.params),{log_level:this.logLevel});if(this.worker){if(typeof window<"u"&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=e===null||e===void 0?void 0:e.workerUrl,u.autoSendHeartbeat=!this.worker}return u}async _reconnectAuth(){if(await this._waitForAuthIfNeeded(),!this.isConnected())this.connect()}}var Xn=class extends Error{constructor(e,t){super(e);this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&t.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Rm(e,t,r){let n=new URL(t,e);if(r){for(let[i,s]of Object.entries(r))if(s!==void 0)n.searchParams.set(i,s)}return n.toString()}async function Tm(e){if(!e||e.type==="none")return{};if(e.type==="bearer")return{Authorization:`Bearer ${e.token}`};if(e.type==="header")return{[e.name]:e.value};if(e.type==="custom")return await e.getHeaders();return{}}function Bm(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:i,body:s,headers:o}){let a=Rm(e.baseUrl,n,i),l=await Tm(e.auth),c=await t(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...o},body:s?JSON.stringify(s):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),A=d&&u?JSON.parse(u):u;if(!c.ok){let f=d?A:void 0,g=f?.error;throw new Xn(g?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:g?.type,icebergCode:g?.code,details:f})}return{status:c.status,headers:c.headers,data:A}}}}function ts(e){return e.join("\x1F")}var Om=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:ts(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map((n)=>({namespace:n}))}async createNamespace(e,t){let r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ts(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ts(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ts(e.namespace)}`}),!0}catch(t){if(t instanceof Xn&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(r){if(r instanceof Xn&&r.status===409)return;throw r}}};function tn(e){return e.join("\x1F")}var Pm=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${tn(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let r={};if(this.accessDelegation)r["X-Iceberg-Access-Delegation"]=this.accessDelegation;return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${tn(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${tn(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${tn(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};if(this.accessDelegation)t["X-Iceberg-Access-Delegation"]=this.accessDelegation;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${tn(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};if(this.accessDelegation)t["X-Iceberg-Access-Delegation"]=this.accessDelegation;try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${tn(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(r){if(r instanceof Xn&&r.status===404)return!1;throw r}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof Xn&&r.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},fu=class{constructor(e){let t="v1";if(e.catalogName)t+=`/${e.catalogName}`;let r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Bm({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new Om(this.client,t),this.tableOps=new Pm(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};var ns=class extends Error{constructor(e,t="storage",r,n){super(e);this.__isStorageError=!0,this.namespace=t,this.name=t==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}};function is(e){return typeof e==="object"&&e!==null&&"__isStorageError"in e}var rs=class extends ns{constructor(e,t,r,n="storage"){super(e,n,t,r);this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},bu=class extends ns{constructor(e,t,r="storage"){super(e,r);this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};var Dm=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)},Nm=(e)=>{if(typeof e!=="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Go=(e)=>{if(Array.isArray(e))return e.map((r)=>Go(r));else if(typeof e==="function"||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([r,n])=>{let i=r.replace(/([-_][a-z])/gi,(s)=>s.toUpperCase().replace(/[-_]/g,""));t[i]=Go(n)}),t},Mm=(e)=>{if(!e||typeof e!=="string")return!1;if(e.length===0||e.length>100)return!1;if(e.trim()!==e)return!1;if(e.includes("/")||e.includes("\\"))return!1;return/^[\w!.\*'() &$@=;:+,?-]+$/.test(e)};function qn(e){return qn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qn(e)}function Lm(e,t){if(qn(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(qn(n)!="object")return n;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Fm(e){var t=Lm(e,"string");return qn(t)=="symbol"?t:t+""}function Gm(e,t,r){return(t=Fm(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function gu(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function J(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?gu(Object(r),!0).forEach(function(n){Gm(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):gu(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var mu=(e)=>{var t;return e.msg||e.message||e.error_description||(typeof e.error==="string"?e.error:(t=e.error)===null||t===void 0?void 0:t.message)||JSON.stringify(e)},Um=async(e,t,r,n)=>{if(e!==null&&typeof e==="object"&&typeof e.json==="function"){let i=e,s=parseInt(i.status,10);if(!Number.isFinite(s))s=500;i.json().then((o)=>{let a=(o===null||o===void 0?void 0:o.statusCode)||(o===null||o===void 0?void 0:o.code)||s+"";t(new rs(mu(o),s,a,n))}).catch(()=>{let o=s+"";t(new rs(i.statusText||`HTTP ${s} error`,s,o,n))})}else t(new bu(mu(e),e,n))},Hm=(e,t,r,n)=>{let i={method:e,headers:(t===null||t===void 0?void 0:t.headers)||{}};if(e==="GET"||e==="HEAD"||!n)return J(J({},i),r);if(Nm(n)){var s;let o=(t===null||t===void 0?void 0:t.headers)||{},a;for(let[l,c]of Object.entries(o))if(l.toLowerCase()==="content-type")a=c;i.headers=jm(o,"Content-Type",(s=a)!==null&&s!==void 0?s:"application/json"),i.body=JSON.stringify(n)}else i.body=n;if(t===null||t===void 0?void 0:t.duplex)i.duplex=t.duplex;return J(J({},i),r)};function jm(e,t,r){let n=J({},e);for(let i of Object.keys(n))if(i.toLowerCase()===t.toLowerCase())delete n[i];return n[t]=r,n}async function zn(e,t,r,n,i,s,o){return new Promise((a,l)=>{e(r,Hm(t,n,i,s)).then((c)=>{if(!c.ok)throw c;if(n===null||n===void 0?void 0:n.noResolveJson)return c;if(o==="vectors"){let u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!u||!u.includes("application/json"))return{}}return c.json()}).then((c)=>a(c)).catch((c)=>Um(c,l,n,o))})}function yu(e="storage"){return{get:async(t,r,n,i)=>zn(t,"GET",r,n,i,void 0,e),post:async(t,r,n,i,s)=>zn(t,"POST",r,i,s,n,e),put:async(t,r,n,i,s)=>zn(t,"PUT",r,i,s,n,e),head:async(t,r,n,i)=>zn(t,"HEAD",r,J(J({},n),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,r,n,i,s)=>zn(t,"DELETE",r,i,s,n,e)}}var Km=yu("storage"),{get:ei,post:Et,put:Uo,head:Wm,remove:Ho}=Km,ft=yu("vectors"),rn=class{constructor(e,t={},r,n="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=Object.fromEntries(Object.entries(t).map(([i,s])=>[i.toLowerCase(),s])),this.fetch=Dm(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=J(J({},this.headers),{},{[e.toLowerCase()]:t}),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(is(r))return{data:null,error:r};throw r}}},Ym=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(is(t))return{data:null,error:t};throw t}}},wu;wu=Symbol.toStringTag;var Qm=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[wu]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ym(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){if(!this.promise)this.promise=this.execute();return this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(is(t))return{data:null,error:t};throw t}}},Jm={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},pu={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Vm=class extends rn{constructor(e,t={},r,n){super(e,t,n,"storage");this.bucketId=r}async uploadOrUpdate(e,t,r,n){var i=this;return i.handleOperation(async()=>{let s,o=J(J({},pu),n),a=J(J({},i.headers),e==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;if(typeof Blob<"u"&&r instanceof Blob){if(s=new FormData,s.append("cacheControl",o.cacheControl),l)s.append("metadata",i.encodeMetadata(l));s.append("",r)}else if(typeof FormData<"u"&&r instanceof FormData){if(s=r,!s.has("cacheControl"))s.append("cacheControl",o.cacheControl);if(l&&!s.has("metadata"))s.append("metadata",i.encodeMetadata(l))}else{if(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l)a["x-metadata"]=i.toBase64(i.encodeMetadata(l));if((typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s==="object"&&("pipe"in s)&&typeof s.pipe==="function")&&!o.duplex)o.duplex="half"}if(n===null||n===void 0?void 0:n.headers)a=J(J({},a),n.headers);let c=i._removeEmptyFolders(t),u=i._getFinalPath(c),d=await(e=="PUT"?Uo:Et)(i.fetch,`${i.url}/object/${u}`,s,J({headers:a},(o===null||o===void 0?void 0:o.duplex)?{duplex:o.duplex}:{}));return{path:c,id:d.Id,fullPath:d.Key}})}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,n){var i=this;let s=i._removeEmptyFolders(e),o=i._getFinalPath(s),a=new URL(i.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",t),i.handleOperation(async()=>{let l,c=J(J({},pu),n),u=J(J({},i.headers),{"x-upsert":String(c.upsert)});if(typeof Blob<"u"&&r instanceof Blob)l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r);else if(typeof FormData<"u"&&r instanceof FormData)l=r,l.append("cacheControl",c.cacheControl);else l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType;return{path:s,fullPath:(await Uo(i.fetch,a.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(e),i=J({},r.headers);if(t===null||t===void 0?void 0:t.upsert)i["x-upsert"]="true";let s=await Et(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 ns("No token returned by API");return{signedUrl:o.toString(),path:e,token:a}})}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var n=this;return n.handleOperation(async()=>await Et(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r===null||r===void 0?void 0:r.destinationBucket},{headers:n.headers}))}async copy(e,t,r){var n=this;return n.handleOperation(async()=>({path:(await Et(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r===null||r===void 0?void 0:r.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(e,t,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(e),s=typeof(r===null||r===void 0?void 0:r.transform)==="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await Et(n.fetch,`${n.url}/object/sign/${i}`,J({expiresIn:t},s?{transform:r.transform}:{}),{headers:n.headers}),a=new URLSearchParams;if(r===null||r===void 0?void 0:r.download)a.set("download",r.download===!0?"":r.download);if((r===null||r===void 0?void 0:r.cacheNonce)!=null)a.set("cacheNonce",String(r.cacheNonce));let l=a.toString(),c=s&&o.signedURL.includes("/object/sign/")?o.signedURL.replace("/object/sign/","/render/image/sign/"):o.signedURL;return{signedUrl:encodeURI(`${n.url}${c}${l?`&${l}`:""}`)}})}async createSignedUrls(e,t,r){var n=this;return n.handleOperation(async()=>{let i=await Et(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:t,paths:e},{headers:n.headers}),s=new URLSearchParams;if(r===null||r===void 0?void 0:r.download)s.set("download",r.download===!0?"":r.download);if((r===null||r===void 0?void 0:r.cacheNonce)!=null)s.set("cacheNonce",String(r.cacheNonce));let o=s.toString();return i.map((a)=>J(J({},a),{},{signedUrl:a.signedURL?encodeURI(`${n.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(e,t,r){let n=typeof(t===null||t===void 0?void 0:t.transform)<"u"?"render/image/authenticated":"object",i=new URLSearchParams;if(t===null||t===void 0?void 0:t.transform)this.applyTransformOptsToQuery(i,t.transform);if((t===null||t===void 0?void 0:t.cacheNonce)!=null)i.set("cacheNonce",String(t.cacheNonce));let s=i.toString(),o=this._getFinalPath(e);return new Qm(()=>ei(this.fetch,`${this.url}/${n}/${o}${s?`?${s}`:""}`,{headers:this.headers,noResolveJson:!0},r),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation(async()=>Go(await ei(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})))}async exists(e){var t=this;let r=t._getFinalPath(e);try{return await Wm(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(i){if(t.shouldThrowOnError)throw i;if(is(i)){var n;let s=i instanceof rs?i.status:i instanceof bu?(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(e,t){let r=this._getFinalPath(e),n=new URLSearchParams;if(t===null||t===void 0?void 0:t.download)n.set("download",t.download===!0?"":t.download);if(t===null||t===void 0?void 0:t.transform)this.applyTransformOptsToQuery(n,t.transform);if((t===null||t===void 0?void 0:t.cacheNonce)!=null)n.set("cacheNonce",String(t.cacheNonce));let i=n.toString(),s=typeof(t===null||t===void 0?void 0:t.transform)<"u"?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}`)+(i?`?${i}`:"")}}}async remove(e){var t=this;return t.handleOperation(async()=>await Ho(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,r){var n=this;return n.handleOperation(async()=>{let i=J(J(J({},Jm),t),{},{prefix:e||""});return await Et(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{let n=J({},e);return await Et(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");return btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(e,t){if(t.width)e.set("width",t.width.toString());if(t.height)e.set("height",t.height.toString());if(t.resize)e.set("resize",t.resize);if(t.format)e.set("format",t.format);if(t.quality)e.set("quality",t.quality.toString());return e}},$m="2.103.0",ti={"X-Client-Info":`storage-js/${$m}`},Zm=class extends rn{constructor(e,t={},r,n){let i=new URL(e);if(n===null||n===void 0?void 0:n.useNewHostname){if(/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=J(J({},ti),t);super(s,o,r,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await ei(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await ei(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation(async()=>await Et(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async updateBucket(e,t){var r=this;return r.handleOperation(async()=>await Uo(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await Et(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await Ho(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};if(e){if("limit"in e)t.limit=String(e.limit);if("offset"in e)t.offset=String(e.offset);if(e.search)t.search=e.search;if(e.sortColumn)t.sortColumn=e.sortColumn;if(e.sortOrder)t.sortOrder=e.sortOrder}return Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},Xm=class extends rn{constructor(e,t={},r){let n=e.replace(/\/$/,""),i=J(J({},ti),t);super(n,i,r,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await Et(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=new URLSearchParams;if((e===null||e===void 0?void 0:e.limit)!==void 0)r.set("limit",e.limit.toString());if((e===null||e===void 0?void 0:e.offset)!==void 0)r.set("offset",e.offset.toString());if(e===null||e===void 0?void 0:e.sortColumn)r.set("sortColumn",e.sortColumn);if(e===null||e===void 0?void 0:e.sortOrder)r.set("sortOrder",e.sortOrder);if(e===null||e===void 0?void 0:e.search)r.set("search",e.search);let n=r.toString(),i=n?`${t.url}/bucket?${n}`:`${t.url}/bucket`;return await ei(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await Ho(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!Mm(e))throw new ns("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 fu({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,s){let o=i[s];if(typeof o!=="function")return o;return async(...a)=>{try{return{data:await o.apply(i,a),error:null}}catch(l){if(n)throw l;return{data:null,error:l}}}}})}},zm=class extends rn{constructor(e,t={},r){let n=e.replace(/\/$/,""),i=J(J({},ti),{},{"Content-Type":"application/json"},t);super(n,i,r,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await ft.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await ft.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}},qm=class extends rn{constructor(e,t={},r){let n=e.replace(/\/$/,""),i=J(J({},ti),{},{"Content-Type":"application/json"},t);super(n,i,r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0){if(e.segmentIndex<0||e.segmentIndex>=e.segmentCount)throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}}return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},ep=class extends rn{constructor(e,t={},r){let n=e.replace(/\/$/,""),i=J(J({},ti),{},{"Content-Type":"application/json"},t);super(n,i,r,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ft.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},tp=class extends ep{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new rp(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,r=this;return t().call(r,e)}async getBucket(e){var t=()=>super.getBucket,r=this;return t().call(r,e)}async listBuckets(e={}){var t=()=>super.listBuckets,r=this;return t().call(r,e)}async deleteBucket(e){var t=()=>super.deleteBucket,r=this;return t().call(r,e)}},rp=class extends zm{constructor(e,t,r,n){super(e,t,n);this.vectorBucketName=r}async createIndex(e){var t=()=>super.createIndex,r=this;return t().call(r,J(J({},e),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,r=this;return t().call(r,J(J({},e),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,r=this;return t().call(r,r.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,r=this;return t().call(r,r.vectorBucketName,e)}index(e){return new np(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},np=class extends qm{constructor(e,t,r,n,i){super(e,t,i);this.vectorBucketName=r,this.indexName=n}async putVectors(e){var t=()=>super.putVectors,r=this;return t().call(r,J(J({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(e){var t=()=>super.getVectors,r=this;return t().call(r,J(J({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,r=this;return t().call(r,J(J({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,r=this;return t().call(r,J(J({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,r=this;return t().call(r,J(J({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},vu=class extends Zm{constructor(e,t={},r,n){super(e,t,r,n)}from(e){return new Vm(this.url,this.headers,e,this.fetch)}get vectors(){return new tp(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Xm(this.url+"/iceberg",this.headers,this.fetch)}};var ss="2.103.0";var Er=30000,os=3,as=os*Er,_u="http://localhost:9999",Cu="supabase.auth.token";var xu={"X-Client-Info":`gotrue-js/${ss}`};var ri="X-Supabase-Api-Version",jo={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Eu=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Su=600000;class Sr extends Error{constructor(e,t,r){super(e);this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function F(e){return typeof e==="object"&&e!==null&&"__isAuthError"in e}class Ko extends Sr{constructor(e,t,r){super(e,t,r);this.name="AuthApiError",this.status=t,this.code=r}}function Iu(e){return F(e)&&e.name==="AuthApiError"}class St extends Sr{constructor(e,t){super(e);this.name="AuthUnknownError",this.originalError=t}}class Nt extends Sr{constructor(e,t,r,n){super(e,r,n);this.name=t,this.status=r}}class nt extends Nt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function ni(e){return F(e)&&e.name==="AuthSessionMissingError"}class cr extends Nt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class nn extends Nt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class sn extends Nt{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0);this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function ku(e){return F(e)&&e.name==="AuthImplicitGrantRedirectError"}class ls extends Nt{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0);this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Wo 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")}}class ii extends Nt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function cs(e){return F(e)&&e.name==="AuthRetryableFetchError"}class us extends Nt{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password");this.reasons=r}}class on extends Nt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}var ds="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ru=`
44
- \r=`.split(""),ip=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Ru.length;t+=1)e[Ru[t].charCodeAt(0)]=-2;for(let t=0;t<ds.length;t+=1)e[ds[t].charCodeAt(0)]=t;return e})();function Tu(e,t,r){if(e!==null){t.queue=t.queue<<8|e,t.queuedBits+=8;while(t.queuedBits>=6){let n=t.queue>>t.queuedBits-6&63;r(ds[n]),t.queuedBits-=6}}else if(t.queuedBits>0){t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;while(t.queuedBits>=6){let n=t.queue>>t.queuedBits-6&63;r(ds[n]),t.queuedBits-=6}}}function Bu(e,t,r){let n=ip[e];if(n>-1){t.queue=t.queue<<6|n,t.queuedBits+=6;while(t.queuedBits>=8)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}else if(n===-2)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function Yo(e){let t=[],r=(o)=>{t.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=(o)=>{ap(o,n,r)};for(let o=0;o<e.length;o+=1)Bu(e.charCodeAt(o),i,s);return t.join("")}function sp(e,t){if(e<=127){t(e);return}else if(e<=2047){t(192|e>>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function op(e,t){for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>55295&&n<=56319){let i=(n-55296)*1024&65535;n=(e.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}sp(n,t)}}function ap(e,t,r){if(t.utf8seq===0){if(e<=127){r(e);return}for(let n=1;n<6;n+=1)if((e>>7-n&1)===0){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");if(t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0)r(t.codepoint)}}function ur(e){let t=[],r={queue:0,queuedBits:0},n=(i)=>{t.push(i)};for(let i=0;i<e.length;i+=1)Bu(e.charCodeAt(i),r,n);return new Uint8Array(t)}function Ou(e){let t=[];return op(e,(r)=>t.push(r)),new Uint8Array(t)}function zt(e){let t=[],r={queue:0,queuedBits:0},n=(i)=>{t.push(i)};return e.forEach((i)=>Tu(i,r,n)),Tu(null,r,n),t.join("")}function Pu(e){return Math.round(Date.now()/1000)+e}function Du(){return Symbol("auth-callback")}var Ke=()=>typeof window<"u"&&typeof document<"u",Ir={tested:!1,writable:!1},hs=()=>{if(!Ke())return!1;try{if(typeof globalThis.localStorage!=="object")return!1}catch(t){return!1}if(Ir.tested)return Ir.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Ir.tested=!0,Ir.writable=!0}catch(t){Ir.tested=!0,Ir.writable=!1}return Ir.writable};function Nu(e){let t={},r=new URL(e);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,s)=>{t[s]=i})}catch(n){}return r.searchParams.forEach((n,i)=>{t[i]=n}),t}var As=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)},Mu=(e)=>typeof e==="object"&&e!==null&&("status"in e)&&("ok"in e)&&("json"in e)&&typeof e.json==="function",kr=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},dr=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(n){return r}},$e=async(e,t)=>{await e.removeItem(t)};class si{constructor(){this.promise=new si.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}si.promiseConstructor=Promise;function oi(e){let t=e.split(".");if(t.length!==3)throw new on("Invalid JWT structure");for(let n=0;n<t.length;n++)if(!Eu.test(t[n]))throw new on("JWT not in base64url format");return{header:JSON.parse(Yo(t[0])),payload:JSON.parse(Yo(t[1])),signature:ur(t[2]),raw:{header:t[0],payload:t[1]}}}async function Lu(e){return await new Promise((t)=>{setTimeout(()=>t(null),e)})}function Fu(e,t){return new Promise((n,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{let o=await e(s);if(!t(s,null,o)){n(o);return}}catch(o){if(!t(s,o)){i(o);return}}})()})}function lp(e){return("0"+e.toString(16)).substr(-2)}function cp(){let t=new Uint32Array(56);if(typeof crypto>"u"){let i="";for(let s=0;s<56;s++)i+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~".charAt(Math.floor(Math.random()*66));return i}return crypto.getRandomValues(t),Array.from(t,lp).join("")}async function up(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map((s)=>String.fromCharCode(s)).join("")}async function dp(e){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."),e;let r=await up(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Rr(e,t,r=!1){let n=cp(),i=n;if(r)i+="/PASSWORD_RECOVERY";await kr(e,`${t}-code-verifier`,i);let s=await dp(n);return[s,n===s?"plain":"s256"]}var hp=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Gu(e){let t=e.headers.get(ri);if(!t)return null;if(!t.match(hp))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(r){return null}}function Uu(e){if(!e)throw Error("Missing exp claim");let t=Math.floor(Date.now()/1000);if(e<=t)throw Error("JWT has expired")}function Hu(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}var Ap=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Tr(e){if(!Ap.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function fs(){return new Proxy({},{get:(t,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 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:(t,r)=>{throw 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:(t,r)=>{throw 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 ju(e,t){return new Proxy(e,{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)}if(!t.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."),t.value=!0;return Reflect.get(r,n,i)}})}function Qo(e){return JSON.parse(JSON.stringify(e))}var Br=(e)=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),fp=[502,503,504];async function Ku(e){var t;if(!Mu(e))throw new ii(Br(e),0);if(fp.includes(e.status))throw new ii(Br(e),e.status);let r;try{r=await e.json()}catch(s){throw new St(Br(s),s)}let n=void 0,i=Gu(e);if(i&&i.getTime()>=jo["2024-01-01"].timestamp&&typeof r==="object"&&r&&typeof r.code==="string")n=r.code;else if(typeof r==="object"&&r&&typeof r.error_code==="string")n=r.error_code;if(!n){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 us(Br(r),e.status,r.weak_password.reasons)}else if(n==="weak_password")throw new us(Br(r),e.status,((t=r.weak_password)===null||t===void 0?void 0:t.reasons)||[]);else if(n==="session_not_found")throw new nt;throw new Ko(Br(r),e.status||500,n)}var gp=(e,t,r,n)=>{let i={method:e,headers:(t===null||t===void 0?void 0:t.headers)||{}};if(e==="GET")return i;return i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t===null||t===void 0?void 0:t.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r)};async function W(e,t,r,n){var i;let s=Object.assign({},n===null||n===void 0?void 0:n.headers);if(!s[ri])s[ri]=jo["2024-01-01"].name;if(n===null||n===void 0?void 0:n.jwt)s.Authorization=`Bearer ${n.jwt}`;let o=(i=n===null||n===void 0?void 0:n.query)!==null&&i!==void 0?i:{};if(n===null||n===void 0?void 0:n.redirectTo)o.redirect_to=n.redirectTo;let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await mp(e,t,r+a,{headers:s,noResolveJson:n===null||n===void 0?void 0:n.noResolveJson},{},n===null||n===void 0?void 0:n.body);return(n===null||n===void 0?void 0:n.xform)?n===null||n===void 0?void 0:n.xform(l):{data:Object.assign({},l),error:null}}async function mp(e,t,r,n,i,s){let o=gp(t,n,i,s),a;try{a=await e(r,Object.assign({},o))}catch(l){throw console.error(l),new ii(Br(l),0)}if(!a.ok)await Ku(a);if(n===null||n===void 0?void 0:n.noResolveJson)return a;try{return await a.json()}catch(l){await Ku(l)}}function _t(e){var t;let r=null;if(pp(e)){if(r=Object.assign({},e),!e.expires_at)r.expires_at=Pu(e.expires_in)}let n=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:r,user:n},error:null}}function Jo(e){let t=_t(e);if(!t.error&&e.weak_password&&typeof e.weak_password==="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message==="string"&&e.weak_password.reasons.reduce((r,n)=>r&&typeof n==="string",!0))t.data.weak_password=e.weak_password;return t}function Mt(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function Wu(e){return{data:e,error:null}}function Yu(e){let{action_link:t,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s}=e,o=_r(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:t,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Vo(e){return e}function pp(e){return e.access_token&&e.refresh_token&&e.expires_in}var gs=["global","local","others"];class an{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=As(r),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,t=gs[0]){if(gs.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${gs.join(", ")}`);try{return await W(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(F(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await W(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Mt})}catch(r){if(F(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=_r(e,["options"]),n=Object.assign(Object.assign({},r),t);if("newEmail"in r)n.new_email=r===null||r===void 0?void 0:r.newEmail,delete n.newEmail;return await W(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Yu,redirectTo:t===null||t===void 0?void 0:t.redirectTo})}catch(t){if(F(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await W(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Mt})}catch(t){if(F(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,n,i,s,o,a;try{let l={nextPage:null,lastPage:0,total:0},c=await W(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e===null||e===void 0?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(n=e===null||e===void 0?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Vo});if(c.error)throw c.error;let u=await c.json(),d=(s=c.headers.get("x-total-count"))!==null&&s!==void 0?s:0,A=(a=(o=c.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&a!==void 0?a:[];if(A.length>0)A.forEach((f)=>{let g=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(f.split(";")[1].split("=")[1]);l[`${m}Page`]=g}),l.total=parseInt(d);return{data:Object.assign(Object.assign({},u),l),error:null}}catch(l){if(F(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){Tr(e);try{return await W(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Mt})}catch(t){if(F(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Tr(e);try{return await W(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Mt})}catch(r){if(F(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){Tr(e);try{return await W(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Mt})}catch(r){if(F(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){Tr(e.userId);try{let{data:t,error:r}=await W(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:(n)=>({data:{factors:n},error:null})});return{data:t,error:r}}catch(t){if(F(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Tr(e.userId),Tr(e.id);try{return{data:await W(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(F(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,n,i,s,o,a;try{let l={nextPage:null,lastPage:0,total:0},c=await W(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e===null||e===void 0?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(n=e===null||e===void 0?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Vo});if(c.error)throw c.error;let u=await c.json(),d=(s=c.headers.get("x-total-count"))!==null&&s!==void 0?s:0,A=(a=(o=c.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&a!==void 0?a:[];if(A.length>0)A.forEach((f)=>{let g=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(f.split(";")[1].split("=")[1]);l[`${m}Page`]=g}),l.total=parseInt(d);return{data:Object.assign(Object.assign({},u),l),error:null}}catch(l){if(F(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await W(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(F(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await W(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(F(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await W(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:(r)=>({data:r,error:null})})}catch(r){if(F(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await W(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(F(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await W(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(F(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{let t={};if(e===null||e===void 0?void 0:e.type)t.type=e.type;return await W(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:(r)=>{var n;return{data:{providers:(n=r===null||r===void 0?void 0:r.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(t){if(F(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await W(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(F(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await W(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(F(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await W(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:(r)=>({data:r,error:null})})}catch(r){if(F(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await W(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(F(t))return{data:null,error:t};throw t}}}function $o(e={}){return{getItem:(t)=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:(t)=>{delete e[t]}}}var It={debug:!!(globalThis&&hs()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ps extends Error{constructor(e){super(e);this.isAcquireTimeout=!0}}class ms extends ps{}async function Zo(e,t,r){if(It.debug)console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let n=new globalThis.AbortController,i;if(t>0)i=setTimeout(()=>{if(n.abort(),It.debug)console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t);await Promise.resolve();try{return await globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async(s)=>{if(s){if(clearTimeout(i),It.debug)console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{if(It.debug)console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}else if(t===0){if(It.debug)console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e);throw new ms(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`)}else{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(t>0)clearTimeout(i);if((s===null||s===void 0?void 0:s.name)==="AbortError"&&t>0)if(n.signal.aborted){if(It.debug)console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",e);return console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${t}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(e,{mode:"exclusive",steal:!0},async(o)=>{if(o){if(It.debug)console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,o.name);try{return await r()}finally{if(It.debug)console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,o.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}))}else{if(It.debug)console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",e);throw new ms(`Lock "${e}" was released because another request stole it`)}throw s}}function Qu(){if(typeof globalThis==="object")return;try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){if(typeof self<"u")self.globalThis=self}}function Xo(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function Ju(e){return parseInt(e,16)}function Vu(e){let t=new TextEncoder().encode(e);return"0x"+Array.from(t,(n)=>n.toString(16).padStart(2,"0")).join("")}function $u(e){var t;let{chainId:r,domain:n,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:A}=e;{if(!Number.isInteger(r))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(A!=="1")throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${A}`);if((t=e.statement)===null||t===void 0?void 0:t.includes(`
45
- `))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}let f=Xo(e.address),g=u?`${u}://${n}`:n,m=e.statement?`${e.statement}
46
- `:"",p=`${g} wants you to sign in with your Ethereum account:
47
- ${f}
43
+ })`);throw Error(`WebSocket not available: ${t}`)}this._handleNodeJsRaceCondition()}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){if(this.isDisconnecting())return"ok";return await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();if(t==="ok")e.teardown();if(this.channels.length===0)this.disconnect();return t}async removeAllChannels(){let e=this.channels.map(async(r)=>{let n=await r.unsubscribe();return r.teardown(),n}),t=await Promise.all(e);return this.disconnect(),t}log(e,t,r){this.socketAdapter.log(e,t,r)}connectionState(){return this.socketAdapter.connectionState()||Zn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){let r=`realtime:${e}`,n=this.getChannels().find((i)=>i.topic===r);if(!n){let i=new fr(`realtime:${e}`,t,this);return this.channels.push(i),i}else return n}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((t)=>t.topic!==e.topic)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),t=this.accessTokenValue}else t=this.accessTokenValue;if(r)this._manuallySetToken=!0;else if(this.accessToken)this._manuallySetToken=!1;if(this.accessTokenValue!=t)this.accessTokenValue=t,this.channels.forEach((n)=>{let i={access_token:t,version:pu};if(t&&n.updateJoinPayload(i),n.joinedOnce&&n.channelAdapter.isJoined())n.channelAdapter.push(ls.access_token,{access_token:t})})}async _waitForAuthIfNeeded(){if(this._authPromise)await this._authPromise}_setAuthSafely(e="general"){if(!this._isManualToken())this.setAuth().catch((t)=>{this.log("error",`Error setting auth in ${e}`,t)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{if((this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch((t)=>{this.log("error","error waiting for auth on connect",t)}),this.worker&&!this.workerRef)this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{if(this.worker&&this.workerRef)this._terminateWorker()}),this.socketAdapter.onMessage((e)=>{if(e.ref&&e.ref===this._pendingWorkerHeartbeatRef)this._pendingWorkerHeartbeatRef=null})}_handleNodeJsRaceCondition(){if(this.socketAdapter.isConnected())this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,r)=>{if(t=="sent")this._setAuthSafely();if(e)e(t,r)}}_startWorkerHeartbeat(){if(this.workerUrl)this.log("worker",`starting worker for from ${this.workerUrl}`);else this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=(t)=>{this.log("worker","worker error",t.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=(t)=>{if(t.data.event==="keepAlive")this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){if(this.workerRef)this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0}_workerObjectUrl(e){let t;if(e)t=e;else{let r=new Blob([ip],{type:"application/javascript"});t=URL.createObjectURL(r)}return t}_initializeOptions(e){var t,r,n,i,s,o,a,l,c;this.worker=(t=e===null||e===void 0?void 0:e.worker)!==null&&t!==void 0?t:!1,this.accessToken=(r=e===null||e===void 0?void 0:e.accessToken)!==null&&r!==void 0?r:null;let u={};u.timeout=(n=e===null||e===void 0?void 0:e.timeout)!==null&&n!==void 0?n:wu,u.heartbeatIntervalMs=(i=e===null||e===void 0?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:tp.HEARTBEAT_INTERVAL,u.transport=(s=e===null||e===void 0?void 0:e.transport)!==null&&s!==void 0?s:Qo.getWebSocketConstructor(),u.params=e===null||e===void 0?void 0:e.params,u.logger=e===null||e===void 0?void 0:e.logger,u.heartbeatCallback=this._wrapHeartbeatCallback(e===null||e===void 0?void 0:e.heartbeatCallback),u.reconnectAfterMs=(o=e===null||e===void 0?void 0:e.reconnectAfterMs)!==null&&o!==void 0?o:(A)=>rp[A-1]||np;let d,f,g=(a=e===null||e===void 0?void 0:e.vsn)!==null&&a!==void 0?a:yu;switch(g){case bu:d=(A,m)=>m(JSON.stringify(A)),f=(A,m)=>m(JSON.parse(A));break;case Jo:d=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${u.vsn}`)}if(u.vsn=g,u.encode=(l=e===null||e===void 0?void 0:e.encode)!==null&&l!==void 0?l:d,u.decode=(c=e===null||e===void 0?void 0:e.decode)!==null&&c!==void 0?c:f,u.beforeReconnect=this._reconnectAuth.bind(this),(e===null||e===void 0?void 0:e.logLevel)||(e===null||e===void 0?void 0:e.log_level))this.logLevel=e.logLevel||e.log_level,u.params=Object.assign(Object.assign({},u.params),{log_level:this.logLevel});if(this.worker){if(typeof window<"u"&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=e===null||e===void 0?void 0:e.workerUrl,u.autoSendHeartbeat=!this.worker}return u}async _reconnectAuth(){if(await this._waitForAuthIfNeeded(),!this.isConnected())this.connect()}}var qn=class extends Error{constructor(e,t){super(e);this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&t.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function sp(e,t,r){let n=new URL(t,e);if(r){for(let[i,s]of Object.entries(r))if(s!==void 0)n.searchParams.set(i,s)}return n.toString()}async function op(e){if(!e||e.type==="none")return{};if(e.type==="bearer")return{Authorization:`Bearer ${e.token}`};if(e.type==="header")return{[e.name]:e.value};if(e.type==="custom")return await e.getHeaders();return{}}function ap(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:i,body:s,headers:o}){let a=sp(e.baseUrl,n,i),l=await op(e.auth),c=await t(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...o},body:s?JSON.stringify(s):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),f=d&&u?JSON.parse(u):u;if(!c.ok){let g=d?f:void 0,A=g?.error;throw new qn(A?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:A?.type,icebergCode:A?.code,details:g})}return{status:c.status,headers:c.headers,data:f}}}}function ps(e){return e.join("\x1F")}var lp=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:ps(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map((n)=>({namespace:n}))}async createNamespace(e,t){let r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ps(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ps(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ps(e.namespace)}`}),!0}catch(t){if(t instanceof qn&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(r){if(r instanceof qn&&r.status===409)return;throw r}}};function sn(e){return e.join("\x1F")}var cp=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let r={};if(this.accessDelegation)r["X-Iceberg-Access-Delegation"]=this.accessDelegation;return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};if(this.accessDelegation)t["X-Iceberg-Access-Delegation"]=this.accessDelegation;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};if(this.accessDelegation)t["X-Iceberg-Access-Delegation"]=this.accessDelegation;try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(r){if(r instanceof qn&&r.status===404)return!1;throw r}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof qn&&r.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},Iu=class{constructor(e){let t="v1";if(e.catalogName)t+=`/${e.catalogName}`;let r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=ap({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new lp(this.client,t),this.tableOps=new cp(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};var ys=class extends Error{constructor(e,t="storage",r,n){super(e);this.__isStorageError=!0,this.namespace=t,this.name=t==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}};function ws(e){return typeof e==="object"&&e!==null&&"__isStorageError"in e}var bs=class extends ys{constructor(e,t,r,n="storage"){super(e,n,t,r);this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Ou=class extends ys{constructor(e,t,r="storage"){super(e,r);this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};var up=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)},dp=(e)=>{if(typeof e!=="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},ea=(e)=>{if(Array.isArray(e))return e.map((r)=>ea(r));else if(typeof e==="function"||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([r,n])=>{let i=r.replace(/([-_][a-z])/gi,(s)=>s.toUpperCase().replace(/[-_]/g,""));t[i]=ea(n)}),t},hp=(e)=>{if(!e||typeof e!=="string")return!1;if(e.length===0||e.length>100)return!1;if(e.trim()!==e)return!1;if(e.includes("/")||e.includes("\\"))return!1;return/^[\w!.\*'() &$@=;:+,?-]+$/.test(e)};function ti(e){return ti=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ti(e)}function fp(e,t){if(ti(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ti(n)!="object")return n;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ap(e){var t=fp(e,"string");return ti(t)=="symbol"?t:t+""}function gp(e,t,r){return(t=Ap(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ku(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function X(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ku(Object(r),!0).forEach(function(n){gp(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ku(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var Ru=(e)=>{var t;return e.msg||e.message||e.error_description||(typeof e.error==="string"?e.error:(t=e.error)===null||t===void 0?void 0:t.message)||JSON.stringify(e)},mp=async(e,t,r,n)=>{if(e!==null&&typeof e==="object"&&typeof e.json==="function"){let i=e,s=parseInt(i.status,10);if(!Number.isFinite(s))s=500;i.json().then((o)=>{let a=(o===null||o===void 0?void 0:o.statusCode)||(o===null||o===void 0?void 0:o.code)||s+"";t(new bs(Ru(o),s,a,n))}).catch(()=>{let o=s+"";t(new bs(i.statusText||`HTTP ${s} error`,s,o,n))})}else t(new Ou(Ru(e),e,n))},pp=(e,t,r,n)=>{let i={method:e,headers:(t===null||t===void 0?void 0:t.headers)||{}};if(e==="GET"||e==="HEAD"||!n)return X(X({},i),r);if(dp(n)){var s;let o=(t===null||t===void 0?void 0:t.headers)||{},a;for(let[l,c]of Object.entries(o))if(l.toLowerCase()==="content-type")a=c;i.headers=bp(o,"Content-Type",(s=a)!==null&&s!==void 0?s:"application/json"),i.body=JSON.stringify(n)}else i.body=n;if(t===null||t===void 0?void 0:t.duplex)i.duplex=t.duplex;return X(X({},i),r)};function bp(e,t,r){let n=X({},e);for(let i of Object.keys(n))if(i.toLowerCase()===t.toLowerCase())delete n[i];return n[t]=r,n}async function ei(e,t,r,n,i,s,o){return new Promise((a,l)=>{e(r,pp(t,n,i,s)).then((c)=>{if(!c.ok)throw c;if(n===null||n===void 0?void 0:n.noResolveJson)return c;if(o==="vectors"){let u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!u||!u.includes("application/json"))return{}}return c.json()}).then((c)=>a(c)).catch((c)=>mp(c,l,n,o))})}function Bu(e="storage"){return{get:async(t,r,n,i)=>ei(t,"GET",r,n,i,void 0,e),post:async(t,r,n,i,s)=>ei(t,"POST",r,i,s,n,e),put:async(t,r,n,i,s)=>ei(t,"PUT",r,i,s,n,e),head:async(t,r,n,i)=>ei(t,"HEAD",r,X(X({},n),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,r,n,i,s)=>ei(t,"DELETE",r,i,s,n,e)}}var yp=Bu("storage"),{get:ri,post:St,put:ta,head:wp,remove:ra}=yp,mt=Bu("vectors"),on=class{constructor(e,t={},r,n="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=Object.fromEntries(Object.entries(t).map(([i,s])=>[i.toLowerCase(),s])),this.fetch=up(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=X(X({},this.headers),{},{[e.toLowerCase()]:t}),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(ws(r))return{data:null,error:r};throw r}}},vp=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(ws(t))return{data:null,error:t};throw t}}},Pu;Pu=Symbol.toStringTag;var _p=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Pu]="BlobDownloadBuilder",this.promise=null}asStream(){return new vp(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){if(!this.promise)this.promise=this.execute();return this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(ws(t))return{data:null,error:t};throw t}}},Cp={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Tu={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},xp=class extends on{constructor(e,t={},r,n){super(e,t,n,"storage");this.bucketId=r}async uploadOrUpdate(e,t,r,n){var i=this;return i.handleOperation(async()=>{let s,o=X(X({},Tu),n),a=X(X({},i.headers),e==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;if(typeof Blob<"u"&&r instanceof Blob){if(s=new FormData,s.append("cacheControl",o.cacheControl),l)s.append("metadata",i.encodeMetadata(l));s.append("",r)}else if(typeof FormData<"u"&&r instanceof FormData){if(s=r,!s.has("cacheControl"))s.append("cacheControl",o.cacheControl);if(l&&!s.has("metadata"))s.append("metadata",i.encodeMetadata(l))}else{if(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l)a["x-metadata"]=i.toBase64(i.encodeMetadata(l));if((typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s==="object"&&("pipe"in s)&&typeof s.pipe==="function")&&!o.duplex)o.duplex="half"}if(n===null||n===void 0?void 0:n.headers)a=X(X({},a),n.headers);let c=i._removeEmptyFolders(t),u=i._getFinalPath(c),d=await(e=="PUT"?ta:St)(i.fetch,`${i.url}/object/${u}`,s,X({headers:a},(o===null||o===void 0?void 0:o.duplex)?{duplex:o.duplex}:{}));return{path:c,id:d.Id,fullPath:d.Key}})}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,n){var i=this;let s=i._removeEmptyFolders(e),o=i._getFinalPath(s),a=new URL(i.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",t),i.handleOperation(async()=>{let l,c=X(X({},Tu),n),u=X(X({},i.headers),{"x-upsert":String(c.upsert)});if(typeof Blob<"u"&&r instanceof Blob)l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r);else if(typeof FormData<"u"&&r instanceof FormData)l=r,l.append("cacheControl",c.cacheControl);else l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType;return{path:s,fullPath:(await ta(i.fetch,a.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(e),i=X({},r.headers);if(t===null||t===void 0?void 0:t.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 ys("No token returned by API");return{signedUrl:o.toString(),path:e,token:a}})}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var n=this;return n.handleOperation(async()=>await St(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r===null||r===void 0?void 0:r.destinationBucket},{headers:n.headers}))}async copy(e,t,r){var n=this;return n.handleOperation(async()=>({path:(await St(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r===null||r===void 0?void 0:r.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(e,t,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(e),s=typeof(r===null||r===void 0?void 0:r.transform)==="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await St(n.fetch,`${n.url}/object/sign/${i}`,X({expiresIn:t},s?{transform:r.transform}:{}),{headers:n.headers}),a=new URLSearchParams;if(r===null||r===void 0?void 0:r.download)a.set("download",r.download===!0?"":r.download);if((r===null||r===void 0?void 0:r.cacheNonce)!=null)a.set("cacheNonce",String(r.cacheNonce));let l=a.toString(),c=s&&o.signedURL.includes("/object/sign/")?o.signedURL.replace("/object/sign/","/render/image/sign/"):o.signedURL;return{signedUrl:encodeURI(`${n.url}${c}${l?`&${l}`:""}`)}})}async createSignedUrls(e,t,r){var n=this;return n.handleOperation(async()=>{let i=await St(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:t,paths:e},{headers:n.headers}),s=new URLSearchParams;if(r===null||r===void 0?void 0:r.download)s.set("download",r.download===!0?"":r.download);if((r===null||r===void 0?void 0:r.cacheNonce)!=null)s.set("cacheNonce",String(r.cacheNonce));let o=s.toString();return i.map((a)=>X(X({},a),{},{signedUrl:a.signedURL?encodeURI(`${n.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(e,t,r){let n=typeof(t===null||t===void 0?void 0:t.transform)<"u"?"render/image/authenticated":"object",i=new URLSearchParams;if(t===null||t===void 0?void 0:t.transform)this.applyTransformOptsToQuery(i,t.transform);if((t===null||t===void 0?void 0:t.cacheNonce)!=null)i.set("cacheNonce",String(t.cacheNonce));let s=i.toString(),o=this._getFinalPath(e);return new _p(()=>ri(this.fetch,`${this.url}/${n}/${o}${s?`?${s}`:""}`,{headers:this.headers,noResolveJson:!0},r),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation(async()=>ea(await ri(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})))}async exists(e){var t=this;let r=t._getFinalPath(e);try{return await wp(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(i){if(t.shouldThrowOnError)throw i;if(ws(i)){var n;let s=i instanceof bs?i.status:i instanceof Ou?(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(e,t){let r=this._getFinalPath(e),n=new URLSearchParams;if(t===null||t===void 0?void 0:t.download)n.set("download",t.download===!0?"":t.download);if(t===null||t===void 0?void 0:t.transform)this.applyTransformOptsToQuery(n,t.transform);if((t===null||t===void 0?void 0:t.cacheNonce)!=null)n.set("cacheNonce",String(t.cacheNonce));let i=n.toString(),s=typeof(t===null||t===void 0?void 0:t.transform)<"u"?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}`)+(i?`?${i}`:"")}}}async remove(e){var t=this;return t.handleOperation(async()=>await ra(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,r){var n=this;return n.handleOperation(async()=>{let i=X(X(X({},Cp),t),{},{prefix:e||""});return await St(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{let n=X({},e);return await St(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");return btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(e,t){if(t.width)e.set("width",t.width.toString());if(t.height)e.set("height",t.height.toString());if(t.resize)e.set("resize",t.resize);if(t.format)e.set("format",t.format);if(t.quality)e.set("quality",t.quality.toString());return e}},Ep="2.103.0",ni={"X-Client-Info":`storage-js/${Ep}`},Sp=class extends on{constructor(e,t={},r,n){let i=new URL(e);if(n===null||n===void 0?void 0:n.useNewHostname){if(/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=X(X({},ni),t);super(s,o,r,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await ri(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await ri(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation(async()=>await St(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async updateBucket(e,t){var r=this;return r.handleOperation(async()=>await ta(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await St(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ra(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};if(e){if("limit"in e)t.limit=String(e.limit);if("offset"in e)t.offset=String(e.offset);if(e.search)t.search=e.search;if(e.sortColumn)t.sortColumn=e.sortColumn;if(e.sortOrder)t.sortOrder=e.sortOrder}return Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},Ip=class extends on{constructor(e,t={},r){let n=e.replace(/\/$/,""),i=X(X({},ni),t);super(n,i,r,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await St(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=new URLSearchParams;if((e===null||e===void 0?void 0:e.limit)!==void 0)r.set("limit",e.limit.toString());if((e===null||e===void 0?void 0:e.offset)!==void 0)r.set("offset",e.offset.toString());if(e===null||e===void 0?void 0:e.sortColumn)r.set("sortColumn",e.sortColumn);if(e===null||e===void 0?void 0:e.sortOrder)r.set("sortOrder",e.sortOrder);if(e===null||e===void 0?void 0:e.search)r.set("search",e.search);let n=r.toString(),i=n?`${t.url}/bucket?${n}`:`${t.url}/bucket`;return await ri(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ra(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!hp(e))throw new ys("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 Iu({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,s){let o=i[s];if(typeof o!=="function")return o;return async(...a)=>{try{return{data:await o.apply(i,a),error:null}}catch(l){if(n)throw l;return{data:null,error:l}}}}})}},kp=class extends on{constructor(e,t={},r){let n=e.replace(/\/$/,""),i=X(X({},ni),{},{"Content-Type":"application/json"},t);super(n,i,r,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await mt.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await mt.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}},Rp=class extends on{constructor(e,t={},r){let n=e.replace(/\/$/,""),i=X(X({},ni),{},{"Content-Type":"application/json"},t);super(n,i,r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0){if(e.segmentIndex<0||e.segmentIndex>=e.segmentCount)throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}}return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},Tp=class extends on{constructor(e,t={},r){let n=e.replace(/\/$/,""),i=X(X({},ni),{},{"Content-Type":"application/json"},t);super(n,i,r,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await mt.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},Op=class extends Tp{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Bp(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,r=this;return t().call(r,e)}async getBucket(e){var t=()=>super.getBucket,r=this;return t().call(r,e)}async listBuckets(e={}){var t=()=>super.listBuckets,r=this;return t().call(r,e)}async deleteBucket(e){var t=()=>super.deleteBucket,r=this;return t().call(r,e)}},Bp=class extends kp{constructor(e,t,r,n){super(e,t,n);this.vectorBucketName=r}async createIndex(e){var t=()=>super.createIndex,r=this;return t().call(r,X(X({},e),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,r=this;return t().call(r,X(X({},e),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,r=this;return t().call(r,r.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,r=this;return t().call(r,r.vectorBucketName,e)}index(e){return new Pp(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Pp=class extends Rp{constructor(e,t,r,n,i){super(e,t,i);this.vectorBucketName=r,this.indexName=n}async putVectors(e){var t=()=>super.putVectors,r=this;return t().call(r,X(X({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(e){var t=()=>super.getVectors,r=this;return t().call(r,X(X({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,r=this;return t().call(r,X(X({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,r=this;return t().call(r,X(X({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,r=this;return t().call(r,X(X({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Du=class extends Sp{constructor(e,t={},r,n){super(e,t,r,n)}from(e){return new xp(this.url,this.headers,e,this.fetch)}get vectors(){return new Op(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Ip(this.url+"/iceberg",this.headers,this.fetch)}};var vs="2.103.0";var kr=30000,_s=3,Cs=_s*kr,Mu="http://localhost:9999",Nu="supabase.auth.token";var Lu={"X-Client-Info":`gotrue-js/${vs}`};var ii="X-Supabase-Api-Version",na={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Fu=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Gu=600000;class Rr extends Error{constructor(e,t,r){super(e);this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function G(e){return typeof e==="object"&&e!==null&&"__isAuthError"in e}class ia extends Rr{constructor(e,t,r){super(e,t,r);this.name="AuthApiError",this.status=t,this.code=r}}function Uu(e){return G(e)&&e.name==="AuthApiError"}class It extends Rr{constructor(e,t){super(e);this.name="AuthUnknownError",this.originalError=t}}class Ut extends Rr{constructor(e,t,r,n){super(e,r,n);this.name=t,this.status=r}}class at extends Ut{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function si(e){return G(e)&&e.name==="AuthSessionMissingError"}class Ar extends Ut{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class an extends Ut{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ln extends Ut{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0);this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Hu(e){return G(e)&&e.name==="AuthImplicitGrantRedirectError"}class xs extends Ut{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0);this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class sa extends Ut{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")}}class oi extends Ut{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Es(e){return G(e)&&e.name==="AuthRetryableFetchError"}class Ss extends Ut{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password");this.reasons=r}}class cn extends Ut{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}var Is="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ju=`
44
+ \r=`.split(""),Dp=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<ju.length;t+=1)e[ju[t].charCodeAt(0)]=-2;for(let t=0;t<Is.length;t+=1)e[Is[t].charCodeAt(0)]=t;return e})();function Ku(e,t,r){if(e!==null){t.queue=t.queue<<8|e,t.queuedBits+=8;while(t.queuedBits>=6){let n=t.queue>>t.queuedBits-6&63;r(Is[n]),t.queuedBits-=6}}else if(t.queuedBits>0){t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;while(t.queuedBits>=6){let n=t.queue>>t.queuedBits-6&63;r(Is[n]),t.queuedBits-=6}}}function Wu(e,t,r){let n=Dp[e];if(n>-1){t.queue=t.queue<<6|n,t.queuedBits+=6;while(t.queuedBits>=8)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}else if(n===-2)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function oa(e){let t=[],r=(o)=>{t.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=(o)=>{Lp(o,n,r)};for(let o=0;o<e.length;o+=1)Wu(e.charCodeAt(o),i,s);return t.join("")}function Mp(e,t){if(e<=127){t(e);return}else if(e<=2047){t(192|e>>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function Np(e,t){for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>55295&&n<=56319){let i=(n-55296)*1024&65535;n=(e.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}Mp(n,t)}}function Lp(e,t,r){if(t.utf8seq===0){if(e<=127){r(e);return}for(let n=1;n<6;n+=1)if((e>>7-n&1)===0){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");if(t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0)r(t.codepoint)}}function gr(e){let t=[],r={queue:0,queuedBits:0},n=(i)=>{t.push(i)};for(let i=0;i<e.length;i+=1)Wu(e.charCodeAt(i),r,n);return new Uint8Array(t)}function Yu(e){let t=[];return Np(e,(r)=>t.push(r)),new Uint8Array(t)}function zt(e){let t=[],r={queue:0,queuedBits:0},n=(i)=>{t.push(i)};return e.forEach((i)=>Ku(i,r,n)),Ku(null,r,n),t.join("")}function Qu(e){return Math.round(Date.now()/1000)+e}function Ju(){return Symbol("auth-callback")}var Qe=()=>typeof window<"u"&&typeof document<"u",Tr={tested:!1,writable:!1},ks=()=>{if(!Qe())return!1;try{if(typeof globalThis.localStorage!=="object")return!1}catch(t){return!1}if(Tr.tested)return Tr.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Tr.tested=!0,Tr.writable=!0}catch(t){Tr.tested=!0,Tr.writable=!1}return Tr.writable};function Vu(e){let t={},r=new URL(e);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,s)=>{t[s]=i})}catch(n){}return r.searchParams.forEach((n,i)=>{t[i]=n}),t}var Rs=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)},Zu=(e)=>typeof e==="object"&&e!==null&&("status"in e)&&("ok"in e)&&("json"in e)&&typeof e.json==="function",Or=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},mr=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(n){return r}},Xe=async(e,t)=>{await e.removeItem(t)};class ai{constructor(){this.promise=new ai.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}ai.promiseConstructor=Promise;function li(e){let t=e.split(".");if(t.length!==3)throw new cn("Invalid JWT structure");for(let n=0;n<t.length;n++)if(!Fu.test(t[n]))throw new cn("JWT not in base64url format");return{header:JSON.parse(oa(t[0])),payload:JSON.parse(oa(t[1])),signature:gr(t[2]),raw:{header:t[0],payload:t[1]}}}async function $u(e){return await new Promise((t)=>{setTimeout(()=>t(null),e)})}function Xu(e,t){return new Promise((n,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{let o=await e(s);if(!t(s,null,o)){n(o);return}}catch(o){if(!t(s,o)){i(o);return}}})()})}function Fp(e){return("0"+e.toString(16)).substr(-2)}function Gp(){let t=new Uint32Array(56);if(typeof crypto>"u"){let i="";for(let s=0;s<56;s++)i+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~".charAt(Math.floor(Math.random()*66));return i}return crypto.getRandomValues(t),Array.from(t,Fp).join("")}async function Up(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map((s)=>String.fromCharCode(s)).join("")}async function Hp(e){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."),e;let r=await Up(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Br(e,t,r=!1){let n=Gp(),i=n;if(r)i+="/PASSWORD_RECOVERY";await Or(e,`${t}-code-verifier`,i);let s=await Hp(n);return[s,n===s?"plain":"s256"]}var jp=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function zu(e){let t=e.headers.get(ii);if(!t)return null;if(!t.match(jp))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(r){return null}}function qu(e){if(!e)throw Error("Missing exp claim");let t=Math.floor(Date.now()/1000);if(e<=t)throw Error("JWT has expired")}function ed(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}var Kp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Pr(e){if(!Kp.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ts(){return new Proxy({},{get:(t,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 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:(t,r)=>{throw 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:(t,r)=>{throw 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 td(e,t){return new Proxy(e,{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)}if(!t.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."),t.value=!0;return Reflect.get(r,n,i)}})}function aa(e){return JSON.parse(JSON.stringify(e))}var Dr=(e)=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Wp=[502,503,504];async function rd(e){var t;if(!Zu(e))throw new oi(Dr(e),0);if(Wp.includes(e.status))throw new oi(Dr(e),e.status);let r;try{r=await e.json()}catch(s){throw new It(Dr(s),s)}let n=void 0,i=zu(e);if(i&&i.getTime()>=na["2024-01-01"].timestamp&&typeof r==="object"&&r&&typeof r.code==="string")n=r.code;else if(typeof r==="object"&&r&&typeof r.error_code==="string")n=r.error_code;if(!n){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 Ss(Dr(r),e.status,r.weak_password.reasons)}else if(n==="weak_password")throw new Ss(Dr(r),e.status,((t=r.weak_password)===null||t===void 0?void 0:t.reasons)||[]);else if(n==="session_not_found")throw new at;throw new ia(Dr(r),e.status||500,n)}var Yp=(e,t,r,n)=>{let i={method:e,headers:(t===null||t===void 0?void 0:t.headers)||{}};if(e==="GET")return i;return i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t===null||t===void 0?void 0:t.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r)};async function V(e,t,r,n){var i;let s=Object.assign({},n===null||n===void 0?void 0:n.headers);if(!s[ii])s[ii]=na["2024-01-01"].name;if(n===null||n===void 0?void 0:n.jwt)s.Authorization=`Bearer ${n.jwt}`;let o=(i=n===null||n===void 0?void 0:n.query)!==null&&i!==void 0?i:{};if(n===null||n===void 0?void 0:n.redirectTo)o.redirect_to=n.redirectTo;let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Qp(e,t,r+a,{headers:s,noResolveJson:n===null||n===void 0?void 0:n.noResolveJson},{},n===null||n===void 0?void 0:n.body);return(n===null||n===void 0?void 0:n.xform)?n===null||n===void 0?void 0:n.xform(l):{data:Object.assign({},l),error:null}}async function Qp(e,t,r,n,i,s){let o=Yp(t,n,i,s),a;try{a=await e(r,Object.assign({},o))}catch(l){throw console.error(l),new oi(Dr(l),0)}if(!a.ok)await rd(a);if(n===null||n===void 0?void 0:n.noResolveJson)return a;try{return await a.json()}catch(l){await rd(l)}}function Ct(e){var t;let r=null;if(Jp(e)){if(r=Object.assign({},e),!e.expires_at)r.expires_at=Qu(e.expires_in)}let n=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:r,user:n},error:null}}function la(e){let t=Ct(e);if(!t.error&&e.weak_password&&typeof e.weak_password==="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message==="string"&&e.weak_password.reasons.reduce((r,n)=>r&&typeof n==="string",!0))t.data.weak_password=e.weak_password;return t}function Ht(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function nd(e){return{data:e,error:null}}function id(e){let{action_link:t,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s}=e,o=Er(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:t,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function ca(e){return e}function Jp(e){return e.access_token&&e.refresh_token&&e.expires_in}var Os=["global","local","others"];class un{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Rs(r),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,t=Os[0]){if(Os.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${Os.join(", ")}`);try{return await V(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(G(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await V(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Ht})}catch(r){if(G(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Er(e,["options"]),n=Object.assign(Object.assign({},r),t);if("newEmail"in r)n.new_email=r===null||r===void 0?void 0:r.newEmail,delete n.newEmail;return await V(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:id,redirectTo:t===null||t===void 0?void 0:t.redirectTo})}catch(t){if(G(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await V(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ht})}catch(t){if(G(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,n,i,s,o,a;try{let l={nextPage:null,lastPage:0,total:0},c=await V(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e===null||e===void 0?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(n=e===null||e===void 0?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:ca});if(c.error)throw c.error;let u=await c.json(),d=(s=c.headers.get("x-total-count"))!==null&&s!==void 0?s:0,f=(a=(o=c.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&a!==void 0?a:[];if(f.length>0)f.forEach((g)=>{let A=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(g.split(";")[1].split("=")[1]);l[`${m}Page`]=A}),l.total=parseInt(d);return{data:Object.assign(Object.assign({},u),l),error:null}}catch(l){if(G(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){Pr(e);try{return await V(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ht})}catch(t){if(G(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Pr(e);try{return await V(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Ht})}catch(r){if(G(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){Pr(e);try{return await V(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Ht})}catch(r){if(G(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){Pr(e.userId);try{let{data:t,error:r}=await V(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:(n)=>({data:{factors:n},error:null})});return{data:t,error:r}}catch(t){if(G(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Pr(e.userId),Pr(e.id);try{return{data:await V(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(G(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,n,i,s,o,a;try{let l={nextPage:null,lastPage:0,total:0},c=await V(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e===null||e===void 0?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(n=e===null||e===void 0?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:ca});if(c.error)throw c.error;let u=await c.json(),d=(s=c.headers.get("x-total-count"))!==null&&s!==void 0?s:0,f=(a=(o=c.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&a!==void 0?a:[];if(f.length>0)f.forEach((g)=>{let A=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(g.split(";")[1].split("=")[1]);l[`${m}Page`]=A}),l.total=parseInt(d);return{data:Object.assign(Object.assign({},u),l),error:null}}catch(l){if(G(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await V(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(G(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await V(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(G(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await V(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:(r)=>({data:r,error:null})})}catch(r){if(G(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await V(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(G(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await V(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(G(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{let t={};if(e===null||e===void 0?void 0:e.type)t.type=e.type;return await V(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:(r)=>{var n;return{data:{providers:(n=r===null||r===void 0?void 0:r.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(t){if(G(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await V(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(G(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await V(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:(t)=>({data:t,error:null})})}catch(t){if(G(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await V(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:(r)=>({data:r,error:null})})}catch(r){if(G(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await V(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(G(t))return{data:null,error:t};throw t}}}function ua(e={}){return{getItem:(t)=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:(t)=>{delete e[t]}}}var kt={debug:!!(globalThis&&ks()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Ps extends Error{constructor(e){super(e);this.isAcquireTimeout=!0}}class Bs extends Ps{}async function da(e,t,r){if(kt.debug)console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let n=new globalThis.AbortController,i;if(t>0)i=setTimeout(()=>{if(n.abort(),kt.debug)console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t);await Promise.resolve();try{return await globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async(s)=>{if(s){if(clearTimeout(i),kt.debug)console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{if(kt.debug)console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}else if(t===0){if(kt.debug)console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e);throw new Bs(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`)}else{if(kt.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(t>0)clearTimeout(i);if((s===null||s===void 0?void 0:s.name)==="AbortError"&&t>0)if(n.signal.aborted){if(kt.debug)console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",e);return console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${t}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(e,{mode:"exclusive",steal:!0},async(o)=>{if(o){if(kt.debug)console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,o.name);try{return await r()}finally{if(kt.debug)console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,o.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}))}else{if(kt.debug)console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",e);throw new Bs(`Lock "${e}" was released because another request stole it`)}throw s}}function sd(){if(typeof globalThis==="object")return;try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){if(typeof self<"u")self.globalThis=self}}function ha(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function od(e){return parseInt(e,16)}function ad(e){let t=new TextEncoder().encode(e);return"0x"+Array.from(t,(n)=>n.toString(16).padStart(2,"0")).join("")}function ld(e){var t;let{chainId:r,domain:n,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:f}=e;{if(!Number.isInteger(r))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if((t=e.statement)===null||t===void 0?void 0:t.includes(`
45
+ `))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}let g=ha(e.address),A=u?`${u}://${n}`:n,m=e.statement?`${e.statement}
46
+ `:"",b=`${A} wants you to sign in with your Ethereum account:
47
+ ${g}
48
48
 
49
- ${m}`,v=`URI: ${d}
50
- Version: ${A}
49
+ ${m}`,w=`URI: ${d}
50
+ Version: ${f}
51
51
  Chain ID: ${r}${o?`
52
52
  Nonce: ${o}`:""}
53
- Issued At: ${s.toISOString()}`;if(i)v+=`
54
- Expiration Time: ${i.toISOString()}`;if(a)v+=`
55
- Not Before: ${a.toISOString()}`;if(l)v+=`
56
- Request ID: ${l}`;if(c){let y=`
57
- Resources:`;for(let E of c){if(!E||typeof E!=="string")throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${E}`);y+=`
58
- - ${E}`}v+=y}return`${p}
59
- ${v}`}class Be extends Error{constructor({message:e,code:t,cause:r,name:n}){var i;super(e,{cause:r});this.__isWebAuthnError=!0,this.name=(i=n!==null&&n!==void 0?n:r instanceof Error?r.name:void 0)!==null&&i!==void 0?i:"Unknown Error",this.code=t}}class ln extends Be{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e});this.name="WebAuthnUnknownError",this.originalError=t}}function Zu({error:e,options:t}){var r,n,i;let{publicKey:s}=t;if(!s)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new Be({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new Be({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});else if(t.mediation==="conditional"&&((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new Be({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});else if(((i=s.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new Be({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else if(e.name==="InvalidStateError")return new Be({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});else if(e.name==="NotAllowedError")return new Be({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if(e.name==="NotSupportedError"){if(s.pubKeyCredParams.filter((a)=>a.type==="public-key").length===0)return new Be({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e});return new Be({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}else if(e.name==="SecurityError"){let o=window.location.hostname;if(!zo(o))return new Be({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});else if(s.rp.id!==o)return new Be({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if(e.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new Be({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new Be({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new Be({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Xu({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new Be({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="NotAllowedError")return new Be({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if(e.name==="SecurityError"){let n=window.location.hostname;if(!zo(n))return new Be({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});else if(r.rpId!==n)return new Be({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if(e.name==="UnknownError")return new Be({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new Be({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class qu{createNewAbortSignal(){if(this.controller){let t=Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}var bp=new qu;function ed(e){if(!e)throw Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON==="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:n}=e,i=_r(e,["challenge","user","excludeCredentials"]),s=ur(t).buffer,o=Object.assign(Object.assign({},r),{id:ur(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:s,user:o});if(n&&n.length>0){a.excludeCredentials=Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:ur(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function td(e){if(!e)throw Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON==="function")return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,n=_r(e,["challenge","allowCredentials"]),i=ur(t).buffer,s=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){s.allowCredentials=Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];s.allowCredentials[o]=Object.assign(Object.assign({},a),{id:ur(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function rd(e){var t;if("toJSON"in e&&typeof e.toJSON==="function")return e.toJSON();let r=e;return{id:e.id,rawId:e.id,response:{attestationObject:zt(new Uint8Array(e.response.attestationObject)),clientDataJSON:zt(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:(t=r.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function nd(e){var t;if("toJSON"in e&&typeof e.toJSON==="function")return e.toJSON();let r=e,n=e.getClientExtensionResults(),i=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:zt(new Uint8Array(i.authenticatorData)),clientDataJSON:zt(new Uint8Array(i.clientDataJSON)),signature:zt(new Uint8Array(i.signature)),userHandle:i.userHandle?zt(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(t=r.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function zo(e){return e==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function zu(){var e,t;return!!(Ke()&&("PublicKeyCredential"in window)&&window.PublicKeyCredential&&("credentials"in navigator)&&typeof((e=navigator===null||navigator===void 0?void 0:navigator.credentials)===null||e===void 0?void 0:e.create)==="function"&&typeof((t=navigator===null||navigator===void 0?void 0:navigator.credentials)===null||t===void 0?void 0:t.get)==="function")}async function yp(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new ln("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new ln("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:Zu({error:t,options:e})}}}async function wp(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new ln("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new ln("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:Xu({error:t,options:e})}}}var vp={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},_p={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function bs(...e){let t=(i)=>i!==null&&typeof i==="object"&&!Array.isArray(i),r=(i)=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(let i of e){if(!i)continue;for(let s in i){let o=i[s];if(o===void 0)continue;if(Array.isArray(o))n[s]=o;else if(r(o))n[s]=o;else if(t(o)){let a=n[s];if(t(a))n[s]=bs(a,o);else n[s]=bs(o)}else n[s]=o}}return n}function Cp(e,t){return bs(vp,e,t||{})}function xp(e,t){return bs(_p,e,t||{})}class qo{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:n},i){var s;try{let{data:o,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!o)return{data:null,error:a};let l=n!==null&&n!==void 0?n:bp.createNewAbortSignal();if(o.webauthn.type==="create"){let{user:c}=o.webauthn.credential_options.publicKey;if(!c.name){let u=r;if(!u){let A=(await this.client.getUser()).data.user,f=((s=A===null||A===void 0?void 0:A.user_metadata)===null||s===void 0?void 0:s.name)||(A===null||A===void 0?void 0:A.email)||(A===null||A===void 0?void 0:A.id)||"User";c.name=`${c.id}:${f}`}else c.name=`${c.id}:${u}`}if(!c.displayName)c.displayName=c.name}switch(o.webauthn.type){case"create":{let c=Cp(o.webauthn.credential_options.publicKey,i===null||i===void 0?void 0:i.create),{data:u,error:d}=await yp({publicKey:c,signal:l});if(u)return{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null};return{data:null,error:d}}case"request":{let c=xp(o.webauthn.credential_options.publicKey,i===null||i===void 0?void 0:i.request),{data:u,error:d}=await wp(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:c,signal:l}));if(u)return{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null};return{data:null,error:d}}}}catch(o){if(F(o))return{data:null,error:o};return{data:null,error:new St("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return{data:null,error:new Sr("rpId is required for WebAuthn authentication")};try{if(!zu())return{data:null,error:new St("Browser does not support WebAuthn",null)};let{data:s,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:n},{request:i});if(!s)return{data:null,error:o};let{webauthn:a}=s;return this._verify({factorId:e,challengeId:s.challengeId,webauthn:{type:a.type,rpId:t,rpOrigins:r,credential_response:a.credential_response}})}catch(s){if(F(s))return{data:null,error:s};return{data:null,error:new St("Unexpected error in authenticate",s)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return{data:null,error:new Sr("rpId is required for WebAuthn registration")};try{if(!zu())return{data:null,error:new St("Browser does not support WebAuthn",null)};let{data:s,error:o}=await this._enroll({friendlyName:e});if(!s)return await this.client.mfa.listFactors().then((c)=>{var u;return(u=c.data)===null||u===void 0?void 0:u.all.find((d)=>d.factor_type==="webauthn"&&d.friendly_name===e&&d.status!=="unverified")}).then((c)=>c?this.client.mfa.unenroll({factorId:c===null||c===void 0?void 0:c.id}):void 0),{data:null,error:o};let{data:a,error:l}=await this._challenge({factorId:s.id,friendlyName:s.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:n},{create:i});if(!a)return{data:null,error:l};return this._verify({factorId:s.id,challengeId:a.challengeId,webauthn:{rpId:t,rpOrigins:r,type:a.webauthn.type,credential_response:a.webauthn.credential_response}})}catch(s){if(F(s))return{data:null,error:s};return{data:null,error:new St("Unexpected error in register",s)}}}}Qu();var Ep={url:_u,storageKey:Cu,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:xu,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5000,skipAutoInitialize:!1};async function id(e,t,r){return await r()}var cn={};class ai{get jwks(){var e,t;return(t=(e=cn[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){cn[this.storageKey]=Object.assign(Object.assign({},cn[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=cn[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){cn[this.storageKey]=Object.assign(Object.assign({},cn[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Ep),e);if(this.storageKey=i.storageKey,this.instanceID=(t=ai.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,ai.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug==="function")this.logger=i.debug;if(this.instanceID>0&&Ke()){let s=`${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.`;if(console.warn(s),this.logDebugMessages)console.trace(s)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new an({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=As(i.fetch),this.lock=i.lock||id,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock)this.lock=i.lock;else if(this.persistSession&&Ke()&&((r=globalThis===null||globalThis===void 0?void 0:globalThis.navigator)===null||r===void 0?void 0:r.locks))this.lock=Zo;else this.lock=id;if(!this.jwks)this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER;if(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 qo(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){if(i.storage)this.storage=i.storage;else if(hs())this.storage=globalThis.localStorage;else this.memoryStorage={},this.storage=$o(this.memoryStorage);if(i.userStorage)this.userStorage=i.userStorage}else this.memoryStorage={},this.storage=$o(this.memoryStorage);if(Ke()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(s){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",s)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async(s)=>{this._debug("received broadcast notification from other tab or client",s);try{await this._notifyAllSubscribers(s.data.event,s.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}if(!i.skipAutoInitialize)this.initialize().catch((s)=>{this._debug("#initialize()","error",s)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ss}) ${new Date().toISOString()}`}_debug(...e){if(this.logDebugMessages)this.logger(this._logPrefix(),...e);return this}async initialize(){if(this.initializePromise)return await this.initializePromise;return this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(Ke()){if(t=Nu(window.location.href),this._isImplicitGrantCallback(t))r="implicit";else if(await this._isPKCECallback(t))r="pkce"}if(Ke()&&this.detectSessionInUrl&&r!=="none"){let{data:n,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),ku(i)){let a=(e=i.details)===null||e===void 0?void 0:e.code;if(a==="identity_already_exists"||a==="identity_not_found"||a==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:s,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",s,"redirect type",o),await this._saveSession(s),setTimeout(async()=>{if(o==="recovery")await this._notifyAllSubscribers("PASSWORD_RECOVERY",s);else await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){if(F(t))return this._returnResult({error:t});return this._returnResult({error:new St("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,n;try{let i=await W(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e===null||e===void 0?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(n=e===null||e===void 0?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}},xform:_t}),{data:s,error:o}=i;if(o||!s)return this._returnResult({data:{user:null,session:null},error:o});let{session:a,user:l}=s;if(s.session)await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",a);return this._returnResult({data:{user:l,session:a},error:null})}catch(i){if(F(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,n;try{let i;if("email"in e){let{email:c,password:u,options:d}=e,A=null,f=null;if(this.flowType==="pkce")[A,f]=await Rr(this.storage,this.storageKey);i=await W(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d===null||d===void 0?void 0:d.emailRedirectTo,body:{email:c,password:u,data:(t=d===null||d===void 0?void 0:d.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d===null||d===void 0?void 0:d.captchaToken},code_challenge:A,code_challenge_method:f},xform:_t})}else if("phone"in e){let{phone:c,password:u,options:d}=e;i=await W(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:u,data:(r=d===null||d===void 0?void 0:d.data)!==null&&r!==void 0?r:{},channel:(n=d===null||d===void 0?void 0:d.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:d===null||d===void 0?void 0:d.captchaToken}},xform:_t})}else throw new nn("You must provide either an email or phone number and a password");let{data:s,error:o}=i;if(o||!s)return await $e(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});let{session:a,user:l}=s;if(s.session)await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",a);return this._returnResult({data:{user:l,session:a},error:null})}catch(i){if(await $e(this.storage,`${this.storageKey}-code-verifier`),F(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:s,options:o}=e;t=await W(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:s,gotrue_meta_security:{captcha_token:o===null||o===void 0?void 0:o.captchaToken}},xform:Jo})}else if("phone"in e){let{phone:i,password:s,options:o}=e;t=await W(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:s,gotrue_meta_security:{captcha_token:o===null||o===void 0?void 0:o.captchaToken}},xform:Jo})}else throw new nn("You must provide either an email or phone number and a password");let{data:r,error:n}=t;if(n)return this._returnResult({data:{user:null,session:null},error:n});else if(!r||!r.session||!r.user){let i=new cr;return this._returnResult({data:{user:null,session:null},error:i})}if(r.session)await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session);return this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:n})}catch(t){if(F(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,n,i,s,o,a,l,c,u,d;let A,f;if("message"in e)A=e.message,f=e.signature;else{let{chain:g,wallet:m,statement:p,options:v}=e,y;if(!Ke()){if(typeof m!=="object"||!(v===null||v===void 0?void 0:v.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=m}else if(typeof m==="object")y=m;else{let O=window;if("ethereum"in O&&typeof O.ethereum==="object"&&"request"in O.ethereum&&typeof O.ethereum.request==="function")y=O.ethereum;else throw 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.")}let E=new URL((t=v===null||v===void 0?void 0:v.url)!==null&&t!==void 0?t:window.location.href),_=await y.request({method:"eth_requestAccounts"}).then((O)=>O).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!_||_.length===0)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let b=Xo(_[0]),w=(r=v===null||v===void 0?void 0:v.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!w){let O=await y.request({method:"eth_chainId"});w=Ju(O)}let C={domain:E.host,address:b,statement:p,uri:E.href,version:"1",chainId:w,nonce:(n=v===null||v===void 0?void 0:v.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(s=(i=v===null||v===void 0?void 0:v.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&s!==void 0?s:new Date,expirationTime:(o=v===null||v===void 0?void 0:v.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(a=v===null||v===void 0?void 0:v.signInWithEthereum)===null||a===void 0?void 0:a.notBefore,requestId:(l=v===null||v===void 0?void 0:v.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(c=v===null||v===void 0?void 0:v.signInWithEthereum)===null||c===void 0?void 0:c.resources};A=$u(C),f=await y.request({method:"personal_sign",params:[Vu(A),b]})}try{let{data:g,error:m}=await W(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:A,signature:f},((u=e.options)===null||u===void 0?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:(d=e.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:_t});if(m)throw m;if(!g||!g.session||!g.user){let p=new cr;return this._returnResult({data:{user:null,session:null},error:p})}if(g.session)await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session);return this._returnResult({data:Object.assign({},g),error:m})}catch(g){if(F(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var t,r,n,i,s,o,a,l,c,u,d,A;let f,g;if("message"in e)f=e.message,g=e.signature;else{let{chain:m,wallet:p,statement:v,options:y}=e,E;if(!Ke()){if(typeof p!=="object"||!(y===null||y===void 0?void 0:y.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=p}else if(typeof p==="object")E=p;else{let b=window;if("solana"in b&&typeof b.solana==="object"&&(("signIn"in b.solana)&&typeof b.solana.signIn==="function"||("signMessage"in b.solana)&&typeof b.solana.signMessage==="function"))E=b.solana;else throw 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.")}let _=new URL((t=y===null||y===void 0?void 0:y.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in E&&E.signIn){let b=await E.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},y===null||y===void 0?void 0:y.signInWithSolana),{version:"1",domain:_.host,uri:_.href}),v?{statement:v}:null)),w;if(Array.isArray(b)&&b[0]&&typeof b[0]==="object")w=b[0];else if(b&&typeof b==="object"&&"signedMessage"in b&&"signature"in b)w=b;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in w&&"signature"in w&&(typeof w.signedMessage==="string"||w.signedMessage instanceof Uint8Array)&&w.signature instanceof Uint8Array)f=typeof w.signedMessage==="string"?w.signedMessage:new TextDecoder().decode(w.signedMessage),g=w.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in E)||typeof E.signMessage!=="function"||!("publicKey"in E)||typeof E!=="object"||!E.publicKey||!("toBase58"in E.publicKey)||typeof E.publicKey.toBase58!=="function")throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${_.host} wants you to sign in with your Solana account:`,E.publicKey.toBase58(),...v?["",v,""]:[""],"Version: 1",`URI: ${_.href}`,`Issued At: ${(n=(r=y===null||y===void 0?void 0:y.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...((i=y===null||y===void 0?void 0:y.signInWithSolana)===null||i===void 0?void 0:i.notBefore)?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...((s=y===null||y===void 0?void 0:y.signInWithSolana)===null||s===void 0?void 0:s.expirationTime)?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...((o=y===null||y===void 0?void 0:y.signInWithSolana)===null||o===void 0?void 0:o.chainId)?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...((a=y===null||y===void 0?void 0:y.signInWithSolana)===null||a===void 0?void 0:a.nonce)?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...((l=y===null||y===void 0?void 0:y.signInWithSolana)===null||l===void 0?void 0:l.requestId)?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...((u=(c=y===null||y===void 0?void 0:y.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||u===void 0?void 0:u.length)?["Resources",...y.signInWithSolana.resources.map((w)=>`- ${w}`)]:[]].join(`
60
- `);let b=await E.signMessage(new TextEncoder().encode(f),"utf8");if(!b||!(b instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=b}}try{let{data:m,error:p}=await W(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:zt(g)},((d=e.options)===null||d===void 0?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:(A=e.options)===null||A===void 0?void 0:A.captchaToken}}:null),xform:_t});if(p)throw p;if(!m||!m.session||!m.user){let v=new cr;return this._returnResult({data:{user:null,session:null},error:v})}if(m.session)await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session);return this._returnResult({data:Object.assign({},m),error:p})}catch(m){if(F(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e){let t=await dr(this.storage,`${this.storageKey}-code-verifier`),[r,n]=(t!==null&&t!==void 0?t:"").split("/");try{if(!r&&this.flowType==="pkce")throw new Wo;let{data:i,error:s}=await W(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:_t});if(await $e(this.storage,`${this.storageKey}-code-verifier`),s)throw s;if(!i||!i.session||!i.user){let o=new cr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}if(i.session)await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session);return this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n!==null&&n!==void 0?n:null}),error:s})}catch(i){if(await $e(this.storage,`${this.storageKey}-code-verifier`),F(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:t,provider:r,token:n,access_token:i,nonce:s}=e,o=await W(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:n,access_token:i,nonce:s,gotrue_meta_security:{captcha_token:t===null||t===void 0?void 0:t.captchaToken}},xform:_t}),{data:a,error:l}=o;if(l)return this._returnResult({data:{user:null,session:null},error:l});else if(!a||!a.session||!a.user){let c=new cr;return this._returnResult({data:{user:null,session:null},error:c})}if(a.session)await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session);return this._returnResult({data:a,error:l})}catch(t){if(F(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,n,i,s;try{if("email"in e){let{email:o,options:a}=e,l=null,c=null;if(this.flowType==="pkce")[l,c]=await Rr(this.storage,this.storageKey);let{error:u}=await W(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(t=a===null||a===void 0?void 0:a.data)!==null&&t!==void 0?t:{},create_user:(r=a===null||a===void 0?void 0:a.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:a===null||a===void 0?void 0:a.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:a===null||a===void 0?void 0:a.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:u})}if("phone"in e){let{phone:o,options:a}=e,{data:l,error:c}=await W(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=a===null||a===void 0?void 0:a.data)!==null&&n!==void 0?n:{},create_user:(i=a===null||a===void 0?void 0:a.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:a===null||a===void 0?void 0:a.captchaToken},channel:(s=a===null||a===void 0?void 0:a.channel)!==null&&s!==void 0?s:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:l===null||l===void 0?void 0:l.message_id},error:c})}throw new nn("You must provide either an email or phone number.")}catch(o){if(await $e(this.storage,`${this.storageKey}-code-verifier`),F(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var t,r;try{let n=void 0,i=void 0;if("options"in e)n=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken;let{data:s,error:o}=await W(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:_t});if(o)throw o;if(!s)throw Error("An error occurred on token verification.");let{session:a,user:l}=s;if(a===null||a===void 0?void 0:a.access_token)await this._saveSession(a),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a);return this._returnResult({data:{user:l,session:a},error:null})}catch(n){if(F(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var t,r,n,i,s;try{let o=null,a=null;if(this.flowType==="pkce")[o,a]=await Rr(this.storage,this.storageKey);let l=await W(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:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),((n=e===null||e===void 0?void 0:e.options)===null||n===void 0?void 0:n.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:a}),headers:this.headers,xform:Wu});if(((i=l.data)===null||i===void 0?void 0:i.url)&&Ke()&&!((s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect))window.location.assign(l.data.url);return this._returnResult(l)}catch(o){if(await $e(this.storage,`${this.storageKey}-code-verifier`),F(o))return this._returnResult({data:null,error:o});throw o}}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:t},error:r}=e;if(r)throw r;if(!t)throw new nt;let{error:n}=await W(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(F(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:n,options:i}=e,{error:s}=await W(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:n,gotrue_meta_security:{captcha_token:i===null||i===void 0?void 0:i.captchaToken}},redirectTo:i===null||i===void 0?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:s})}else if("phone"in e){let{phone:r,type:n,options:i}=e,{data:s,error:o}=await W(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:n,gotrue_meta_security:{captcha_token:i===null||i===void 0?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:s===null||s===void 0?void 0:s.message_id},error:o})}throw new nn("You must provide either an email or phone number and a type")}catch(t){if(F(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async(t)=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch(i){}})()),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 r=t();this.pendingInLock.push((async()=>{try{await r}catch(n){}})()),await r;while(this.pendingInLock.length){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await r}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 t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){if(this._debug("#__loadSession()","begin"),!this.lockAcquired)this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let e=null,t=await dr(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null)if(this._isValidSession(t))e=t;else this._debug("#getSession()","session from storage is not valid"),await this._removeSession();if(!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1000-Date.now()<as:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){let s=await dr(this.userStorage,this.storageKey+"-user");if(s===null||s===void 0?void 0:s.user)e.user=s.user;else e.user=fs()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let s={value:this.suppressGetSessionWarning};if(e.user=ju(e.user,s),s.value)this.suppressGetSessionWarning=!0}return{data:{session:e},error:null}}let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i)return this._returnResult({data:{session:null},error:i});return 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 t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());if(t.data.user)this.suppressGetSessionWarning=!0;return t}async _getUser(e){try{if(e)return await W(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Mt});return await this._useSession(async(t)=>{var r,n,i;let{data:s,error:o}=t;if(o)throw o;if(!((r=s.session)===null||r===void 0?void 0:r.access_token)&&!this.hasCustomAuthorizationHeader)return{data:{user:null},error:new nt};return await W(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:Mt})})}catch(t){if(F(t)){if(ni(t))await this._removeSession(),await $e(this.storage,`${this.storageKey}-code-verifier`);return this._returnResult({data:{user:null},error:t})}throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async(r)=>{let{data:n,error:i}=r;if(i)throw i;if(!n.session)throw new nt;let s=n.session,o=null,a=null;if(this.flowType==="pkce"&&e.email!=null)[o,a]=await Rr(this.storage,this.storageKey);let{data:l,error:c}=await W(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t===null||t===void 0?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:s.access_token,xform:Mt});if(c)throw c;return s.user=l.user,await this._saveSession(s),await this._notifyAllSubscribers("USER_UPDATED",s),this._returnResult({data:{user:s.user},error:null})})}catch(r){if(await $e(this.storage,`${this.storageKey}-code-verifier`),F(r))return this._returnResult({data:{user:null},error:r});throw r}}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 nt;let t=Date.now()/1000,r=t,n=!0,i=null,{payload:s}=oi(e.access_token);if(s.exp)r=s.exp,n=r<=t;if(n){let{data:o,error:a}=await this._callRefreshToken(e.refresh_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});if(!o)return{data:{user:null,session:null},error:null};i=o}else{let{data:o,error:a}=await this._getUser(e.access_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(F(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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(t)=>{var r;if(!e){let{data:s,error:o}=t;if(o)throw o;e=(r=s.session)!==null&&r!==void 0?r:void 0}if(!(e===null||e===void 0?void 0:e.refresh_token))throw new nt;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n)return this._returnResult({data:{user:null,session:null},error:null});return this._returnResult({data:{user:n.user,session:n},error:null})})}catch(t){if(F(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!Ke())throw new sn("No browser detected.");if(e.error||e.error_description||e.error_code)throw new sn(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new ls("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new sn("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new ls("No code detected.");let{data:v,error:y}=await this._exchangeCodeForSession(e.code);if(y)throw y;let E=new URL(window.location.href);return E.searchParams.delete("code"),window.history.replaceState(window.history.state,"",E.toString()),{data:{session:v.session,redirectType:null},error:null}}let{provider_token:r,provider_refresh_token:n,access_token:i,refresh_token:s,expires_in:o,expires_at:a,token_type:l}=e;if(!i||!o||!s||!l)throw new sn("No session defined in URL");let c=Math.round(Date.now()/1000),u=parseInt(o),d=c+u;if(a)d=parseInt(a);let A=d-c;if(A*1000<=Er)console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${A}s, should have been closer to ${u}s`);let f=d-u;if(c-f>=120)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,d,c);else if(c-f<0)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,d,c);let{data:g,error:m}=await this._getUser(i);if(m)throw m;let p={provider_token:r,provider_refresh_token:n,access_token:i,expires_in:u,expires_at:d,refresh_token:s,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(r){if(F(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(e){if(typeof this.detectSessionInUrl==="function")return this.detectSessionInUrl(new URL(window.location.href),e);return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await dr(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}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(t)=>{var r;let{data:n,error:i}=t;if(i&&!ni(i))return this._returnResult({error:i});let s=(r=n.session)===null||r===void 0?void 0:r.access_token;if(s){let{error:o}=await this.admin.signOut(s,e);if(o){if(!(Iu(o)&&(o.status===404||o.status===401||o.status===403)||ni(o)))return this._returnResult({error:o})}}if(e!=="others")await this._removeSession(),await $e(this.storage,`${this.storageKey}-code-verifier`);return this._returnResult({error:null})})}onAuthStateChange(e){let t=Du(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async(t)=>{var r,n;try{let{data:{session:i},error:s}=t;if(s)throw s;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),ni(i))console.warn(i);else console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,n=null;if(this.flowType==="pkce")[r,n]=await Rr(this.storage,this.storageKey,!0);try{return await W(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(await $e(this.storage,`${this.storageKey}-code-verifier`),F(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(F(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){if("token"in e)return this.linkIdentityIdToken(e);return this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:r,error:n}=await this._useSession(async(i)=>{var s,o,a,l,c;let{data:u,error:d}=i;if(d)throw d;let A=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(s=e.options)===null||s===void 0?void 0:s.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(a=e.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:!0});return await W(this.fetch,"GET",A,{headers:this.headers,jwt:(c=(l=u.session)===null||l===void 0?void 0:l.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;if(Ke()&&!((t=e.options)===null||t===void 0?void 0:t.skipBrowserRedirect))window.location.assign(r===null||r===void 0?void 0:r.url);return this._returnResult({data:{provider:e.provider,url:r===null||r===void 0?void 0:r.url},error:null})}catch(r){if(F(r))return this._returnResult({data:{provider:e.provider,url:null},error:r});throw r}}async linkIdentityIdToken(e){return await this._useSession(async(t)=>{var r;try{let{error:n,data:{session:i}}=t;if(n)throw n;let{options:s,provider:o,token:a,access_token:l,nonce:c}=e,u=await W(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i===null||i===void 0?void 0:i.access_token)!==null&&r!==void 0?r:void 0,body:{provider:o,id_token:a,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:s===null||s===void 0?void 0:s.captchaToken}},xform:_t}),{data:d,error:A}=u;if(A)return this._returnResult({data:{user:null,session:null},error:A});else if(!d||!d.session||!d.user)return this._returnResult({data:{user:null,session:null},error:new cr});if(d.session)await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session);return this._returnResult({data:d,error:A})}catch(n){if(await $e(this.storage,`${this.storageKey}-code-verifier`),F(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async(t)=>{var r,n;let{data:i,error:s}=t;if(s)throw s;return await W(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0})})}catch(t){if(F(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await Fu(async(n)=>{if(n>0)await Lu(200*Math.pow(2,n-1));return this._debug(t,"refreshing attempt",n),await W(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:_t})},(n,i)=>{let s=200*Math.pow(2,n);return i&&cs(i)&&Date.now()+s-r<Er})}catch(r){if(this._debug(t,"error",r),F(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e==="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});if(this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Ke()&&!t.skipBrowserRedirect)window.location.assign(r);return{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;let r="#_recoverAndRefresh()";this._debug("#_recoverAndRefresh()","begin");try{let n=await dr(this.storage,this.storageKey);if(n&&this.userStorage){let s=await dr(this.userStorage,this.storageKey+"-user");if(!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!s)s={user:n.user},await kr(this.userStorage,this.storageKey+"-user",s);n.user=(e=s===null||s===void 0?void 0:s.user)!==null&&e!==void 0?e:fs()}else if(n&&!n.user){if(!n.user){let s=await dr(this.storage,this.storageKey+"-user");if(s&&(s===null||s===void 0?void 0:s.user))n.user=s.user,await $e(this.storage,this.storageKey+"-user"),await kr(this.storage,this.storageKey,n);else n.user=fs()}}if(this._debug("#_recoverAndRefresh()","session from storage",n),!this._isValidSession(n)){if(this._debug("#_recoverAndRefresh()","session is not valid"),n!==null)await this._removeSession();return}let i=((t=n.expires_at)!==null&&t!==void 0?t:1/0)*1000-Date.now()<as;if(this._debug("#_recoverAndRefresh()",`session has${i?"":" not"} expired with margin of ${as}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:s}=await this._callRefreshToken(n.refresh_token);if(s){if(console.error(s),!cs(s))this._debug("#_recoverAndRefresh()","refresh failed with a non-retryable error, removing the session",s),await this._removeSession()}}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:s,error:o}=await this._getUser(n.access_token);if(!o&&(s===null||s===void 0?void 0:s.user))n.user=s.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n);else this._debug("#_recoverAndRefresh()","could not get user data, skipping SIGNED_IN notification")}catch(s){console.error("Error getting user data:",s),this._debug("#_recoverAndRefresh()","error getting user data, skipping SIGNED_IN notification",s)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug("#_recoverAndRefresh()","error",n),console.error(n);return}finally{this._debug("#_recoverAndRefresh()","end")}}async _callRefreshToken(e){var t,r;if(!e)throw new nt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new si;let{data:i,error:s}=await this._refreshAccessToken(e);if(s)throw s;if(!i.session)throw new nt;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let o={data:i.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(i){if(this._debug(n,"error",i),F(i)){let s={data:null,error:i};if(!cs(i))await this._removeSession();return(t=this.refreshingDeferred)===null||t===void 0||t.resolve(s),s}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,r=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${r}`);try{if(this.broadcastChannel&&r)this.broadcastChannel.postMessage({event:e,session:t});let i=[],s=Array.from(this.stateChangeEmitters.values()).map(async(o)=>{try{await o.callback(e,t)}catch(a){i.push(a)}});if(await Promise.all(s),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await $e(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),r=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){if(!r&&t.user)await kr(this.userStorage,this.storageKey+"-user",{user:t.user});let n=Object.assign({},t);delete n.user;let i=Qo(n);await kr(this.storage,this.storageKey,i)}else{let n=Qo(t);await kr(this.storage,this.storageKey,n)}}async _removeSession(){if(this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await $e(this.storage,this.storageKey),await $e(this.storage,this.storageKey+"-code-verifier"),await $e(this.storage,this.storageKey+"-user"),this.userStorage)await $e(this.userStorage,this.storageKey+"-user");await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{if(e&&Ke()&&(window===null||window===void 0?void 0:window.removeEventListener))window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Er);if(this.autoRefreshTicker=e,e&&typeof e==="object"&&typeof e.unref==="function")e.unref();else if(typeof Deno<"u"&&typeof Deno.unrefTimer==="function")Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);if(this.autoRefreshTickTimeout=t,t&&typeof t==="object"&&typeof t.unref==="function")t.unref();else if(typeof Deno<"u"&&typeof Deno.unrefTimer==="function")Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;if(this.autoRefreshTicker=null,e)clearInterval(e);let t=this.autoRefreshTickTimeout;if(this.autoRefreshTickTimeout=null,t)clearTimeout(t)}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(t)=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((r.expires_at*1000-e)/Er);if(this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Er}ms, refresh threshold is ${os} ticks`),n<=os)await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ps)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ke()||!(window===null||window===void 0?void 0:window.addEventListener)){if(this.autoRefreshToken)this.startAutoRefresh();return!1}try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window===null||window===void 0||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken)this._startAutoRefresh();if(!e)await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()})}else if(document.visibilityState==="hidden"){if(this.autoRefreshToken)this._stopAutoRefresh()}}async _getUrlForProvider(e,t,r){let n=[`provider=${encodeURIComponent(t)}`];if(r===null||r===void 0?void 0:r.redirectTo)n.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`);if(r===null||r===void 0?void 0:r.scopes)n.push(`scopes=${encodeURIComponent(r.scopes)}`);if(this.flowType==="pkce"){let[i,s]=await Rr(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(s)}`});n.push(o.toString())}if(r===null||r===void 0?void 0:r.queryParams){let i=new URLSearchParams(r.queryParams);n.push(i.toString())}if(r===null||r===void 0?void 0:r.skipBrowserRedirect)n.push(`skip_http_redirect=${r.skipBrowserRedirect}`);return`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async(t)=>{var r;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});return await W(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=n===null||n===void 0?void 0:n.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(F(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async(t)=>{var r,n;let{data:i,error:s}=t;if(s)return this._returnResult({data:null,error:s});let o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:a,error:l}=await W(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(r=i===null||i===void 0?void 0:i.session)===null||r===void 0?void 0:r.access_token});if(l)return this._returnResult({data:null,error:l});if(e.factorType==="totp"&&a.type==="totp"&&((n=a===null||a===void 0?void 0:a.totp)===null||n===void 0?void 0:n.qr_code))a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`;return this._returnResult({data:a,error:null})})}catch(t){if(F(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async(t)=>{var r;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});let s=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?rd(e.webauthn.credential_response):nd(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await W(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:s,headers:this.headers,jwt:(r=n===null||n===void 0?void 0:n.session)===null||r===void 0?void 0:r.access_token});if(a)return this._returnResult({data:null,error:a});return await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1000)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:a})})}catch(t){if(F(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async(t)=>{var r;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});let s=await W(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(r=n===null||n===void 0?void 0:n.session)===null||r===void 0?void 0:r.access_token});if(s.error)return s;let{data:o}=s;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:ed(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:td(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(F(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});if(r)return this._returnResult({data:null,error:r});return await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let n={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=t===null||t===void 0?void 0:t.factors)!==null&&e!==void 0?e:[])if(n.all.push(i),i.status==="verified")n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,n,i;if(e)try{let{payload:A}=oi(e),f=null;if(A.aal)f=A.aal;let g=f,{data:{user:m},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});if(((r=(t=m===null||m===void 0?void 0:m.factors)===null||t===void 0?void 0:t.filter((E)=>E.status==="verified"))!==null&&r!==void 0?r:[]).length>0)g="aal2";let y=A.amr||[];return{data:{currentLevel:f,nextLevel:g,currentAuthenticationMethods:y},error:null}}catch(A){if(F(A))return this._returnResult({data:null,error:A});throw A}let{data:{session:s},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:a}=oi(s.access_token),l=null;if(a.aal)l=a.aal;let c=l;if(((i=(n=s.user.factors)===null||n===void 0?void 0:n.filter((A)=>A.status==="verified"))!==null&&i!==void 0?i:[]).length>0)c="aal2";let d=a.amr||[];return{data:{currentLevel:l,nextLevel:c,currentAuthenticationMethods:d},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async(t)=>{let{data:{session:r},error:n}=t;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new nt});return await W(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:(i)=>({data:i,error:null})})})}catch(t){if(F(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async(r)=>{let{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new nt});let s=await W(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:(o)=>({data:o,error:null})});if(s.data&&s.data.redirect_url){if(Ke()&&!(t===null||t===void 0?void 0:t.skipBrowserRedirect))window.location.assign(s.data.redirect_url)}return s})}catch(r){if(F(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async(r)=>{let{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new nt});let s=await W(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:(o)=>({data:o,error:null})});if(s.data&&s.data.redirect_url){if(Ke()&&!(t===null||t===void 0?void 0:t.skipBrowserRedirect))window.location.assign(s.data.redirect_url)}return s})}catch(r){if(F(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async(e)=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new nt});return await W(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:(n)=>({data:n,error:null})})})}catch(e){if(F(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async(t)=>{let{data:{session:r},error:n}=t;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new nt});return await W(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}})}catch(t){if(F(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find((o)=>o.kid===e);if(r)return r;let n=Date.now();if(r=this.jwks.keys.find((o)=>o.kid===e),r&&this.jwks_cached_at+Su>n)return r;let{data:i,error:s}=await W(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(s)throw s;if(!i.keys||i.keys.length===0)return null;if(this.jwks=i,this.jwks_cached_at=n,r=i.keys.find((o)=>o.kid===e),!r)return null;return r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:A,error:f}=await this.getSession();if(f||!A.session)return this._returnResult({data:null,error:f});r=A.session.access_token}let{header:n,payload:i,signature:s,raw:{header:o,payload:a}}=oi(r);if(!(t===null||t===void 0?void 0:t.allowExpired))Uu(i.exp);let l=!n.alg||n.alg.startsWith("HS")||!n.kid||!(("crypto"in globalThis)&&("subtle"in globalThis.crypto))?null:await this.fetchJwk(n.kid,(t===null||t===void 0?void 0:t.keys)?{keys:t.keys}:t===null||t===void 0?void 0:t.jwks);if(!l){let{error:A}=await this.getUser(r);if(A)throw A;return{data:{claims:i,header:n,signature:s},error:null}}let c=Hu(n.alg),u=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!await crypto.subtle.verify(c,u,s,Ou(`${o}.${a}`)))throw new on("Invalid JWT signature");return{data:{claims:i,header:n,signature:s},error:null}}catch(r){if(F(r))return this._returnResult({data:null,error:r});throw r}}}ai.nextInstanceID={};var ea=ai;var Sp=ea,ta=Sp;var Ip="2.103.0",li="";if(typeof Deno<"u")li="deno";else if(typeof document<"u")li="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")li="react-native";else li="node";var kp={"X-Client-Info":`supabase-js-${li}/${Ip}`},Rp={headers:kp},Tp={schema:"public"},Bp={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Op={};function ci(e){return ci=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ci(e)}function Pp(e,t){if(ci(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(ci(n)!="object")return n;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Dp(e){var t=Pp(e,"string");return ci(t)=="symbol"?t:t+""}function Np(e,t,r){return(t=Dp(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function sd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Oe(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?sd(Object(r),!0).forEach(function(n){Np(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):sd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var Mp=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)},Lp=()=>Headers,Fp=(e,t,r)=>{let n=Mp(r),i=Lp();return async(s,o)=>{var a;let l=(a=await t())!==null&&a!==void 0?a:e,c=new i(o===null||o===void 0?void 0:o.headers);if(!c.has("apikey"))c.set("apikey",e);if(!c.has("Authorization"))c.set("Authorization",`Bearer ${l}`);return n(s,Oe(Oe({},o),{},{headers:c}))}};function Gp(e){return e.endsWith("/")?e:e+"/"}function Up(e,t){var r,n;let{db:i,auth:s,realtime:o,global:a}=e,{db:l,auth:c,realtime:u,global:d}=t,A={db:Oe(Oe({},l),i),auth:Oe(Oe({},c),s),realtime:Oe(Oe({},u),o),storage:{},global:Oe(Oe(Oe({},d),a),{},{headers:Oe(Oe({},(r=d===null||d===void 0?void 0:d.headers)!==null&&r!==void 0?r:{}),(n=a===null||a===void 0?void 0:a.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};if(e.accessToken)A.accessToken=e.accessToken;else delete A.accessToken;return A}function Hp(e){let t=e===null||e===void 0?void 0:e.trim();if(!t)throw Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Gp(t))}catch(r){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var jp=class extends ta{constructor(e){super(e)}},Kp=class{constructor(e,t,r){var n,i;this.supabaseUrl=e,this.supabaseKey=t;let s=Hp(e);if(!t)throw 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:Tp,realtime:Op,auth:Oe(Oe({},Bp),{},{storageKey:o}),global:Rp},l=Up(r!==null&&r!==void 0?r:{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},!l.accessToken){var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}else this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});if(this.fetch=Fp(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Oe({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken)Promise.resolve(this.accessToken()).then((u)=>this.realtime.setAuth(u)).catch((u)=>console.warn("Failed to set initial Realtime auth token:",u));if(this.rest=new tu(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 vu(this.storageUrl.href,this.headers,this.fetch,r===null||r===void 0?void 0:r.storage),!l.accessToken)this._listenForAuthEvents()}get functions(){return new Wi(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this,t,r;if(e.accessToken)return await e.accessToken();let{data:n}=await e.auth.getSession();return(t=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&t!==void 0?t:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:s,flowType:o,lock:a,debug:l,throwOnError:c},u,d){let A={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new jp({url:this.authUrl.href,headers:Oe(Oe({},A),u),storageKey:s,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:a,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some((f)=>f.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Zn(this.realtimeUrl.href,Oe(Oe({},e),{},{params:Oe(Oe({},{apikey:this.supabaseKey}),e===null||e===void 0?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t===null||t===void 0?void 0:t.access_token)})}_handleTokenChanged(e,t,r){if((e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r)this.changedAccessToken=r,this.realtime.setAuth(r);else if(e==="SIGNED_OUT"){if(this.realtime.setAuth(),t=="STORAGE")this.auth.signOut();this.changedAccessToken=void 0}}},od=(e,t,r)=>new Kp(e,t,r);function Wp(){if(typeof window<"u")return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(t===void 0||t===null)return!1;let r=t.match(/^v(\d+)\./);if(!r)return!1;return parseInt(r[1],10)<=18}if(Wp())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 qp=300000,ld=16384,cd=4096;function ud(e,t){if(!e)throw Error(`${t} is not configured`);let r;try{r=new URL(e)}catch{throw Error(`${t} is not a valid URL`)}if(r.protocol!=="https:"&&r.protocol!=="http:")throw Error(`${t} must use http or https`);return r.toString()}function dd(e=process.env){let t=ud(e.FLATBLOX_SUPABASE_URL??e.VITE_SUPABASE_URL,"VITE_SUPABASE_URL"),r=e.FLATBLOX_SUPABASE_PUBLISHABLE_KEY??e.VITE_SUPABASE_PUBLISHABLE_KEY;if(!r)throw Error("VITE_SUPABASE_PUBLISHABLE_KEY is not configured");let n=ud(e.FLATBLOX_DASHBOARD_URL??e.VITE_SITE_URL,e.FLATBLOX_DASHBOARD_URL?"FLATBLOX_DASHBOARD_URL":"VITE_SITE_URL"),i=e.FLATBLOX_DASHBOARD_URL?n:new URL("/dashboard/",n).toString(),s=e.XDG_CONFIG_HOME||ad(Xp(),".config");return{supabaseUrl:t,publishableKey:r,dashboardUrl:i,authFile:e.FLATBLOX_TUI_AUTH_FILE??ad(s,"flatblox","tui-auth.json")}}function e0(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.accessToken==="string"&&t.accessToken.length>0&&t.accessToken.length<=ld&&typeof t.refreshToken==="string"&&t.refreshToken.length>0&&t.refreshToken.length<=ld}async function t0(e){try{let t=JSON.parse(await Jp(e,"utf8"));if(!e0(t))return null;return{accessToken:t.accessToken,refreshToken:t.refreshToken}}catch(t){if(t.code==="ENOENT"||t instanceof SyntaxError)return null;throw t}}async function ys(e,t){await Qp(zp(e),{recursive:!0,mode:448});let r=`${e}.${process.pid}.tmp`;await Zp(r,`${JSON.stringify({accessToken:t.access_token,refreshToken:t.refresh_token})}
61
- `,{mode:384}),await Vp(r,e),await Yp(e,384)}async function Or(e){try{await $p(e)}catch(t){if(t.code!=="ENOENT")throw t}}function hd(e){return od(e.supabaseUrl,e.publishableKey,{auth:{autoRefreshToken:!0,detectSessionInUrl:!1,persistSession:!1}})}async function Ad(e,t){let r=await t0(t);if(!r)return null;let{data:n,error:i}=await e.auth.setSession({access_token:r.accessToken,refresh_token:r.refreshToken});if(i||!n.session)return await Or(t),null;return await ys(t,n.session),n.session}function r0(e,t=process.platform){if(t==="darwin")return["open",e];if(t==="win32")return["rundll32.exe","url.dll,FileProtocolHandler",e];return["xdg-open",e]}function n0(e){try{return Bun.spawn(r0(e),{stdout:"ignore",stderr:"ignore"}).unref(),!0}catch{return!1}}function i0(e){let r=`<!doctype html>
53
+ Issued At: ${s.toISOString()}`;if(i)w+=`
54
+ Expiration Time: ${i.toISOString()}`;if(a)w+=`
55
+ Not Before: ${a.toISOString()}`;if(l)w+=`
56
+ Request ID: ${l}`;if(c){let p=`
57
+ Resources:`;for(let C of c){if(!C||typeof C!=="string")throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${C}`);p+=`
58
+ - ${C}`}w+=p}return`${b}
59
+ ${w}`}class Re extends Error{constructor({message:e,code:t,cause:r,name:n}){var i;super(e,{cause:r});this.__isWebAuthnError=!0,this.name=(i=n!==null&&n!==void 0?n:r instanceof Error?r.name:void 0)!==null&&i!==void 0?i:"Unknown Error",this.code=t}}class dn extends Re{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e});this.name="WebAuthnUnknownError",this.originalError=t}}function cd({error:e,options:t}){var r,n,i;let{publicKey:s}=t;if(!s)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new Re({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.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:e});else if(t.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:e});else 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:e})}else if(e.name==="InvalidStateError")return new Re({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});else if(e.name==="NotAllowedError")return new Re({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if(e.name==="NotSupportedError"){if(s.pubKeyCredParams.filter((a)=>a.type==="public-key").length===0)return new Re({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e});return new Re({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}else if(e.name==="SecurityError"){let o=window.location.hostname;if(!fa(o))return new Re({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});else 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:e})}else if(e.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:e})}else if(e.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:e});return new Re({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function ud({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new Re({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="NotAllowedError")return new Re({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if(e.name==="SecurityError"){let n=window.location.hostname;if(!fa(n))return new Re({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});else if(r.rpId!==n)return new Re({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if(e.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:e});return new Re({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class hd{createNewAbortSignal(){if(this.controller){let t=Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}var Vp=new hd;function fd(e){if(!e)throw Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON==="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:n}=e,i=Er(e,["challenge","user","excludeCredentials"]),s=gr(t).buffer,o=Object.assign(Object.assign({},r),{id:gr(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:s,user:o});if(n&&n.length>0){a.excludeCredentials=Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:gr(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function Ad(e){if(!e)throw Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON==="function")return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,n=Er(e,["challenge","allowCredentials"]),i=gr(t).buffer,s=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){s.allowCredentials=Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];s.allowCredentials[o]=Object.assign(Object.assign({},a),{id:gr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function gd(e){var t;if("toJSON"in e&&typeof e.toJSON==="function")return e.toJSON();let r=e;return{id:e.id,rawId:e.id,response:{attestationObject:zt(new Uint8Array(e.response.attestationObject)),clientDataJSON:zt(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:(t=r.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function md(e){var t;if("toJSON"in e&&typeof e.toJSON==="function")return e.toJSON();let r=e,n=e.getClientExtensionResults(),i=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:zt(new Uint8Array(i.authenticatorData)),clientDataJSON:zt(new Uint8Array(i.clientDataJSON)),signature:zt(new Uint8Array(i.signature)),userHandle:i.userHandle?zt(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(t=r.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function fa(e){return e==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function dd(){var e,t;return!!(Qe()&&("PublicKeyCredential"in window)&&window.PublicKeyCredential&&("credentials"in navigator)&&typeof((e=navigator===null||navigator===void 0?void 0:navigator.credentials)===null||e===void 0?void 0:e.create)==="function"&&typeof((t=navigator===null||navigator===void 0?void 0:navigator.credentials)===null||t===void 0?void 0:t.get)==="function")}async function Zp(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new dn("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new dn("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:cd({error:t,options:e})}}}async function $p(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new dn("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new dn("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:ud({error:t,options:e})}}}var Xp={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},zp={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ds(...e){let t=(i)=>i!==null&&typeof i==="object"&&!Array.isArray(i),r=(i)=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(let i of e){if(!i)continue;for(let s in i){let o=i[s];if(o===void 0)continue;if(Array.isArray(o))n[s]=o;else if(r(o))n[s]=o;else if(t(o)){let a=n[s];if(t(a))n[s]=Ds(a,o);else n[s]=Ds(o)}else n[s]=o}}return n}function qp(e,t){return Ds(Xp,e,t||{})}function e0(e,t){return Ds(zp,e,t||{})}class Aa{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:n},i){var s;try{let{data:o,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!o)return{data:null,error:a};let l=n!==null&&n!==void 0?n:Vp.createNewAbortSignal();if(o.webauthn.type==="create"){let{user:c}=o.webauthn.credential_options.publicKey;if(!c.name){let u=r;if(!u){let f=(await this.client.getUser()).data.user,g=((s=f===null||f===void 0?void 0:f.user_metadata)===null||s===void 0?void 0:s.name)||(f===null||f===void 0?void 0:f.email)||(f===null||f===void 0?void 0:f.id)||"User";c.name=`${c.id}:${g}`}else c.name=`${c.id}:${u}`}if(!c.displayName)c.displayName=c.name}switch(o.webauthn.type){case"create":{let c=qp(o.webauthn.credential_options.publicKey,i===null||i===void 0?void 0:i.create),{data:u,error:d}=await Zp({publicKey:c,signal:l});if(u)return{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null};return{data:null,error:d}}case"request":{let c=e0(o.webauthn.credential_options.publicKey,i===null||i===void 0?void 0:i.request),{data:u,error:d}=await $p(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:c,signal:l}));if(u)return{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null};return{data:null,error:d}}}}catch(o){if(G(o))return{data:null,error:o};return{data:null,error:new It("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return{data:null,error:new Rr("rpId is required for WebAuthn authentication")};try{if(!dd())return{data:null,error:new It("Browser does not support WebAuthn",null)};let{data:s,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:n},{request:i});if(!s)return{data:null,error:o};let{webauthn:a}=s;return this._verify({factorId:e,challengeId:s.challengeId,webauthn:{type:a.type,rpId:t,rpOrigins:r,credential_response:a.credential_response}})}catch(s){if(G(s))return{data:null,error:s};return{data:null,error:new It("Unexpected error in authenticate",s)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return{data:null,error:new Rr("rpId is required for WebAuthn registration")};try{if(!dd())return{data:null,error:new It("Browser does not support WebAuthn",null)};let{data:s,error:o}=await this._enroll({friendlyName:e});if(!s)return await this.client.mfa.listFactors().then((c)=>{var u;return(u=c.data)===null||u===void 0?void 0:u.all.find((d)=>d.factor_type==="webauthn"&&d.friendly_name===e&&d.status!=="unverified")}).then((c)=>c?this.client.mfa.unenroll({factorId:c===null||c===void 0?void 0:c.id}):void 0),{data:null,error:o};let{data:a,error:l}=await this._challenge({factorId:s.id,friendlyName:s.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:n},{create:i});if(!a)return{data:null,error:l};return this._verify({factorId:s.id,challengeId:a.challengeId,webauthn:{rpId:t,rpOrigins:r,type:a.webauthn.type,credential_response:a.webauthn.credential_response}})}catch(s){if(G(s))return{data:null,error:s};return{data:null,error:new It("Unexpected error in register",s)}}}}sd();var t0={url:Mu,storageKey:Nu,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Lu,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5000,skipAutoInitialize:!1};async function pd(e,t,r){return await r()}var hn={};class ci{get jwks(){var e,t;return(t=(e=hn[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){hn[this.storageKey]=Object.assign(Object.assign({},hn[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=hn[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){hn[this.storageKey]=Object.assign(Object.assign({},hn[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},t0),e);if(this.storageKey=i.storageKey,this.instanceID=(t=ci.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,ci.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug==="function")this.logger=i.debug;if(this.instanceID>0&&Qe()){let s=`${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.`;if(console.warn(s),this.logDebugMessages)console.trace(s)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new un({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Rs(i.fetch),this.lock=i.lock||pd,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock)this.lock=i.lock;else if(this.persistSession&&Qe()&&((r=globalThis===null||globalThis===void 0?void 0:globalThis.navigator)===null||r===void 0?void 0:r.locks))this.lock=da;else this.lock=pd;if(!this.jwks)this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER;if(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 Aa(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){if(i.storage)this.storage=i.storage;else if(ks())this.storage=globalThis.localStorage;else this.memoryStorage={},this.storage=ua(this.memoryStorage);if(i.userStorage)this.userStorage=i.userStorage}else this.memoryStorage={},this.storage=ua(this.memoryStorage);if(Qe()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(s){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",s)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async(s)=>{this._debug("received broadcast notification from other tab or client",s);try{await this._notifyAllSubscribers(s.data.event,s.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}if(!i.skipAutoInitialize)this.initialize().catch((s)=>{this._debug("#initialize()","error",s)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${vs}) ${new Date().toISOString()}`}_debug(...e){if(this.logDebugMessages)this.logger(this._logPrefix(),...e);return this}async initialize(){if(this.initializePromise)return await this.initializePromise;return this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(Qe()){if(t=Vu(window.location.href),this._isImplicitGrantCallback(t))r="implicit";else if(await this._isPKCECallback(t))r="pkce"}if(Qe()&&this.detectSessionInUrl&&r!=="none"){let{data:n,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Hu(i)){let a=(e=i.details)===null||e===void 0?void 0:e.code;if(a==="identity_already_exists"||a==="identity_not_found"||a==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:s,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",s,"redirect type",o),await this._saveSession(s),setTimeout(async()=>{if(o==="recovery")await this._notifyAllSubscribers("PASSWORD_RECOVERY",s);else await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){if(G(t))return this._returnResult({error:t});return this._returnResult({error:new It("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,n;try{let i=await V(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e===null||e===void 0?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(n=e===null||e===void 0?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}},xform:Ct}),{data:s,error:o}=i;if(o||!s)return this._returnResult({data:{user:null,session:null},error:o});let{session:a,user:l}=s;if(s.session)await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",a);return this._returnResult({data:{user:l,session:a},error:null})}catch(i){if(G(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,n;try{let i;if("email"in e){let{email:c,password:u,options:d}=e,f=null,g=null;if(this.flowType==="pkce")[f,g]=await Br(this.storage,this.storageKey);i=await V(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d===null||d===void 0?void 0:d.emailRedirectTo,body:{email:c,password:u,data:(t=d===null||d===void 0?void 0:d.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d===null||d===void 0?void 0:d.captchaToken},code_challenge:f,code_challenge_method:g},xform:Ct})}else if("phone"in e){let{phone:c,password:u,options:d}=e;i=await V(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:u,data:(r=d===null||d===void 0?void 0:d.data)!==null&&r!==void 0?r:{},channel:(n=d===null||d===void 0?void 0:d.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:d===null||d===void 0?void 0:d.captchaToken}},xform:Ct})}else throw new an("You must provide either an email or phone number and a password");let{data:s,error:o}=i;if(o||!s)return await Xe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});let{session:a,user:l}=s;if(s.session)await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",a);return this._returnResult({data:{user:l,session:a},error:null})}catch(i){if(await Xe(this.storage,`${this.storageKey}-code-verifier`),G(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:s,options:o}=e;t=await V(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:s,gotrue_meta_security:{captcha_token:o===null||o===void 0?void 0:o.captchaToken}},xform:la})}else if("phone"in e){let{phone:i,password:s,options:o}=e;t=await V(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:s,gotrue_meta_security:{captcha_token:o===null||o===void 0?void 0:o.captchaToken}},xform:la})}else throw new an("You must provide either an email or phone number and a password");let{data:r,error:n}=t;if(n)return this._returnResult({data:{user:null,session:null},error:n});else if(!r||!r.session||!r.user){let i=new Ar;return this._returnResult({data:{user:null,session:null},error:i})}if(r.session)await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session);return this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:n})}catch(t){if(G(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,n,i,s,o,a,l,c,u,d;let f,g;if("message"in e)f=e.message,g=e.signature;else{let{chain:A,wallet:m,statement:b,options:w}=e,p;if(!Qe()){if(typeof m!=="object"||!(w===null||w===void 0?void 0:w.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");p=m}else if(typeof m==="object")p=m;else{let B=window;if("ethereum"in B&&typeof B.ethereum==="object"&&"request"in B.ethereum&&typeof B.ethereum.request==="function")p=B.ethereum;else throw 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.")}let C=new URL((t=w===null||w===void 0?void 0:w.url)!==null&&t!==void 0?t:window.location.href),_=await p.request({method:"eth_requestAccounts"}).then((B)=>B).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!_||_.length===0)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let y=ha(_[0]),v=(r=w===null||w===void 0?void 0:w.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!v){let B=await p.request({method:"eth_chainId"});v=od(B)}let x={domain:C.host,address:y,statement:b,uri:C.href,version:"1",chainId:v,nonce:(n=w===null||w===void 0?void 0:w.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(s=(i=w===null||w===void 0?void 0:w.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&s!==void 0?s:new Date,expirationTime:(o=w===null||w===void 0?void 0:w.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(a=w===null||w===void 0?void 0:w.signInWithEthereum)===null||a===void 0?void 0:a.notBefore,requestId:(l=w===null||w===void 0?void 0:w.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(c=w===null||w===void 0?void 0:w.signInWithEthereum)===null||c===void 0?void 0:c.resources};f=ld(x),g=await p.request({method:"personal_sign",params:[ad(f),y]})}try{let{data:A,error:m}=await V(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:g},((u=e.options)===null||u===void 0?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:(d=e.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:Ct});if(m)throw m;if(!A||!A.session||!A.user){let b=new Ar;return this._returnResult({data:{user:null,session:null},error:b})}if(A.session)await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session);return this._returnResult({data:Object.assign({},A),error:m})}catch(A){if(G(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async signInWithSolana(e){var t,r,n,i,s,o,a,l,c,u,d,f;let g,A;if("message"in e)g=e.message,A=e.signature;else{let{chain:m,wallet:b,statement:w,options:p}=e,C;if(!Qe()){if(typeof b!=="object"||!(p===null||p===void 0?void 0:p.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");C=b}else if(typeof b==="object")C=b;else{let y=window;if("solana"in y&&typeof y.solana==="object"&&(("signIn"in y.solana)&&typeof y.solana.signIn==="function"||("signMessage"in y.solana)&&typeof y.solana.signMessage==="function"))C=y.solana;else throw 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.")}let _=new URL((t=p===null||p===void 0?void 0:p.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in C&&C.signIn){let y=await C.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},p===null||p===void 0?void 0:p.signInWithSolana),{version:"1",domain:_.host,uri:_.href}),w?{statement:w}:null)),v;if(Array.isArray(y)&&y[0]&&typeof y[0]==="object")v=y[0];else if(y&&typeof y==="object"&&"signedMessage"in y&&"signature"in y)v=y;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in v&&"signature"in v&&(typeof v.signedMessage==="string"||v.signedMessage instanceof Uint8Array)&&v.signature instanceof Uint8Array)g=typeof v.signedMessage==="string"?v.signedMessage:new TextDecoder().decode(v.signedMessage),A=v.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in C)||typeof C.signMessage!=="function"||!("publicKey"in C)||typeof C!=="object"||!C.publicKey||!("toBase58"in C.publicKey)||typeof C.publicKey.toBase58!=="function")throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${_.host} wants you to sign in with your Solana account:`,C.publicKey.toBase58(),...w?["",w,""]:[""],"Version: 1",`URI: ${_.href}`,`Issued At: ${(n=(r=p===null||p===void 0?void 0:p.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...((i=p===null||p===void 0?void 0:p.signInWithSolana)===null||i===void 0?void 0:i.notBefore)?[`Not Before: ${p.signInWithSolana.notBefore}`]:[],...((s=p===null||p===void 0?void 0:p.signInWithSolana)===null||s===void 0?void 0:s.expirationTime)?[`Expiration Time: ${p.signInWithSolana.expirationTime}`]:[],...((o=p===null||p===void 0?void 0:p.signInWithSolana)===null||o===void 0?void 0:o.chainId)?[`Chain ID: ${p.signInWithSolana.chainId}`]:[],...((a=p===null||p===void 0?void 0:p.signInWithSolana)===null||a===void 0?void 0:a.nonce)?[`Nonce: ${p.signInWithSolana.nonce}`]:[],...((l=p===null||p===void 0?void 0:p.signInWithSolana)===null||l===void 0?void 0:l.requestId)?[`Request ID: ${p.signInWithSolana.requestId}`]:[],...((u=(c=p===null||p===void 0?void 0:p.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||u===void 0?void 0:u.length)?["Resources",...p.signInWithSolana.resources.map((v)=>`- ${v}`)]:[]].join(`
60
+ `);let y=await C.signMessage(new TextEncoder().encode(g),"utf8");if(!y||!(y instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");A=y}}try{let{data:m,error:b}=await V(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:zt(A)},((d=e.options)===null||d===void 0?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:Ct});if(b)throw b;if(!m||!m.session||!m.user){let w=new Ar;return this._returnResult({data:{user:null,session:null},error:w})}if(m.session)await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session);return this._returnResult({data:Object.assign({},m),error:b})}catch(m){if(G(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e){let t=await mr(this.storage,`${this.storageKey}-code-verifier`),[r,n]=(t!==null&&t!==void 0?t:"").split("/");try{if(!r&&this.flowType==="pkce")throw new sa;let{data:i,error:s}=await V(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:Ct});if(await Xe(this.storage,`${this.storageKey}-code-verifier`),s)throw s;if(!i||!i.session||!i.user){let o=new Ar;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}if(i.session)await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session);return this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n!==null&&n!==void 0?n:null}),error:s})}catch(i){if(await Xe(this.storage,`${this.storageKey}-code-verifier`),G(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:t,provider:r,token:n,access_token:i,nonce:s}=e,o=await V(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:n,access_token:i,nonce:s,gotrue_meta_security:{captcha_token:t===null||t===void 0?void 0:t.captchaToken}},xform:Ct}),{data:a,error:l}=o;if(l)return this._returnResult({data:{user:null,session:null},error:l});else if(!a||!a.session||!a.user){let c=new Ar;return this._returnResult({data:{user:null,session:null},error:c})}if(a.session)await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session);return this._returnResult({data:a,error:l})}catch(t){if(G(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,n,i,s;try{if("email"in e){let{email:o,options:a}=e,l=null,c=null;if(this.flowType==="pkce")[l,c]=await Br(this.storage,this.storageKey);let{error:u}=await V(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(t=a===null||a===void 0?void 0:a.data)!==null&&t!==void 0?t:{},create_user:(r=a===null||a===void 0?void 0:a.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:a===null||a===void 0?void 0:a.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:a===null||a===void 0?void 0:a.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:u})}if("phone"in e){let{phone:o,options:a}=e,{data:l,error:c}=await V(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=a===null||a===void 0?void 0:a.data)!==null&&n!==void 0?n:{},create_user:(i=a===null||a===void 0?void 0:a.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:a===null||a===void 0?void 0:a.captchaToken},channel:(s=a===null||a===void 0?void 0:a.channel)!==null&&s!==void 0?s:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:l===null||l===void 0?void 0:l.message_id},error:c})}throw new an("You must provide either an email or phone number.")}catch(o){if(await Xe(this.storage,`${this.storageKey}-code-verifier`),G(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var t,r;try{let n=void 0,i=void 0;if("options"in e)n=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken;let{data:s,error:o}=await V(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Ct});if(o)throw o;if(!s)throw Error("An error occurred on token verification.");let{session:a,user:l}=s;if(a===null||a===void 0?void 0:a.access_token)await this._saveSession(a),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a);return this._returnResult({data:{user:l,session:a},error:null})}catch(n){if(G(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var t,r,n,i,s;try{let o=null,a=null;if(this.flowType==="pkce")[o,a]=await Br(this.storage,this.storageKey);let l=await V(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:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),((n=e===null||e===void 0?void 0:e.options)===null||n===void 0?void 0:n.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:a}),headers:this.headers,xform:nd});if(((i=l.data)===null||i===void 0?void 0:i.url)&&Qe()&&!((s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect))window.location.assign(l.data.url);return this._returnResult(l)}catch(o){if(await Xe(this.storage,`${this.storageKey}-code-verifier`),G(o))return this._returnResult({data:null,error:o});throw o}}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:t},error:r}=e;if(r)throw r;if(!t)throw new at;let{error:n}=await V(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(G(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:n,options:i}=e,{error:s}=await V(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:n,gotrue_meta_security:{captcha_token:i===null||i===void 0?void 0:i.captchaToken}},redirectTo:i===null||i===void 0?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:s})}else if("phone"in e){let{phone:r,type:n,options:i}=e,{data:s,error:o}=await V(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:n,gotrue_meta_security:{captcha_token:i===null||i===void 0?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:s===null||s===void 0?void 0:s.message_id},error:o})}throw new an("You must provide either an email or phone number and a type")}catch(t){if(G(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async(t)=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch(i){}})()),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 r=t();this.pendingInLock.push((async()=>{try{await r}catch(n){}})()),await r;while(this.pendingInLock.length){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await r}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 t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){if(this._debug("#__loadSession()","begin"),!this.lockAcquired)this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let e=null,t=await mr(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null)if(this._isValidSession(t))e=t;else this._debug("#getSession()","session from storage is not valid"),await this._removeSession();if(!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1000-Date.now()<Cs:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){let s=await mr(this.userStorage,this.storageKey+"-user");if(s===null||s===void 0?void 0:s.user)e.user=s.user;else e.user=Ts()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let s={value:this.suppressGetSessionWarning};if(e.user=td(e.user,s),s.value)this.suppressGetSessionWarning=!0}return{data:{session:e},error:null}}let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i)return this._returnResult({data:{session:null},error:i});return 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 t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());if(t.data.user)this.suppressGetSessionWarning=!0;return t}async _getUser(e){try{if(e)return await V(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ht});return await this._useSession(async(t)=>{var r,n,i;let{data:s,error:o}=t;if(o)throw o;if(!((r=s.session)===null||r===void 0?void 0:r.access_token)&&!this.hasCustomAuthorizationHeader)return{data:{user:null},error:new at};return await V(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:Ht})})}catch(t){if(G(t)){if(si(t))await this._removeSession(),await Xe(this.storage,`${this.storageKey}-code-verifier`);return this._returnResult({data:{user:null},error:t})}throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async(r)=>{let{data:n,error:i}=r;if(i)throw i;if(!n.session)throw new at;let s=n.session,o=null,a=null;if(this.flowType==="pkce"&&e.email!=null)[o,a]=await Br(this.storage,this.storageKey);let{data:l,error:c}=await V(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t===null||t===void 0?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:s.access_token,xform:Ht});if(c)throw c;return s.user=l.user,await this._saveSession(s),await this._notifyAllSubscribers("USER_UPDATED",s),this._returnResult({data:{user:s.user},error:null})})}catch(r){if(await Xe(this.storage,`${this.storageKey}-code-verifier`),G(r))return this._returnResult({data:{user:null},error:r});throw r}}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 at;let t=Date.now()/1000,r=t,n=!0,i=null,{payload:s}=li(e.access_token);if(s.exp)r=s.exp,n=r<=t;if(n){let{data:o,error:a}=await this._callRefreshToken(e.refresh_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});if(!o)return{data:{user:null,session:null},error:null};i=o}else{let{data:o,error:a}=await this._getUser(e.access_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});i={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(G(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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(t)=>{var r;if(!e){let{data:s,error:o}=t;if(o)throw o;e=(r=s.session)!==null&&r!==void 0?r:void 0}if(!(e===null||e===void 0?void 0:e.refresh_token))throw new at;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n)return this._returnResult({data:{user:null,session:null},error:null});return this._returnResult({data:{user:n.user,session:n},error:null})})}catch(t){if(G(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!Qe())throw new ln("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ln(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new xs("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ln("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new xs("No code detected.");let{data:w,error:p}=await this._exchangeCodeForSession(e.code);if(p)throw p;let C=new URL(window.location.href);return C.searchParams.delete("code"),window.history.replaceState(window.history.state,"",C.toString()),{data:{session:w.session,redirectType:null},error:null}}let{provider_token:r,provider_refresh_token:n,access_token:i,refresh_token:s,expires_in:o,expires_at:a,token_type:l}=e;if(!i||!o||!s||!l)throw new ln("No session defined in URL");let c=Math.round(Date.now()/1000),u=parseInt(o),d=c+u;if(a)d=parseInt(a);let f=d-c;if(f*1000<=kr)console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let g=d-u;if(c-g>=120)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,c);else if(c-g<0)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,d,c);let{data:A,error:m}=await this._getUser(i);if(m)throw m;let b={provider_token:r,provider_refresh_token:n,access_token:i,expires_in:u,expires_at:d,refresh_token:s,token_type:l,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(r){if(G(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(e){if(typeof this.detectSessionInUrl==="function")return this.detectSessionInUrl(new URL(window.location.href),e);return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await mr(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}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(t)=>{var r;let{data:n,error:i}=t;if(i&&!si(i))return this._returnResult({error:i});let s=(r=n.session)===null||r===void 0?void 0:r.access_token;if(s){let{error:o}=await this.admin.signOut(s,e);if(o){if(!(Uu(o)&&(o.status===404||o.status===401||o.status===403)||si(o)))return this._returnResult({error:o})}}if(e!=="others")await this._removeSession(),await Xe(this.storage,`${this.storageKey}-code-verifier`);return this._returnResult({error:null})})}onAuthStateChange(e){let t=Ju(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async(t)=>{var r,n;try{let{data:{session:i},error:s}=t;if(s)throw s;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),si(i))console.warn(i);else console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,n=null;if(this.flowType==="pkce")[r,n]=await Br(this.storage,this.storageKey,!0);try{return await V(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(await Xe(this.storage,`${this.storageKey}-code-verifier`),G(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(G(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){if("token"in e)return this.linkIdentityIdToken(e);return this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:r,error:n}=await this._useSession(async(i)=>{var s,o,a,l,c;let{data:u,error:d}=i;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(s=e.options)===null||s===void 0?void 0:s.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(a=e.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:!0});return await V(this.fetch,"GET",f,{headers:this.headers,jwt:(c=(l=u.session)===null||l===void 0?void 0:l.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;if(Qe()&&!((t=e.options)===null||t===void 0?void 0:t.skipBrowserRedirect))window.location.assign(r===null||r===void 0?void 0:r.url);return this._returnResult({data:{provider:e.provider,url:r===null||r===void 0?void 0:r.url},error:null})}catch(r){if(G(r))return this._returnResult({data:{provider:e.provider,url:null},error:r});throw r}}async linkIdentityIdToken(e){return await this._useSession(async(t)=>{var r;try{let{error:n,data:{session:i}}=t;if(n)throw n;let{options:s,provider:o,token:a,access_token:l,nonce:c}=e,u=await V(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i===null||i===void 0?void 0:i.access_token)!==null&&r!==void 0?r:void 0,body:{provider:o,id_token:a,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:s===null||s===void 0?void 0:s.captchaToken}},xform:Ct}),{data:d,error:f}=u;if(f)return this._returnResult({data:{user:null,session:null},error:f});else if(!d||!d.session||!d.user)return this._returnResult({data:{user:null,session:null},error:new Ar});if(d.session)await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session);return this._returnResult({data:d,error:f})}catch(n){if(await Xe(this.storage,`${this.storageKey}-code-verifier`),G(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async(t)=>{var r,n;let{data:i,error:s}=t;if(s)throw s;return await V(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0})})}catch(t){if(G(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await Xu(async(n)=>{if(n>0)await $u(200*Math.pow(2,n-1));return this._debug(t,"refreshing attempt",n),await V(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ct})},(n,i)=>{let s=200*Math.pow(2,n);return i&&Es(i)&&Date.now()+s-r<kr})}catch(r){if(this._debug(t,"error",r),G(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e==="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});if(this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Qe()&&!t.skipBrowserRedirect)window.location.assign(r);return{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;let r="#_recoverAndRefresh()";this._debug("#_recoverAndRefresh()","begin");try{let n=await mr(this.storage,this.storageKey);if(n&&this.userStorage){let s=await mr(this.userStorage,this.storageKey+"-user");if(!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!s)s={user:n.user},await Or(this.userStorage,this.storageKey+"-user",s);n.user=(e=s===null||s===void 0?void 0:s.user)!==null&&e!==void 0?e:Ts()}else if(n&&!n.user){if(!n.user){let s=await mr(this.storage,this.storageKey+"-user");if(s&&(s===null||s===void 0?void 0:s.user))n.user=s.user,await Xe(this.storage,this.storageKey+"-user"),await Or(this.storage,this.storageKey,n);else n.user=Ts()}}if(this._debug("#_recoverAndRefresh()","session from storage",n),!this._isValidSession(n)){if(this._debug("#_recoverAndRefresh()","session is not valid"),n!==null)await this._removeSession();return}let i=((t=n.expires_at)!==null&&t!==void 0?t:1/0)*1000-Date.now()<Cs;if(this._debug("#_recoverAndRefresh()",`session has${i?"":" not"} expired with margin of ${Cs}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:s}=await this._callRefreshToken(n.refresh_token);if(s){if(console.error(s),!Es(s))this._debug("#_recoverAndRefresh()","refresh failed with a non-retryable error, removing the session",s),await this._removeSession()}}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:s,error:o}=await this._getUser(n.access_token);if(!o&&(s===null||s===void 0?void 0:s.user))n.user=s.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n);else this._debug("#_recoverAndRefresh()","could not get user data, skipping SIGNED_IN notification")}catch(s){console.error("Error getting user data:",s),this._debug("#_recoverAndRefresh()","error getting user data, skipping SIGNED_IN notification",s)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug("#_recoverAndRefresh()","error",n),console.error(n);return}finally{this._debug("#_recoverAndRefresh()","end")}}async _callRefreshToken(e){var t,r;if(!e)throw new at;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new ai;let{data:i,error:s}=await this._refreshAccessToken(e);if(s)throw s;if(!i.session)throw new at;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let o={data:i.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(i){if(this._debug(n,"error",i),G(i)){let s={data:null,error:i};if(!Es(i))await this._removeSession();return(t=this.refreshingDeferred)===null||t===void 0||t.resolve(s),s}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,r=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${r}`);try{if(this.broadcastChannel&&r)this.broadcastChannel.postMessage({event:e,session:t});let i=[],s=Array.from(this.stateChangeEmitters.values()).map(async(o)=>{try{await o.callback(e,t)}catch(a){i.push(a)}});if(await Promise.all(s),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Xe(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),r=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){if(!r&&t.user)await Or(this.userStorage,this.storageKey+"-user",{user:t.user});let n=Object.assign({},t);delete n.user;let i=aa(n);await Or(this.storage,this.storageKey,i)}else{let n=aa(t);await Or(this.storage,this.storageKey,n)}}async _removeSession(){if(this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Xe(this.storage,this.storageKey),await Xe(this.storage,this.storageKey+"-code-verifier"),await Xe(this.storage,this.storageKey+"-user"),this.userStorage)await Xe(this.userStorage,this.storageKey+"-user");await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{if(e&&Qe()&&(window===null||window===void 0?void 0:window.removeEventListener))window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),kr);if(this.autoRefreshTicker=e,e&&typeof e==="object"&&typeof e.unref==="function")e.unref();else if(typeof Deno<"u"&&typeof Deno.unrefTimer==="function")Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);if(this.autoRefreshTickTimeout=t,t&&typeof t==="object"&&typeof t.unref==="function")t.unref();else if(typeof Deno<"u"&&typeof Deno.unrefTimer==="function")Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;if(this.autoRefreshTicker=null,e)clearInterval(e);let t=this.autoRefreshTickTimeout;if(this.autoRefreshTickTimeout=null,t)clearTimeout(t)}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(t)=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((r.expires_at*1000-e)/kr);if(this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${kr}ms, refresh threshold is ${_s} ticks`),n<=_s)await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ps)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Qe()||!(window===null||window===void 0?void 0:window.addEventListener)){if(this.autoRefreshToken)this.startAutoRefresh();return!1}try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window===null||window===void 0||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken)this._startAutoRefresh();if(!e)await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()})}else if(document.visibilityState==="hidden"){if(this.autoRefreshToken)this._stopAutoRefresh()}}async _getUrlForProvider(e,t,r){let n=[`provider=${encodeURIComponent(t)}`];if(r===null||r===void 0?void 0:r.redirectTo)n.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`);if(r===null||r===void 0?void 0:r.scopes)n.push(`scopes=${encodeURIComponent(r.scopes)}`);if(this.flowType==="pkce"){let[i,s]=await Br(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(s)}`});n.push(o.toString())}if(r===null||r===void 0?void 0:r.queryParams){let i=new URLSearchParams(r.queryParams);n.push(i.toString())}if(r===null||r===void 0?void 0:r.skipBrowserRedirect)n.push(`skip_http_redirect=${r.skipBrowserRedirect}`);return`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async(t)=>{var r;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});return await V(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=n===null||n===void 0?void 0:n.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(G(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async(t)=>{var r,n;let{data:i,error:s}=t;if(s)return this._returnResult({data:null,error:s});let o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:a,error:l}=await V(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(r=i===null||i===void 0?void 0:i.session)===null||r===void 0?void 0:r.access_token});if(l)return this._returnResult({data:null,error:l});if(e.factorType==="totp"&&a.type==="totp"&&((n=a===null||a===void 0?void 0:a.totp)===null||n===void 0?void 0:n.qr_code))a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`;return this._returnResult({data:a,error:null})})}catch(t){if(G(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async(t)=>{var r;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});let s=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?gd(e.webauthn.credential_response):md(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await V(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:s,headers:this.headers,jwt:(r=n===null||n===void 0?void 0:n.session)===null||r===void 0?void 0:r.access_token});if(a)return this._returnResult({data:null,error:a});return await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1000)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:a})})}catch(t){if(G(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async(t)=>{var r;let{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});let s=await V(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(r=n===null||n===void 0?void 0:n.session)===null||r===void 0?void 0:r.access_token});if(s.error)return s;let{data:o}=s;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:fd(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Ad(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(G(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});if(r)return this._returnResult({data:null,error:r});return await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let n={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=t===null||t===void 0?void 0:t.factors)!==null&&e!==void 0?e:[])if(n.all.push(i),i.status==="verified")n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,n,i;if(e)try{let{payload:f}=li(e),g=null;if(f.aal)g=f.aal;let A=g,{data:{user:m},error:b}=await this.getUser(e);if(b)return this._returnResult({data:null,error:b});if(((r=(t=m===null||m===void 0?void 0:m.factors)===null||t===void 0?void 0:t.filter((C)=>C.status==="verified"))!==null&&r!==void 0?r:[]).length>0)A="aal2";let p=f.amr||[];return{data:{currentLevel:g,nextLevel:A,currentAuthenticationMethods:p},error:null}}catch(f){if(G(f))return this._returnResult({data:null,error:f});throw f}let{data:{session:s},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:a}=li(s.access_token),l=null;if(a.aal)l=a.aal;let c=l;if(((i=(n=s.user.factors)===null||n===void 0?void 0:n.filter((f)=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0)c="aal2";let d=a.amr||[];return{data:{currentLevel:l,nextLevel:c,currentAuthenticationMethods:d},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async(t)=>{let{data:{session:r},error:n}=t;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new at});return await V(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:(i)=>({data:i,error:null})})})}catch(t){if(G(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async(r)=>{let{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new at});let s=await V(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:(o)=>({data:o,error:null})});if(s.data&&s.data.redirect_url){if(Qe()&&!(t===null||t===void 0?void 0:t.skipBrowserRedirect))window.location.assign(s.data.redirect_url)}return s})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async(r)=>{let{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new at});let s=await V(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:(o)=>({data:o,error:null})});if(s.data&&s.data.redirect_url){if(Qe()&&!(t===null||t===void 0?void 0:t.skipBrowserRedirect))window.location.assign(s.data.redirect_url)}return s})}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async(e)=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new at});return await V(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:(n)=>({data:n,error:null})})})}catch(e){if(G(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async(t)=>{let{data:{session:r},error:n}=t;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new at});return await V(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}})}catch(t){if(G(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find((o)=>o.kid===e);if(r)return r;let n=Date.now();if(r=this.jwks.keys.find((o)=>o.kid===e),r&&this.jwks_cached_at+Gu>n)return r;let{data:i,error:s}=await V(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(s)throw s;if(!i.keys||i.keys.length===0)return null;if(this.jwks=i,this.jwks_cached_at=n,r=i.keys.find((o)=>o.kid===e),!r)return null;return r}async getClaims(e,t={}){try{let r=e;if(!r){let{data:f,error:g}=await this.getSession();if(g||!f.session)return this._returnResult({data:null,error:g});r=f.session.access_token}let{header:n,payload:i,signature:s,raw:{header:o,payload:a}}=li(r);if(!(t===null||t===void 0?void 0:t.allowExpired))qu(i.exp);let l=!n.alg||n.alg.startsWith("HS")||!n.kid||!(("crypto"in globalThis)&&("subtle"in globalThis.crypto))?null:await this.fetchJwk(n.kid,(t===null||t===void 0?void 0:t.keys)?{keys:t.keys}:t===null||t===void 0?void 0:t.jwks);if(!l){let{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:i,header:n,signature:s},error:null}}let c=ed(n.alg),u=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!await crypto.subtle.verify(c,u,s,Yu(`${o}.${a}`)))throw new cn("Invalid JWT signature");return{data:{claims:i,header:n,signature:s},error:null}}catch(r){if(G(r))return this._returnResult({data:null,error:r});throw r}}}ci.nextInstanceID={};var ga=ci;var r0=ga,ma=r0;var n0="2.103.0",ui="";if(typeof Deno<"u")ui="deno";else if(typeof document<"u")ui="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")ui="react-native";else ui="node";var i0={"X-Client-Info":`supabase-js-${ui}/${n0}`},s0={headers:i0},o0={schema:"public"},a0={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},l0={};function di(e){return di=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},di(e)}function c0(e,t){if(di(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(di(n)!="object")return n;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function u0(e){var t=c0(e,"string");return di(t)=="symbol"?t:t+""}function d0(e,t,r){return(t=u0(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function bd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Te(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?bd(Object(r),!0).forEach(function(n){d0(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):bd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var h0=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)},f0=()=>Headers,A0=(e,t,r)=>{let n=h0(r),i=f0();return async(s,o)=>{var a;let l=(a=await t())!==null&&a!==void 0?a:e,c=new i(o===null||o===void 0?void 0:o.headers);if(!c.has("apikey"))c.set("apikey",e);if(!c.has("Authorization"))c.set("Authorization",`Bearer ${l}`);return n(s,Te(Te({},o),{},{headers:c}))}};function g0(e){return e.endsWith("/")?e:e+"/"}function m0(e,t){var r,n;let{db:i,auth:s,realtime:o,global:a}=e,{db:l,auth:c,realtime:u,global:d}=t,f={db:Te(Te({},l),i),auth:Te(Te({},c),s),realtime:Te(Te({},u),o),storage:{},global:Te(Te(Te({},d),a),{},{headers:Te(Te({},(r=d===null||d===void 0?void 0:d.headers)!==null&&r!==void 0?r:{}),(n=a===null||a===void 0?void 0:a.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};if(e.accessToken)f.accessToken=e.accessToken;else delete f.accessToken;return f}function p0(e){let t=e===null||e===void 0?void 0:e.trim();if(!t)throw Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(g0(t))}catch(r){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var b0=class extends ma{constructor(e){super(e)}},y0=class{constructor(e,t,r){var n,i;this.supabaseUrl=e,this.supabaseKey=t;let s=p0(e);if(!t)throw 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:o0,realtime:l0,auth:Te(Te({},a0),{},{storageKey:o}),global:s0},l=m0(r!==null&&r!==void 0?r:{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},!l.accessToken){var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}else this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});if(this.fetch=A0(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Te({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken)Promise.resolve(this.accessToken()).then((u)=>this.realtime.setAuth(u)).catch((u)=>console.warn("Failed to set initial Realtime auth token:",u));if(this.rest=new Au(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 Du(this.storageUrl.href,this.headers,this.fetch,r===null||r===void 0?void 0:r.storage),!l.accessToken)this._listenForAuthEvents()}get functions(){return new os(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this,t,r;if(e.accessToken)return await e.accessToken();let{data:n}=await e.auth.getSession();return(t=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&t!==void 0?t:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:s,flowType:o,lock:a,debug:l,throwOnError:c},u,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new b0({url:this.authUrl.href,headers:Te(Te({},f),u),storageKey:s,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:a,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some((g)=>g.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new zn(this.realtimeUrl.href,Te(Te({},e),{},{params:Te(Te({},{apikey:this.supabaseKey}),e===null||e===void 0?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t===null||t===void 0?void 0:t.access_token)})}_handleTokenChanged(e,t,r){if((e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r)this.changedAccessToken=r,this.realtime.setAuth(r);else if(e==="SIGNED_OUT"){if(this.realtime.setAuth(),t=="STORAGE")this.auth.signOut();this.changedAccessToken=void 0}}},yd=(e,t,r)=>new y0(e,t,r);function w0(){if(typeof window<"u")return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(t===void 0||t===null)return!1;let r=t.match(/^v(\d+)\./);if(!r)return!1;return parseInt(r[1],10)<=18}if(w0())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 x0=300000,vd=16384,_d=4096;function Cd(e,t){if(!e)throw Error(`${t} is not configured`);let r;try{r=new URL(e)}catch{throw Error(`${t} is not a valid URL`)}if(r.protocol!=="https:"&&r.protocol!=="http:")throw Error(`${t} must use http or https`);return r.toString()}function Ed(e=process.env){let t=Cd(e.FLATBLOX_SUPABASE_URL??e.VITE_SUPABASE_URL,"VITE_SUPABASE_URL"),r=e.FLATBLOX_SUPABASE_PUBLISHABLE_KEY??e.VITE_SUPABASE_PUBLISHABLE_KEY;if(!r)throw Error("VITE_SUPABASE_PUBLISHABLE_KEY is not configured");let n=Cd(e.FLATBLOX_DASHBOARD_URL??e.VITE_SITE_URL,e.FLATBLOX_DASHBOARD_URL?"FLATBLOX_DASHBOARD_URL":"VITE_SITE_URL"),i=e.FLATBLOX_DASHBOARD_URL?n:new URL("/dashboard/",n).toString(),s=e.XDG_CONFIG_HOME||wd(C0(),".config");return{supabaseUrl:t,publishableKey:r,dashboardUrl:i,authFile:e.FLATBLOX_TUI_AUTH_FILE??wd(s,"flatblox","tui-auth.json")}}function E0(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.accessToken==="string"&&t.accessToken.length>0&&t.accessToken.length<=vd&&typeof t.refreshToken==="string"&&t.refreshToken.length>0&&t.refreshToken.length<=vd}async function S0(e){try{let t=JSON.parse(await v0(e,"utf8"));if(!E0(t))return null;return{accessToken:t.accessToken,refreshToken:t.refreshToken}}catch(t){if(t.code==="ENOENT"||t instanceof SyntaxError)return null;throw t}}var hi=new Map;function Sd(e,t){let r=xd(e),n=(hi.get(r)??Promise.resolve()).catch(()=>{}).then(t);hi.set(r,n);let i=()=>{if(hi.get(r)===n)hi.delete(r)};return n.then(i,i),n}function Ms(e,t){let r=`${JSON.stringify({accessToken:t.access_token,refreshToken:t.refresh_token})}
61
+ `;return Sd(e,()=>$r(e,r))}function fn(e){return Sd(e,async()=>{try{await _0(e)}catch(t){if(t.code!=="ENOENT")throw t}})}function pa(e){if(typeof e!=="object"||e===null)return!1;let{code:t}=e;return t==="refresh_token_not_found"||t==="refresh_token_already_used"||t==="session_not_found"||t==="session_expired"||t==="user_not_found"||t==="bad_jwt"}function Id(e,t,r){let{data:n}=e.auth.onAuthStateChange((s,o)=>{(o?Ms(t,o):s==="SIGNED_OUT"?fn(t):void 0)?.catch(r)}),i=e.auth.startAutoRefresh().catch(r);return async()=>{n.subscription.unsubscribe(),await i,await e.auth.stopAutoRefresh(),await hi.get(xd(t))?.catch(r)}}function kd(e){return yd(e.supabaseUrl,e.publishableKey,{auth:{autoRefreshToken:!0,detectSessionInUrl:!1,persistSession:!1}})}async function ba(e,t){let r=await S0(t);if(!r)return null;let{data:n,error:i}=await e.auth.setSession({access_token:r.accessToken,refresh_token:r.refreshToken});if(i||!n.session){if(i&&!pa(i))throw i;return await fn(t),null}return await Ms(t,n.session),n.session}function I0(e,t=process.platform){if(t==="darwin")return["open",e];if(t==="win32")return["rundll32.exe","url.dll,FileProtocolHandler",e];return["xdg-open",e]}function k0(e){try{return Bun.spawn(I0(e),{stdout:"ignore",stderr:"ignore"}).unref(),!0}catch{return!1}}function R0(e){let r=`<!doctype html>
62
62
  <meta charset="utf-8">
63
63
  <title>Flatblox TUI connected</title>
64
64
  <style>body{background:#0e1018;color:#eef0ff;font:18px system-ui;display:grid;min-height:90vh;place-items:center}main{text-align:center}h1{color:#ff5ca8}</style>
@@ -69,23 +69,23 @@ history.replaceState(null,"",location.pathname+location.search);
69
69
  fetch("/token?state="+encodeURIComponent(${JSON.stringify(e)}),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:values.get("code")})})
70
70
  .then(response=>{if(!response.ok)throw new Error();document.querySelector("h1").textContent="Flatblox TUI connected";document.querySelector("#status").textContent="You can close this tab and return to the terminal."})
71
71
  .catch(()=>{document.querySelector("h1").textContent="Connection failed";document.querySelector("#status").textContent="Return to the terminal and try again."});
72
- </script>`;return new Response(r,{headers:{"cache-control":"no-store",connection:"close","content-security-policy":"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'","content-type":"text/html; charset=utf-8","x-content-type-options":"nosniff"}})}async function fd(e){let t=e.launch??n0,r=e.timeoutMs??qp,n=e.announce??((v)=>process.stdout.write(`Open this URL to connect Flatblox TUI:
73
- ${v}
72
+ </script>`;return new Response(r,{headers:{"cache-control":"no-store",connection:"close","content-security-policy":"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'","content-type":"text/html; charset=utf-8","x-content-type-options":"nosniff"}})}async function Rd(e){let t=e.launch??k0,r=e.timeoutMs??x0,n=e.announce??((w)=>process.stdout.write(`Open this URL to connect Flatblox TUI:
73
+ ${w}
74
74
 
75
- `)),{dashboardUrl:i,signal:s}=e,o=crypto.randomUUID(),a,l,c=new Promise((v,y)=>{a=v,l=y}),u=!1,d=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(v){let y=new URL(v.url);if(y.searchParams.get("state")!==o)return new Response("Invalid pairing state",{status:403});if(v.method==="GET"&&y.pathname==="/callback")return i0(o);if(v.method!=="POST"||y.pathname!=="/token")return new Response("Not found",{status:404});let E=await v.text();if(E.length>cd+64)return new Response("Pairing code is too large",{status:413});let _;try{_=JSON.parse(E)}catch{return new Response("Invalid pairing code",{status:400})}let b=typeof _==="object"&&_!==null?_.code:null;if(typeof b!=="string"||b.length===0||b.length>cd)return new Response("Invalid pairing code",{status:400});if(!u)u=!0,a(b);return new Response("Connected",{headers:{"cache-control":"no-store",connection:"close"}})}}),A=`http://127.0.0.1:${d.port}/callback`,f=new URL("tui-auth",i.endsWith("/")?i:`${i}/`);f.searchParams.set("callback",A),f.searchParams.set("state",o);let g=f.toString();n(g),t(g);let m=setTimeout(()=>{if(!u)u=!0,l(Error("Sign-in timed out"))},r),p=()=>{if(!u)u=!0,l(Error("Sign-in cancelled"))};if(s?.aborted)p();else s?.addEventListener("abort",p,{once:!0});try{return await c}finally{s?.removeEventListener("abort",p),clearTimeout(m),await d.stop(!1)}}async function gd(e,t){let{data:r,error:n}=await e.auth.verifyOtp({token_hash:t,type:"magiclink"});if(n||!r.session)throw Error(n?.message??"Could not start the Supabase session");return r.session}import{basename as s0,resolve as md}from"path";var na=`flatblox-tui [draft.json] [options]
75
+ `)),{dashboardUrl:i,signal:s}=e,o=crypto.randomUUID(),a,l,c=new Promise((w,p)=>{a=w,l=p}),u=!1,d=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(w){let p=new URL(w.url);if(p.searchParams.get("state")!==o)return new Response("Invalid pairing state",{status:403});if(w.method==="GET"&&p.pathname==="/callback")return R0(o);if(w.method!=="POST"||p.pathname!=="/token")return new Response("Not found",{status:404});let C=await w.text();if(C.length>_d+64)return new Response("Pairing code is too large",{status:413});let _;try{_=JSON.parse(C)}catch{return new Response("Invalid pairing code",{status:400})}let y=typeof _==="object"&&_!==null?_.code:null;if(typeof y!=="string"||y.length===0||y.length>_d)return new Response("Invalid pairing code",{status:400});if(!u)u=!0,a(y);return new Response("Connected",{headers:{"cache-control":"no-store",connection:"close"}})}}),f=`http://127.0.0.1:${d.port}/callback`,g=new URL("tui-auth",i.endsWith("/")?i:`${i}/`);g.searchParams.set("callback",f),g.searchParams.set("state",o);let A=g.toString();n(A),t(A);let m=setTimeout(()=>{if(!u)u=!0,l(Error("Sign-in timed out"))},r),b=()=>{if(!u)u=!0,l(Error("Sign-in cancelled"))};if(s?.aborted)b();else s?.addEventListener("abort",b,{once:!0});try{return await c}finally{s?.removeEventListener("abort",b),clearTimeout(m),await d.stop(!1)}}async function Td(e,t){let{data:r,error:n}=await e.auth.verifyOtp({token_hash:t,type:"magiclink"});if(n||!r.session)throw Error(n?.message??"Could not start the Supabase session");return r.session}import{basename as T0,resolve as Od}from"path";var wa=`flatblox-tui [draft.json] [options]
76
76
 
77
77
  Options:
78
78
  --cloud Open saved artworks from Flatblox (default)
79
79
  --local Create a new local artwork
80
80
  --logout Sign out of the cloud dashboard
81
- -s, --size <1-${Te}> Grid size for a new artwork (default: 16)
81
+ -s, --size <1-${ke}> Grid size for a new artwork (default: 16)
82
82
  -o, --output <file> Save path for a new or opened artwork
83
83
  -e, --export <fmt> Write svg, obj, png, or all next to the draft and exit
84
- -h, --help Show this help`;function ra(e,t,r){let n=e[t+1];if(!n||n.startsWith("-"))throw Error(`${r} needs a value`);return n}function pd(e){let t,r,n,i=16,s=!1,o=!1,a=!1,l=!1,c=!1;for(let u=0;u<e.length;u++){let d=e[u];if(d==="-h"||d==="--help")s=!0;else if(d==="--cloud")o=!0;else if(d==="--local")a=!0;else if(d==="--logout")o=!0,l=!0;else if(d==="-s"||d==="--size")i=Number(ra(e,u,d)),c=!0,u++;else if(d==="-o"||d==="--output")r=ra(e,u,d),c=!0,u++;else if(d==="-e"||d==="--export"){let A=ra(e,u,d),f=A==="all"?["svg","obj","png"]:A.split(",");n=n??[];for(let g of f){if(!$l(g))throw Error(`Unknown export format: ${g}`);if(!n.includes(g))n.push(g)}c=!0,u++}else if(d.startsWith("-"))throw Error(`Unknown option: ${d}`);else if(t)throw Error("Only one draft file can be opened");else t=d,c=!0}if(!Number.isInteger(i)||i<1||i>Te)throw Error(`Grid size must be between 1 and ${Te}`);if(o&&(a||c))throw Error("Cloud mode cannot be combined with local file options");return{mode:o||!a&&!c?"cloud":"local",filePath:t,outputPath:r,...n?{exportFormats:n}:{},size:i,help:s,logout:l}}function o0(e){return s0(e).replace(/\.flatblox\.json$/i,"").replace(/\.json$/i,"")}async function bd(e){let t=e.filePath?md(e.filePath):void 0,r=t?Bun.file(t):void 0,n=r&&await r.exists()?Pn(await r.text()):{...Mn(e.size),filename:t?o0(t):"untitled"},i=md(e.outputPath??t??`${n.filename}.flatblox.json`);return{session:new Vt(n),filePath:i}}var ws="id, filename, num_cols, num_rows, grid, palette, palette_saturation, palette_lightness, artboards, created_at, updated_at",wd=16;function vd(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function yd(e,t){let r=Rn(e);return r.length===t&&r.every((n)=>n.length===t)?r:null}function _d(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){if(e[r].length!==t[r].length)return!1;for(let n=0;n<e[r].length;n++){let i=e[r][n],s=t[r][n];if(i.active!==s.active||i.color!==s.color||(i.tileIndex??null)!==(s.tileIndex??null)||(i.depth??null)!==(s.depth??null)||(i.mirrorZ??!1)!==(s.mirrorZ??!1))return!1}}return!0}function a0(e){if(!Array.isArray(e))return[];return e.slice(0,oo).flatMap((t,r)=>{if(!vd(t)||!("grid"in t))return[];return[{...t,id:Number.isInteger(t.id)?Number(t.id):r,name:typeof t.name==="string"?t.name:`Frame ${r+1}`,grid:t.grid}]})}function l0(e){if(!Array.isArray(e))return[...ut[0].colors];let t=e.filter(vt).slice(0,wd);return t.length>0?t:[...ut[0].colors]}function vs(e){if(!vd(e))return null;let t=Number(e.num_cols);if(!Number.isInteger(t)||t<1||t>Te||e.num_rows!==t||typeof e.id!=="string"||typeof e.filename!=="string"||typeof e.created_at!=="string"||typeof e.updated_at!=="string")return null;let r=yd(e.grid,t);if(!r)return null;let n=a0(e.artboards),i=JSON.stringify(e.grid),s=n.findIndex((o)=>JSON.stringify(o.grid)===i);if(s<0)s=n.findIndex((o)=>{let a=yd(o.grid,t);return a?_d(a,r):!1});return{id:e.id,filename:e.filename||"Untitled",size:t,grid:r,palette:l0(e.palette),paletteSaturation:ct(e.palette_saturation),paletteLightness:ct(e.palette_lightness),artboards:n,activeArtboard:s<0?0:s,createdAt:e.created_at,updatedAt:e.updated_at}}function Cd(e){return Qt(e.grid,e.paletteSaturation,e.paletteLightness)}function xd(e){return{filename:e.filename,grid:e.grid.map((t)=>t.map((r)=>({...r}))),palette:[...e.palette],activeColor:e.activeColor??e.palette[0],paletteColorAdjustment:{saturation:e.paletteSaturation,lightness:e.paletteLightness},draft:e.draft?structuredClone(e.draft):void 0}}function c0(e,t,r=new Date().toISOString()){if(t.grid.length!==e.size||!t.grid.every((s)=>s.length===e.size))throw Error("Artwork dimensions changed");let n=Kr(t.grid),i=e.artboards.map((s)=>({...s}));if(i.length===0)i.push({id:0,name:"Frame 1",grid:n});else{let s=Math.min(e.activeArtboard,i.length-1);i[s]={...i[s],grid:n}}return{grid:n,artboards:i,updated_at:r}}function u0(e,t,r=new Date().toISOString()){let n=e.grid.length;if(n<1||n>Te||!e.grid.every((o)=>o.length===n))throw Error("Artwork grid is invalid");let i=e.palette.filter(vt).slice(0,wd);if(i.length===0)throw Error("Artwork palette is invalid");let s=Kr(e.grid);return{user_id:t,filename:e.filename||"untitled",num_cols:n,num_rows:n,grid:s,palette:i,artboards:[{id:0,name:"Frame 1",grid:s}],updated_at:r}}class ia{client;userId;afterSignOut;username;maxCanvasSize;constructor(e,t,r,n=32,i){this.client=e,this.userId=t,this.username=r,this.maxCanvasSize=n,this.afterSignOut=i}async listArtworks(){let{data:e,error:t}=await this.client.from("pixel_art").select(ws).eq("user_id",this.userId).order("created_at",{ascending:!1});if(t)throw Error(t.message);return(e??[]).flatMap((r)=>{let n=vs(r);return n?[n]:[]})}async createArtwork(e){let t=u0(e,this.userId),{data:r,error:n}=await this.client.from("pixel_art").insert(t).select(ws).single();if(n)throw Error(n.message);let i=vs(r);if(!i)throw Error("Supabase returned an invalid artwork");return i}async saveArtwork(e,t){let r=await this.trySaveArtwork(e,t);if(r)return r;let n=await this.fetchArtwork(e.id);if(!n||!_d(e.grid,n.grid))throw Error("This artwork changed in the web app. Return and refresh before saving.");let i=await this.trySaveArtwork(n,t);if(i)return i;throw Error("This artwork changed again while saving. Return and refresh before trying again.")}async trySaveArtwork(e,t){let r=c0(e,t),{data:n,error:i}=await this.client.from("pixel_art").update(r).eq("id",e.id).eq("user_id",this.userId).eq("updated_at",e.updatedAt).select(ws).maybeSingle();if(i)throw Error(i.message);if(!n)return null;let s=vs(n);if(!s)throw Error("Supabase returned an invalid artwork");return s}async fetchArtwork(e){let{data:t,error:r}=await this.client.from("pixel_art").select(ws).eq("id",e).eq("user_id",this.userId).maybeSingle();if(r)throw Error(r.message);return t?vs(t):null}async signOut(){let{error:e}=await this.client.auth.signOut();if(e)throw Error(e.message);await this.afterSignOut?.()}}import{NativeImage as d0,Renderable as h0,RGBA as A0}from"@opentui/core";var ui=A0.fromInts(14,16,24),_s=new Map,f0=256;function g0(e,t,r,n){let i=`${e}|${t}|${r}|${n}`,s=_s.get(i);if(s)return s;if(_s.size>=f0)_s.clear();let o=m0(e,t,r,n);return _s.set(i,o),o}function m0(e,t,r,n){let i=t*2,s=Math.max(1,Math.min(r,e,i)),o=Math.max(1,Math.floor(e/s)),a=Math.max(1,Math.floor(i/s)),l=1,c=1,u=0,d=Number.POSITIVE_INFINITY;for(let A=1;A<=o;A++)for(let f=1;f<=a;f++){let g=f*n/2,m=Math.min(A,g),p=Math.abs(Math.log(g/A));if(m>u||m===u&&p<d)l=A,c=f,u=m,d=p}return{sampleCount:s,columnScale:l,subrowScale:c,columns:s*l,subrows:s*c}}function p0(e,t,r,n,i){let s=Math.max(1,Math.round(Math.min(e*n,t*i))),o=Math.max(1,Math.min(r,s)),a=Math.min(e,Math.ceil(s/n));return{sampleCount:o,side:s,columns:a,rows:Math.min(t,Math.ceil(s/i)),pixelWidth:Math.max(s,Math.round(a*n))}}class sa extends h0{currentGrid=[];textFrame=null;artworkImage=null;artworkImageCache=null;constructor(e,t){super(e,{...t,buffered:!0});if(t.grid)this.currentGrid=t.grid}set grid(e){let t=e??[];if(t===this.currentGrid)return;this.currentGrid=t,this.requestRender()}renderSelf(e){let t=this.currentGrid.length,r=xt(this._ctx);if(r&&ki(this._ctx)){if(this.textFrame=null,e.clear(ui),t===0||this.width<=0||this.height<=0)return;this.drawArtworkImage(e,t,r.width,r.height);return}let n=Ii(this._ctx),i=this.textFrame;if(i&&i.grid===this.currentGrid&&i.width===this.width&&i.height===this.height&&i.cellAspect===n)return;if(this.textFrame={grid:this.currentGrid,width:this.width,height:this.height,cellAspect:n},e.clear(ui),t===0||this.width<=0||this.height<=0)return;this.releaseArtworkImage();let s=this.height*2,o=g0(this.width,this.height,t,n),{columns:a,subrows:l}=o,c=Math.floor((this.width-a)/2),u=Math.floor((s-l)/2),d=this.currentGrid,{columnScale:A,subrowScale:f,sampleCount:g}=o,m=(p)=>{let v=p-u;if(v<0||v>=l)return-1;let y=Math.floor(v/f);return Math.min(t-1,Math.floor(y*t/g))};for(let p=0;p<this.height;p++){let v=m(p*2),y=m(p*2+1);for(let E=0;E<a;E++){let _=Math.floor(E/A),b=Math.min(t-1,Math.floor(_*t/g)),w=v<0?ui:ar(d[v]?.[b],b,v),C=y<0?ui:ar(d[y]?.[b],b,y);e.setCell(c+E,p,"\u2580",w,C)}}}drawArtworkImage(e,t,r,n){let i=p0(this.width,this.height,t,r,n),s=this.artworkImageCache;if(!(this.artworkImage&&s&&s.grid===this.currentGrid&&s.sampleCount===i.sampleCount&&s.side===i.side&&s.pixelWidth===i.pixelWidth)){let a=new Uint8Array(i.sampleCount**2*4);for(let A=0;A<i.sampleCount;A++){let f=Math.min(t-1,Math.floor(A*t/i.sampleCount));for(let g=0;g<i.sampleCount;g++){let m=Math.min(t-1,Math.floor(g*t/i.sampleCount)),[p,v,y]=ar(this.currentGrid[f]?.[m],m,f).toInts(),E=(A*i.sampleCount+g)*4;a[E]=p,a[E+1]=v,a[E+2]=y,a[E+3]=255}}let l=d0.fromRgba(a,i.sampleCount,i.sampleCount),c=l.resize({width:i.side,height:i.side,kernel:"nearest"});l.dispose();let u=i.pixelWidth-i.side,d=u>0?c.extend({left:u,background:ui.toInts()}):c;if(d!==c)c.dispose();this.releaseArtworkImage(),this.artworkImage=d,this.artworkImageCache={grid:this.currentGrid,sampleCount:i.sampleCount,side:i.side,pixelWidth:i.pixelWidth}}if(!this.artworkImage)return;e.drawImage(this.artworkImage,Math.floor((this.width-i.columns)/2),Math.floor((this.height-i.rows)/2),i.columns,i.rows,i.pixelWidth,i.side,0,0,i.pixelWidth,i.side,"auto")}releaseArtworkImage(){this.artworkImage?.dispose(),this.artworkImage=null,this.artworkImageCache=null}destroySelf(){this.releaseArtworkImage(),super.destroySelf()}}Yt({artwork_preview:sa});var oa=[16,32,64],Sd=74,Ed=2;function aa(e,t){let r=Mn(e),n=ut[t];return r.palette=[...n.colors],r.activeColor=r.palette[0],r}function la(e,t){let r=e.name.toLowerCase(),n=Number(r)-1;if(r==="escape")return{kind:"cancel"};if(Number.isInteger(n)&&oa[n])return{kind:"size",size:oa[n]};let i=wr(r);if(i)return{kind:"palette",delta:i.dx+i.dy*t};if(or(e))return{kind:"create"}}function b0(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function Id(e,t){if(e.length<=t)return e;return`${e.slice(0,Math.max(1,t-1))}\u2026`}function y0(e){return Sn(eo(e.palette,e.grid),e.paletteSaturation,e.paletteLightness)}function ca(e,t){return Math.max(0,Math.min(ut.length-1,e+t))}function Cs(e){return Math.max(1,Math.min(Sd,e-4))>=64?2:1}function ua(e){let t=K(()=>Math.max(1,Math.min(Sd,e.width-4))),r=K(()=>Math.max(1,Math.min(19,e.height-2))),n=K(()=>Cs(e.width)),i=K(()=>r()>=12?1:0),s=K(()=>Math.max(1,r()-7-i()*2)),o=K(()=>s()*n()),a=K(()=>Math.floor(e.selectedPalette/o())*o()),l=K(()=>{let f=a();return ut.slice(f,f+o()).map((g,m)=>({palette:g,index:f+m}))}),c=K(()=>b0(l(),n())),u=K(()=>Math.max(1,Math.floor((t()-4-(n()-1))/n()))),d=K(()=>Math.max(3,Math.min(10,u()-8))),A=K(()=>Math.max(1,u()-d()-4));return(()=>{var f=S("box"),g=S("box"),m=S("box"),p=S("text"),v=S("box"),y=S("text"),E=Re("Choose a palette | "),_=S("box"),b=S("box"),w=S("text");return k(f,g),h(f,"id","new-artwork-modal"),h(f,"position","absolute"),h(f,"zIndex",30),h(f,"border",!0),h(f,"title"," New artwork "),h(f,"flexDirection","column"),k(g,m),k(g,v),k(g,y),k(g,_),k(g,b),k(g,w),h(g,"flexGrow",1),h(g,"width","100%"),h(g,"padding",1),h(g,"flexDirection","column"),k(m,p),h(m,"height",1),h(m,"flexDirection","row"),h(m,"gap",1),k(p,Re("Grid size")),L(m,Q(wt,{each:oa,children:(C,O)=>{let N=()=>C<=e.maxSize,P=()=>C===e.selectedSize;return(()=>{var R=S("box"),U=S("text"),X=Re(" "),V=Re("\xD7");return k(R,U),h(R,"height",1),h(R,"paddingX",1),h(R,"onMouseDown",()=>e.onSelectSize(C)),k(U,X),k(U,V),L(U,()=>O()+1,X),L(U,C,V),L(U,C,null),de((te)=>{var ge=P()?x.panelActive:x.panel,z=N()?P()?x.accentText:x.muted:x.border;return ge!==te.e&&(te.e=h(R,"backgroundColor",ge,te.e)),z!==te.t&&(te.t=h(U,"fg",z,te.t)),te},{e:void 0,t:void 0}),R})()}}),null),k(y,E),L(y,()=>ut[e.selectedPalette].name,null),L(g,Q(wt,{get each(){return c()},children:(C)=>(()=>{var O=S("box");return h(O,"height",1),h(O,"flexDirection","row"),h(O,"gap",1),L(O,Q(wt,{each:C,children:(N)=>{let P=()=>N.index===e.selectedPalette;return(()=>{var R=S("box"),U=S("text"),X=S("box");return k(R,U),k(R,X),h(R,"height",1),h(R,"paddingX",1),h(R,"flexDirection","row"),h(R,"justifyContent","space-between"),h(R,"onMouseDown",()=>e.onSelectPalette(N.index)),L(U,()=>Id(N.palette.name,A())),h(X,"height",1),h(X,"flexDirection","row"),L(X,Q(wt,{get each(){return N.palette.colors.slice(0,d())},children:(V)=>(()=>{var te=S("text");return k(te,Re("\u25A0")),de((ge)=>h(te,"fg",je(V),ge)),te})()})),de((V)=>{var te=u(),ge=P()?x.panelActive:x.panel,z=P()?x.text:x.muted;return te!==V.e&&(V.e=h(R,"width",te,V.e)),ge!==V.t&&(V.t=h(R,"backgroundColor",ge,V.t)),z!==V.a&&(V.a=h(U,"fg",z,V.a)),V},{e:void 0,t:void 0,a:void 0}),R})()}})),O})()}),_),h(b,"flexGrow",1),L(w,()=>e.message||"1\u20133 size \xB7 arrows palette \xB7 Enter create \xB7 Esc cancel"),de((C)=>{var O=Math.max(0,Math.floor((e.width-t())/2)),N=Math.max(0,Math.floor((e.height-r())/2)),P=t(),R=r(),U=x.border,X=x.accent,V=x.panel,te=x.textPink,ge=i(),z=x.textPink,Me=i(),Le=e.message?x.warning:x.textPink;return O!==C.e&&(C.e=h(f,"left",O,C.e)),N!==C.t&&(C.t=h(f,"top",N,C.t)),P!==C.a&&(C.a=h(f,"width",P,C.a)),R!==C.o&&(C.o=h(f,"height",R,C.o)),U!==C.i&&(C.i=h(f,"borderColor",U,C.i)),X!==C.n&&(C.n=h(f,"titleColor",X,C.n)),V!==C.s&&(C.s=h(g,"backgroundColor",V,C.s)),te!==C.h&&(C.h=h(p,"fg",te,C.h)),ge!==C.r&&(C.r=h(v,"height",ge,C.r)),z!==C.d&&(C.d=h(y,"fg",z,C.d)),Me!==C.l&&(C.l=h(_,"height",Me,C.l)),Le!==C.u&&(C.u=h(w,"fg",Le,C.u)),C},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0}),f})()}function w0(e){let t=K(()=>Cd(e.artwork)),r=K(()=>y0(e.artwork)),n=()=>e.selected()===e.index,i=()=>e.cardWidth-2;return(()=>{var s=S("box"),o=S("box"),a=S("box"),l=S("artwork_preview"),c=S("box"),u=S("text"),d=S("text"),A=S("text"),f=S("box"),g=S("box");return k(s,o),k(s,d),k(s,A),k(s,f),k(s,g),h(s,"flexDirection","column"),k(o,a),h(o,"width","100%"),h(o,"height","100%"),h(o,"border",!0),h(o,"borderColor","transparent"),h(o,"flexDirection","column"),k(a,l),k(a,c),k(a,u),h(a,"flexGrow",1),h(a,"width","100%"),h(a,"flexDirection","column"),h(a,"paddingX",1),h(l,"flexGrow",1),h(l,"width","100%"),h(c,"height",1),h(c,"width","100%"),h(c,"flexDirection","row"),h(c,"gap",1),h(c,"overflow","hidden"),L(c,Q(wt,{get each(){return r()},children:(m)=>Q(Fn,{get color(){return je(m)},get background(){return x.panel},width:1,shape:"circle"})})),L(u,()=>Id(e.artwork.filename,e.cardWidth-3)),h(d,"position","absolute"),h(d,"left",1),h(d,"top",0),h(d,"height",1),h(d,"zIndex",1),L(d,()=>"\u2580".repeat(i())),h(A,"position","absolute"),h(A,"left",1),h(A,"height",1),h(A,"zIndex",1),L(A,()=>"\u2584".repeat(i())),h(f,"position","absolute"),h(f,"left",0),h(f,"top",0),h(f,"width",1),h(f,"height","100%"),h(f,"zIndex",2),h(g,"position","absolute"),h(g,"top",0),h(g,"width",1),h(g,"height","100%"),h(g,"zIndex",2),de((m)=>{var p=`artwork-card-${e.artwork.id}`,v=e.cardWidth,y=e.cardHeight,E=x.card,_=e.onSelect,b=x.card,w=x.panel,C=`artwork-preview-${e.artwork.id}`,O=t(),N=x.textPink,P=`artwork-card-selection-top-${e.artwork.id}`,R=i(),U=n()?x.orangeActive:x.card,X=x.panel,V=`artwork-card-selection-bottom-${e.artwork.id}`,te=e.cardHeight-1,ge=i(),z=n()?x.orangeActive:x.card,Me=x.panel,Le=`artwork-card-selection-side-${e.artwork.id}`,q=n()?x.orangeActive:x.card,Z=e.cardWidth-1,ue=n()?x.orangeActive:x.card;return p!==m.e&&(m.e=h(s,"id",p,m.e)),v!==m.t&&(m.t=h(s,"width",v,m.t)),y!==m.a&&(m.a=h(s,"height",y,m.a)),E!==m.o&&(m.o=h(s,"backgroundColor",E,m.o)),_!==m.i&&(m.i=h(s,"onMouseDown",_,m.i)),b!==m.n&&(m.n=h(o,"backgroundColor",b,m.n)),w!==m.s&&(m.s=h(a,"backgroundColor",w,m.s)),C!==m.h&&(m.h=h(l,"id",C,m.h)),O!==m.r&&(m.r=h(l,"grid",O,m.r)),N!==m.d&&(m.d=h(u,"fg",N,m.d)),P!==m.l&&(m.l=h(d,"id",P,m.l)),R!==m.u&&(m.u=h(d,"width",R,m.u)),U!==m.c&&(m.c=h(d,"fg",U,m.c)),X!==m.w&&(m.w=h(d,"bg",X,m.w)),V!==m.m&&(m.m=h(A,"id",V,m.m)),te!==m.f&&(m.f=h(A,"top",te,m.f)),ge!==m.y&&(m.y=h(A,"width",ge,m.y)),z!==m.g&&(m.g=h(A,"fg",z,m.g)),Me!==m.p&&(m.p=h(A,"bg",Me,m.p)),Le!==m.b&&(m.b=h(f,"id",Le,m.b)),q!==m.T&&(m.T=h(f,"backgroundColor",q,m.T)),Z!==m.A&&(m.A=h(g,"left",Z,m.A)),ue!==m.O&&(m.O=h(g,"backgroundColor",ue,m.O)),m},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0,m:void 0,f:void 0,y:void 0,g:void 0,p:void 0,b:void 0,T:void 0,A:void 0,O:void 0}),s})()}function da(e){let t=ht(),r=Lr(),[n,i]=j([]),[s,o]=j(0),[a,l]=j(!0),[c,u]=j("Loading saved artworks\u2026"),[d,A]=j(null),[f,g]=j(!1),[m,p]=j(16),[v,y]=j(0),[E,_]=j(""),b=K(()=>{let M=Math.max(8,r().width-2);return Math.min(28,M,Math.max(12,Math.floor(M/3)))}),w=K(()=>{let M=r().height<18?7:r().height<25?9:12;return Math.max(4,Math.min(M,r().height-6))}),C=K(()=>Math.max(1,Math.floor((r().width-2)/(b()+Ed)))),O=K(()=>C()*b()+Math.max(0,C()-1)*Ed),N=K(()=>Math.max(1,Math.floor((r().height-5)/(w()+1)))),P=K(()=>C()*N()),R=K(()=>Math.floor(s()/P())),U=K(()=>R()*P()),X=K(()=>{let M=U();return n().slice(M,M+P())});mi(()=>{let M=Math.max(0,n().length-1);if(s()>M)o(M)});let V=async()=>{l(!0),u("Loading saved artworks\u2026");try{let M=await e.repository.listArtworks();i(M),u(M.length===0?"No saved artworks yet":`${M.length} saved artwork${M.length===1?"":"s"}`)}catch(M){u(`Load failed: ${M instanceof Error?M.message:String(M)}`)}finally{l(!1)}};gr(()=>void V());let te=(M,re)=>{let ie=n().length;if(ie===0)return;let oe=Math.max(0,Math.min(ie-1,s()+M+re*C()));o(oe),u(n()[oe].filename)},ge=()=>{let M=n()[s()];if(!M)return;A({artwork:M,session:new Vt(xd(M))})},z=()=>{p(16),y(0),_(""),g(!0),u("Choose a size and palette")},Me=()=>{g(!1),_(""),u("New artwork cancelled")},Le=(M)=>{if(M>e.repository.maxCanvasSize){_(`${M}\xD7${M} is unavailable on this plan`);return}p(M),_("")},q=(M)=>{y((re)=>ca(re,M)),_("")},Z=()=>{g(!1),A({artwork:null,session:new Vt(aa(m(),v()))})},ue=async(M)=>{let re=d();if(!re)throw Error("No artwork is open");let ie=re.artwork?await e.repository.saveArtwork(re.artwork,M):await e.repository.createArtwork(M);if(i((oe)=>oe.some((me)=>me.id===ie.id)?oe.map((me)=>me.id===ie.id?ie:me):[ie,...oe]),!re.artwork)o(0);return A((oe)=>oe===re?{...oe,artwork:ie}:oe),e.variant==="local"?"Saved locally":"Saved to Flatblox cloud"},pe=async()=>{u("Signing out\u2026");try{await e.repository.signOut(),t.destroy()}catch(M){u(`Sign out failed: ${M instanceof Error?M.message:String(M)}`)}};return Fr((M)=>{if(M.eventType==="release"||d())return;let re=M.name.toLowerCase();if(f()){let oe=la(M,Cs(r().width));if(oe?.kind==="cancel")Me();else if(oe?.kind==="size")Le(oe.size);else if(oe?.kind==="palette")q(oe.delta);else if(oe?.kind==="create")Z();return}let ie=wr(re);if(M.ctrl&&re==="c")t.destroy();else if(re==="escape"&&e.onBack)e.onBack();else if(re==="q"||re==="escape")t.destroy();else if(ie)te(ie.dx,ie.dy);else if(re==="n")z();else if(or(M))ge();else if(re==="r")V();else if(re==="o"&&e.variant!=="local")pe()}),Q(ke,{get when(){return d()},get fallback(){return(()=>{var M=S("box"),re=S("box"),ie=S("box"),oe=S("text"),qe=S("b"),me=S("box"),Se=S("box"),gt=S("text"),Ze=S("box"),et=S("box"),ee=S("text"),mt=S("text");return k(M,re),k(M,Ze),k(M,et),h(M,"width","100%"),h(M,"height","100%"),h(M,"flexDirection","column"),k(re,ie),k(re,me),k(re,Se),h(re,"height",3),h(re,"paddingY",1),h(re,"paddingX",1),h(re,"flexDirection","row"),k(ie,oe),h(ie,"height",1),h(ie,"flexBasis",0),h(ie,"flexGrow",1),h(ie,"flexDirection","row"),k(oe,qe),L(qe,Fi),h(me,"height",1),h(me,"flexBasis",0),h(me,"flexGrow",1),h(me,"flexDirection","row"),h(me,"justifyContent","center"),L(me,Q($r,{id:"dashboard-wordmark",width:14,height:1,get backgroundColor(){return x.panel},get foregroundColor(){return x.accent}})),k(Se,gt),h(Se,"height",1),h(Se,"flexBasis",0),h(Se,"flexGrow",1),h(Se,"flexDirection","row"),h(Se,"justifyContent","flex-end"),L(gt,()=>e.repository.username),h(Ze,"id","dashboard-content"),h(Ze,"flexGrow",1),h(Ze,"flexDirection","column"),h(Ze,"justifyContent","center"),h(Ze,"padding",1),L(Ze,Q(ke,{get when(){return lt(()=>!a())()&&n().length>0},get fallback(){return(()=>{var T=S("box"),Y=S("text");return k(T,Y),h(T,"flexGrow",1),h(T,"alignItems","center"),h(T,"justifyContent","center"),L(Y,c),de((he)=>h(Y,"fg",x.muted,he)),T})()},get children(){var T=S("box");return h(T,"id","artwork-grid"),h(T,"alignSelf","center"),h(T,"flexDirection","row"),h(T,"flexWrap","wrap"),h(T,"rowGap",1),h(T,"columnGap",2),L(T,Q(wt,{get each(){return X()},children:(Y,he)=>Q(w0,{artwork:Y,get index(){return U()+he()},selected:s,get cardWidth(){return b()},get cardHeight(){return w()},onSelect:()=>o(U()+he())})})),de((Y)=>h(T,"width",O(),Y)),T}})),k(et,ee),k(et,mt),h(et,"height",1),h(et,"paddingX",1),h(et,"flexDirection","row"),h(et,"justifyContent","space-between"),L(ee,c),L(mt,()=>e.variant==="local"?"N new | arrows move | Enter edit | R refresh | Esc back | Q quit":"N new | arrows move | Enter edit | R refresh | O sign out | Q quit"),L(M,Q(ke,{get when(){return f()},get children(){return Q(ua,{get width(){return r().width},get height(){return r().height},get selectedPalette(){return v()},get selectedSize(){return m()},get maxSize(){return e.repository.maxCanvasSize},get message(){return E()},onSelectPalette:(T)=>{y(T),_("")},onSelectSize:Le})}}),null),de((T)=>{var Y=x.background,he=x.panel,it=x.accentText,Ct=x.muted,Fe=x.panel,be=x.panelActive,Xe=c().startsWith("Load failed")?x.warning:x.textPink,Lt=x.muted;return Y!==T.e&&(T.e=h(M,"backgroundColor",Y,T.e)),he!==T.t&&(T.t=h(re,"backgroundColor",he,T.t)),it!==T.a&&(T.a=h(oe,"fg",it,T.a)),Ct!==T.o&&(T.o=h(gt,"fg",Ct,T.o)),Fe!==T.i&&(T.i=h(Ze,"backgroundColor",Fe,T.i)),be!==T.n&&(T.n=h(et,"backgroundColor",be,T.n)),Xe!==T.s&&(T.s=h(ee,"fg",Xe,T.s)),Lt!==T.h&&(T.h=h(mt,"fg",Lt,T.h)),T},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),M})()},children:(M)=>Q(Zr,{get session(){return M().session},saveDocument:ue,get promptForFilenameOnSave(){return!M().artwork},onBack:()=>{A(null),u("Returned from editor")}})})}import{readdir as v0,readFile as _0,stat as kd,writeFile as C0}from"fs/promises";import{basename as x0,join as Rd,resolve as E0}from"path";function Td(e,t,r,n){return{id:e,filename:t.filename,size:t.grid.length,grid:t.grid,palette:t.palette,paletteSaturation:t.paletteColorAdjustment?.saturation??0,paletteLightness:t.paletteColorAdjustment?.lightness??0,artboards:[],activeArtboard:t.draft?.activeArtboard??0,createdAt:r.toISOString(),updatedAt:n.toISOString(),activeColor:t.activeColor,draft:t.draft}}function S0(e){return e.replace(/[\\/]/g,"-").replace(/^\.+$/,"")||"untitled"}function I0(e){return typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string"&&e.code!=="ENOENT"}function k0(e=process.env,t=process.cwd()){return e.INIT_CWD||e.PWD||t}class ha{username;maxCanvasSize=64;directory;constructor(e=k0()){this.directory=E0(e),this.username=x0(this.directory)||"Local"}async listArtworks(){let e=await v0(this.directory,{withFileTypes:!0});return(await Promise.all(e.map(async(r)=>{if(!r.isFile()||!r.name.endsWith(".flatblox.json"))return null;let n=Rd(this.directory,r.name);try{let i=Pn(await _0(n,"utf8")),s=await kd(n),o=s.birthtimeMs>0?s.birthtime:s.mtime;return Td(n,i,o,s.mtime)}catch(i){if(I0(i))throw i;return null}}))).filter((r)=>r!==null).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}async createArtwork(e){let t=Rd(this.directory,`${S0(e.filename)}.flatblox.json`);if(await Bun.file(t).exists())throw Error(`A local artwork named ${e.filename} already exists`);return this.writeArtwork(t,e)}async saveArtwork(e,t){return this.writeArtwork(e.id,t)}async signOut(){}async writeArtwork(e,t){await C0(e,Dn(t));let r=await kd(e),n=r.birthtimeMs>0?r.birthtime:r.mtime;return Td(e,t,n,r.mtime)}}function Bd(e){let t=ht(),r=Lr(),[n,i]=j(0),[s,o]=j(!1),[a,l]=j(16),[c,u]=j(0),[d,A]=j(null),[f,g]=j(null),[m,p]=j(!1),v=e.cloudRepository,[y,E]=j(v instanceof Promise?null:v??null);if(v instanceof Promise)v.then(E,(q)=>N(q instanceof Error?q.message:String(q)));let[_,b]=j(!1),[w,C]=j(!1),[O,N]=j(""),[P,R]=j(""),U=null,X=e.localRepository??new ha,V=()=>{l(16),u(0),o(!0)},te=()=>{o(!1),g(null),A(new Vt(aa(a(),c())))},ge=(q)=>{u((Z)=>ca(Z,q))},z=async()=>{if(w())return;let q=new AbortController;U=q,C(!0),N(""),R("");try{let Z=await e.onSignIn(q.signal,R);if(!q.signal.aborted)E(Z),b(!0)}catch(Z){if(!q.signal.aborted)N(Z instanceof Error?Z.message:String(Z))}finally{if(U===q)U=null;C(!1)}},Me=(q)=>{i((Z)=>Math.max(0,Math.min(2,Z+q)))},Le=()=>{if(y())b(!0);else z()};return Fr((q)=>{if(q.eventType==="release"||d()||m()||_())return;let Z=q.name.toLowerCase();if(w()){if(Z==="escape"||Z==="q"||q.ctrl&&Z==="c")U?.abort();return}if(s()){let pe=la(q,Cs(r().width));if(pe?.kind==="cancel")o(!1);else if(pe?.kind==="size")l(pe.size);else if(pe?.kind==="palette")ge(pe.delta);else if(pe?.kind==="create")te();return}let ue=wr(Z);if(q.ctrl&&Z==="c")t.destroy();else if(Z==="q"||Z==="escape")t.destroy();else if(ue?.dy)Me(ue.dy);else if(Z==="n")V();else if(Z==="l")p(!0);else if(Z==="s"||Z==="d")Le();else if(or(q))if(n()===0)V();else if(n()===1)p(!0);else Le()}),Q(ke,{get when(){return lt(()=>!!_())()?y():null},get fallback(){return Q(ke,{get when(){return d()},get fallback(){return Q(ke,{get when(){return m()},get fallback(){return(()=>{var q=S("box"),Z=S("box"),ue=S("box"),pe=S("box"),M=S("box"),re=S("text"),ie=S("box"),oe=S("box"),qe=S("text"),me=S("box"),Se=S("box"),gt=S("text"),Ze=S("box"),et=S("text");return k(q,Z),h(q,"width","100%"),h(q,"height","100%"),h(q,"alignItems","center"),h(q,"justifyContent","center"),k(Z,ue),k(Z,pe),k(Z,ie),k(Z,me),k(Z,Ze),k(Z,et),h(Z,"flexDirection","column"),h(Z,"alignItems","center"),L(Z,Q($r,{id:"welcome-wordmark",width:32,height:2,get backgroundColor(){return x.background},get foregroundColor(){return x.accent}}),ue),h(ue,"height",3),k(pe,M),h(pe,"id","welcome-new-artwork"),h(pe,"width",36),h(pe,"height",3),h(pe,"border",!0),h(pe,"onMouseDown",()=>{i(0),V()}),k(M,re),h(M,"width","100%"),h(M,"height","100%"),h(M,"alignItems","center"),h(M,"justifyContent","center"),k(re,Re("New artwork")),h(re,"id","welcome-new-artwork-label"),k(ie,oe),h(ie,"id","welcome-load-artwork"),h(ie,"width",36),h(ie,"height",3),h(ie,"border",!0),h(ie,"onMouseDown",()=>{i(1),p(!0)}),k(oe,qe),h(oe,"width","100%"),h(oe,"height","100%"),h(oe,"alignItems","center"),h(oe,"justifyContent","center"),k(qe,Re("Load artwork")),h(qe,"id","welcome-load-artwork-label"),k(me,Se),h(me,"id","welcome-sign-in"),h(me,"width",36),h(me,"height",3),h(me,"border",!0),h(me,"onMouseDown",()=>{i(2),Le()}),k(Se,gt),h(Se,"width","100%"),h(Se,"height","100%"),h(Se,"alignItems","center"),h(Se,"justifyContent","center"),h(gt,"id","welcome-sign-in-label"),L(gt,()=>y()?"Dashboard":"Sign in"),h(Ze,"height",2),L(et,(()=>{var ee=lt(()=>!!w());return()=>ee()?lt(()=>!!P())()?`Open this URL: ${P()} \xB7 Esc cancel`:"Complete sign-in in your browser \xB7 Esc cancel":O()||"\u2191/\u2193 select \xB7 Enter open \xB7 Q quit"})()),L(q,Q(ke,{get when(){return s()},get children(){return Q(ua,{get width(){return r().width},get height(){return r().height},get selectedPalette(){return c()},get selectedSize(){return a()},maxSize:64,message:"",onSelectPalette:u,onSelectSize:l})}}),null),de((ee)=>{var mt=x.background,T=P()?Math.max(36,r().width-4):36,Y=n()===0?x.accent:x.border,he=n()===0?x.textPink:x.text,it=n()===1?x.accent:x.border,Ct=n()===1?x.textPink:x.text,Fe=n()===2?x.accent:x.border,be=n()===2?x.textPink:x.text,Xe=O()?x.warning:x.muted;return mt!==ee.e&&(ee.e=h(q,"backgroundColor",mt,ee.e)),T!==ee.t&&(ee.t=h(Z,"width",T,ee.t)),Y!==ee.a&&(ee.a=h(pe,"borderColor",Y,ee.a)),he!==ee.o&&(ee.o=h(re,"fg",he,ee.o)),it!==ee.i&&(ee.i=h(ie,"borderColor",it,ee.i)),Ct!==ee.n&&(ee.n=h(qe,"fg",Ct,ee.n)),Fe!==ee.s&&(ee.s=h(me,"borderColor",Fe,ee.s)),be!==ee.h&&(ee.h=h(gt,"fg",be,ee.h)),Xe!==ee.r&&(ee.r=h(et,"fg",Xe,ee.r)),ee},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),q})()},get children(){return Q(da,{repository:X,variant:"local",onBack:()=>p(!1)})}})},children:(q)=>Q(Zr,{get session(){return q()},saveDocument:async(Z)=>{let ue=f(),pe=ue?await X.saveArtwork(ue,Z):await X.createArtwork(Z);return g(pe),"Saved locally"},get promptForFilenameOnSave(){return!f()},onBack:()=>{g(null),A(null)}})})},children:(q)=>Q(da,{get repository(){return q()}})})}var Od={backgroundColor:x.background,debounceDelay:1,exitOnCtrlC:!1,targetFps:60,useKittyKeyboard:{events:!0,allKeysAsEscapes:!0}};async function R0(e){let t=dd(),r=hd(t),n=await Ad(r,t.authFile);if(e){if(n)await r.auth.signOut();await Or(t.authFile),process.stdout.write(`Signed out of Flatblox TUI.
85
- `);return}let i,s=async(o)=>{if(!i){let{data:d}=r.auth.onAuthStateChange((A,f)=>{if(f)ys(t.authFile,f);else Or(t.authFile)});i=()=>d.subscription.unsubscribe(),r.auth.startAutoRefresh()}let{data:a,error:l}=await r.auth.getUser(o);if(l||!a.user)throw await Or(t.authFile),Error(l?.message??"Could not verify the Supabase session");let{data:c,error:u}=await r.from("profiles").select("username, tier").eq("id",a.user.id).maybeSingle();if(u)throw await Or(t.authFile),Error(u.message);return new ia(r,a.user.id,c?.username?.trim()||"Flatblox account",cl[c?.tier??"tier0"],()=>Or(t.authFile))};try{let o=n?s(n.access_token):void 0;await Xs(()=>Q(Bd,{cloudRepository:o,onSignIn:async(a,l)=>{let c=await fd({dashboardUrl:t.dashboardUrl,announce:l,signal:a}),u=await gd(r,c);return await ys(t.authFile,u),s(u.access_token)}}),Od)}finally{if(i)i(),await r.auth.stopAutoRefresh()}}async function T0(e){let t=await bd(e);if(e.exportFormats){let r=await Bi(t.session.toDocument(),Gn(t.filePath,t.session.filename),e.exportFormats);process.stdout.write(`${r.join(`
84
+ -h, --help Show this help`;function ya(e,t,r){let n=e[t+1];if(!n||n.startsWith("-"))throw Error(`${r} needs a value`);return n}function Bd(e){let t,r,n,i=16,s=!1,o=!1,a=!1,l=!1,c=!1;for(let u=0;u<e.length;u++){let d=e[u];if(d==="-h"||d==="--help")s=!0;else if(d==="--cloud")o=!0;else if(d==="--local")a=!0;else if(d==="--logout")o=!0,l=!0;else if(d==="-s"||d==="--size")i=Number(ya(e,u,d)),c=!0,u++;else if(d==="-o"||d==="--output")r=ya(e,u,d),c=!0,u++;else if(d==="-e"||d==="--export"){let f=ya(e,u,d),g=f==="all"?["svg","obj","png"]:f.split(",");n=n??[];for(let A of g){if(!dc(A))throw Error(`Unknown export format: ${A}`);if(!n.includes(A))n.push(A)}c=!0,u++}else if(d.startsWith("-"))throw Error(`Unknown option: ${d}`);else if(t)throw Error("Only one draft file can be opened");else t=d,c=!0}if(!Number.isInteger(i)||i<1||i>ke)throw Error(`Grid size must be between 1 and ${ke}`);if(o&&(a||c))throw Error("Cloud mode cannot be combined with local file options");return{mode:o||!a&&!c?"cloud":"local",filePath:t,outputPath:r,...n?{exportFormats:n}:{},size:i,help:s,logout:l}}function O0(e){return T0(e).replace(/\.flatblox\.json$/i,"").replace(/\.json$/i,"")}async function Pd(e){let t=e.filePath?Od(e.filePath):void 0,r=t?Bun.file(t):void 0,n=r&&await r.exists()?Mn(await r.text()):{...Fn(e.size),filename:t?O0(t):"untitled"},i=Od(e.outputPath??t??`${n.filename}.flatblox.json`);return{session:new Jt(n),filePath:i}}var Ns="id, filename, num_cols, num_rows, grid, palette, palette_saturation, palette_lightness, artboards, created_at, updated_at",Md=16;function Nd(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Dd(e,t){let r=On(e);return r.length===t&&r.every((n)=>n.length===t)?r:null}function Ld(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){if(e[r].length!==t[r].length)return!1;for(let n=0;n<e[r].length;n++){let i=e[r][n],s=t[r][n];if(i.active!==s.active||i.color!==s.color||(i.tileIndex??null)!==(s.tileIndex??null)||(i.depth??null)!==(s.depth??null)||(i.mirrorZ??!1)!==(s.mirrorZ??!1))return!1}}return!0}function B0(e){if(!Array.isArray(e))return[];return e.slice(0,wo).flatMap((t,r)=>{if(!Nd(t)||!("grid"in t))return[];return[{...t,id:Number.isInteger(t.id)?Number(t.id):r,name:typeof t.name==="string"?t.name:`Frame ${r+1}`,grid:t.grid}]})}function P0(e){if(!Array.isArray(e))return[...ht[0].colors];let t=e.filter(_t).slice(0,Md);return t.length>0?t:[...ht[0].colors]}function Ls(e){if(!Nd(e))return null;let t=Number(e.num_cols);if(!Number.isInteger(t)||t<1||t>ke||e.num_rows!==t||typeof e.id!=="string"||typeof e.filename!=="string"||typeof e.created_at!=="string"||typeof e.updated_at!=="string")return null;let r=Dd(e.grid,t);if(!r)return null;let n=B0(e.artboards),i=JSON.stringify(e.grid),s=n.findIndex((o)=>JSON.stringify(o.grid)===i);if(s<0)s=n.findIndex((o)=>{let a=Dd(o.grid,t);return a?Ld(a,r):!1});return{id:e.id,filename:e.filename||"Untitled",size:t,grid:r,palette:P0(e.palette),paletteSaturation:dt(e.palette_saturation),paletteLightness:dt(e.palette_lightness),artboards:n,activeArtboard:s<0?0:s,createdAt:e.created_at,updatedAt:e.updated_at}}function Fd(e){return Qt(e.grid,e.paletteSaturation,e.paletteLightness)}function Gd(e){return{filename:e.filename,grid:e.grid.map((t)=>t.map((r)=>({...r}))),palette:[...e.palette],activeColor:e.activeColor??e.palette[0],paletteColorAdjustment:{saturation:e.paletteSaturation,lightness:e.paletteLightness},draft:e.draft?structuredClone(e.draft):void 0}}function D0(e,t,r=new Date().toISOString()){if(t.grid.length!==e.size||!t.grid.every((s)=>s.length===e.size))throw Error("Artwork dimensions changed");let n=Qr(t.grid),i=e.artboards.map((s)=>({...s}));if(i.length===0)i.push({id:0,name:"Frame 1",grid:n});else{let s=Math.min(e.activeArtboard,i.length-1);i[s]={...i[s],grid:n}}return{grid:n,artboards:i,updated_at:r}}function M0(e,t,r=new Date().toISOString()){let n=e.grid.length;if(n<1||n>ke||!e.grid.every((o)=>o.length===n))throw Error("Artwork grid is invalid");let i=e.palette.filter(_t).slice(0,Md);if(i.length===0)throw Error("Artwork palette is invalid");let s=Qr(e.grid);return{user_id:t,filename:e.filename||"untitled",num_cols:n,num_rows:n,grid:s,palette:i,artboards:[{id:0,name:"Frame 1",grid:s}],updated_at:r}}class va{client;userId;afterSignOut;username;maxCanvasSize;constructor(e,t,r,n=32,i){this.client=e,this.userId=t,this.username=r,this.maxCanvasSize=n,this.afterSignOut=i}async listArtworks(){let e=[],t=0;for(;;){let{data:r,error:n}=await this.client.from("pixel_art").select(Ns).eq("user_id",this.userId).order("created_at",{ascending:!1}).order("id",{ascending:!1}).range(t,t+99);if(n?.code==="PGRST103"&&t>0)return e;if(n)throw Error(n.message);if(!r?.length)return e;for(let i of r){let s=Ls(i);if(s)e.push(s)}t+=r.length}}async createArtwork(e){let t=M0(e,this.userId),{data:r,error:n}=await this.client.from("pixel_art").insert(t).select(Ns).single();if(n)throw Error(n.message);let i=Ls(r);if(!i)throw Error("Supabase returned an invalid artwork");return i}async saveArtwork(e,t){let r=await this.trySaveArtwork(e,t);if(r)return r;let n=await this.fetchArtwork(e.id);if(!n||!Ld(e.grid,n.grid))throw Error("This artwork changed in the web app. Return and refresh before saving.");let i=await this.trySaveArtwork(n,t);if(i)return i;throw Error("This artwork changed again while saving. Return and refresh before trying again.")}async trySaveArtwork(e,t){let r=D0(e,t),{data:n,error:i}=await this.client.from("pixel_art").update(r).eq("id",e.id).eq("user_id",this.userId).eq("updated_at",e.updatedAt).select(Ns).maybeSingle();if(i)throw Error(i.message);if(!n)return null;let s=Ls(n);if(!s)throw Error("Supabase returned an invalid artwork");return s}async fetchArtwork(e){let{data:t,error:r}=await this.client.from("pixel_art").select(Ns).eq("id",e).eq("user_id",this.userId).maybeSingle();if(r)throw Error(r.message);return t?Ls(t):null}async signOut(){let{error:e}=await this.client.auth.signOut();if(e)throw Error(e.message);await this.afterSignOut?.()}}async function Ud(e,t,r=Si){let n=Promise.withResolvers();await r(e,{...t,onDestroy:()=>{try{t.onDestroy?.()}finally{n.resolve()}}}),await n.promise}import{NativeImage as N0,Renderable as L0,RGBA as F0}from"@opentui/core";var fi=F0.fromInts(14,16,24),Fs=new Map,G0=256;function U0(e,t,r,n){let i=`${e}|${t}|${r}|${n}`,s=Fs.get(i);if(s)return s;if(Fs.size>=G0)Fs.clear();let o=H0(e,t,r,n);return Fs.set(i,o),o}function H0(e,t,r,n){let i=t*2,s=Math.max(1,Math.min(r,e,i)),o=Math.max(1,Math.floor(e/s)),a=Math.max(1,Math.floor(i/s)),l=1,c=1,u=0,d=Number.POSITIVE_INFINITY;for(let f=1;f<=o;f++)for(let g=1;g<=a;g++){let A=g*n/2,m=Math.min(f,A),b=Math.abs(Math.log(A/f));if(m>u||m===u&&b<d)l=f,c=g,u=m,d=b}return{sampleCount:s,columnScale:l,subrowScale:c,columns:s*l,subrows:s*c}}function j0(e,t,r,n,i){let s=Math.max(1,Math.round(Math.min(e*n,t*i))),o=Math.max(1,Math.min(r,s)),a=Math.min(e,Math.ceil(s/n));return{sampleCount:o,side:s,columns:a,rows:Math.min(t,Math.ceil(s/i)),pixelWidth:Math.max(s,Math.round(a*n))}}class _a extends L0{currentGrid=[];textFrame=null;artworkImage=null;artworkImageCache=null;constructor(e,t){super(e,{...t,buffered:!0});if(t.grid)this.currentGrid=t.grid}set grid(e){let t=e??[];if(t===this.currentGrid)return;this.currentGrid=t,this.requestRender()}renderSelf(e){let t=this.currentGrid.length,r=Et(this._ctx);if(r&&Li(this._ctx)){if(this.textFrame=null,e.clear(fi),t===0||this.width<=0||this.height<=0)return;this.drawArtworkImage(e,t,r.width,r.height);return}let n=Ni(this._ctx),i=this.textFrame;if(i&&i.grid===this.currentGrid&&i.width===this.width&&i.height===this.height&&i.cellAspect===n)return;if(this.textFrame={grid:this.currentGrid,width:this.width,height:this.height,cellAspect:n},e.clear(fi),t===0||this.width<=0||this.height<=0)return;this.releaseArtworkImage();let s=this.height*2,o=U0(this.width,this.height,t,n),{columns:a,subrows:l}=o,c=Math.floor((this.width-a)/2),u=Math.floor((s-l)/2),d=this.currentGrid,{columnScale:f,subrowScale:g,sampleCount:A}=o,m=(b)=>{let w=b-u;if(w<0||w>=l)return-1;let p=Math.floor(w/g);return Math.min(t-1,Math.floor(p*t/A))};for(let b=0;b<this.height;b++){let w=m(b*2),p=m(b*2+1);for(let C=0;C<a;C++){let _=Math.floor(C/f),y=Math.min(t-1,Math.floor(_*t/A)),v=w<0?fi:Zt(d[w]?.[y],y,w),x=p<0?fi:Zt(d[p]?.[y],y,p);e.setCell(c+C,b,"\u2580",v,x)}}}drawArtworkImage(e,t,r,n){let i=j0(this.width,this.height,t,r,n),s=this.artworkImageCache;if(!(this.artworkImage&&s&&s.grid===this.currentGrid&&s.sampleCount===i.sampleCount&&s.side===i.side&&s.pixelWidth===i.pixelWidth)){let a=new Uint8Array(i.sampleCount**2*4);for(let f=0;f<i.sampleCount;f++){let g=Math.min(t-1,Math.floor(f*t/i.sampleCount));for(let A=0;A<i.sampleCount;A++){let m=Math.min(t-1,Math.floor(A*t/i.sampleCount)),[b,w,p]=Zt(this.currentGrid[g]?.[m],m,g).toInts(),C=(f*i.sampleCount+A)*4;a[C]=b,a[C+1]=w,a[C+2]=p,a[C+3]=255}}let l=N0.fromRgba(a,i.sampleCount,i.sampleCount),c=l.resize({width:i.side,height:i.side,kernel:"nearest"});l.dispose();let u=i.pixelWidth-i.side,d=u>0?c.extend({left:u,background:fi.toInts()}):c;if(d!==c)c.dispose();this.releaseArtworkImage(),this.artworkImage=d,this.artworkImageCache={grid:this.currentGrid,sampleCount:i.sampleCount,side:i.side,pixelWidth:i.pixelWidth}}if(!this.artworkImage)return;e.drawImage(this.artworkImage,Math.floor((this.width-i.columns)/2),Math.floor((this.height-i.rows)/2),i.columns,i.rows,i.pixelWidth,i.side,0,0,i.pixelWidth,i.side,"auto")}releaseArtworkImage(){this.artworkImage?.dispose(),this.artworkImage=null,this.artworkImageCache=null}destroySelf(){this.releaseArtworkImage(),super.destroySelf()}}Yt({artwork_preview:_a});var Ca=[16,32,64],jd=74,Hd=2;function xa(e,t){let r=Fn(e),n=ht[t];return r.palette=[...n.colors],r.activeColor=r.palette[0],r}function Ea(e,t){let r=e.name.toLowerCase(),n=Number(r)-1;if(r==="escape")return{kind:"cancel"};if(Number.isInteger(n)&&Ca[n])return{kind:"size",size:Ca[n]};let i=xr(r);if(i)return{kind:"palette",delta:i.dx+i.dy*t};if(hr(e))return{kind:"create"}}function K0(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function Kd(e,t){if(e.length<=t)return e;return`${e.slice(0,Math.max(1,t-1))}\u2026`}function W0(e){return kn(Ao(e.palette,e.grid),e.paletteSaturation,e.paletteLightness)}function Sa(e,t){return Math.max(0,Math.min(ht.length-1,e+t))}function Gs(e){return Math.max(1,Math.min(jd,e-4))>=64?2:1}function Ia(e){let t=J(()=>Math.max(1,Math.min(jd,e.width-4))),r=J(()=>Math.max(1,Math.min(19,e.height-2))),n=J(()=>Gs(e.width)),i=J(()=>r()>=12?1:0),s=J(()=>Math.max(1,r()-7-i()*2)),o=J(()=>s()*n()),a=J(()=>Math.floor(e.selectedPalette/o())*o()),l=J(()=>{let g=a();return ht.slice(g,g+o()).map((A,m)=>({palette:A,index:g+m}))}),c=J(()=>K0(l(),n())),u=J(()=>Math.max(1,Math.floor((t()-4-(n()-1))/n()))),d=J(()=>Math.max(3,Math.min(10,u()-8))),f=J(()=>Math.max(1,u()-d()-4));return(()=>{var g=I("box"),A=I("box"),m=I("box"),b=I("text"),w=I("box"),p=I("text"),C=Ee("Choose a palette | "),_=I("box"),y=I("box"),v=I("text");return T(g,A),h(g,"id","new-artwork-modal"),h(g,"position","absolute"),h(g,"zIndex",30),h(g,"border",!0),h(g,"title"," New artwork "),h(g,"flexDirection","column"),T(A,m),T(A,w),T(A,p),T(A,_),T(A,y),T(A,v),h(A,"flexGrow",1),h(A,"width","100%"),h(A,"padding",1),h(A,"flexDirection","column"),T(m,b),h(m,"height",1),h(m,"flexDirection","row"),h(m,"gap",1),T(b,Ee("Grid size")),L(m,Z(vt,{each:Ca,children:(x,B)=>{let M=()=>x<=e.maxSize,P=()=>x===e.selectedSize;return(()=>{var O=I("box"),W=I("text"),Q=Ee(" "),j=Ee("\xD7");return T(O,W),h(O,"height",1),h(O,"paddingX",1),h(O,"onMouseDown",()=>e.onSelectSize(x)),T(W,Q),T(W,j),L(W,()=>B()+1,Q),L(W,x,j),L(W,x,null),he((ee)=>{var ie=P()?E.panelActive:E.panel,z=M()?P()?E.accentText:E.muted:E.border;return ie!==ee.e&&(ee.e=h(O,"backgroundColor",ie,ee.e)),z!==ee.t&&(ee.t=h(W,"fg",z,ee.t)),ee},{e:void 0,t:void 0}),O})()}}),null),T(p,C),L(p,()=>ht[e.selectedPalette].name,null),L(A,Z(vt,{get each(){return c()},children:(x)=>(()=>{var B=I("box");return h(B,"height",1),h(B,"flexDirection","row"),h(B,"gap",1),L(B,Z(vt,{each:x,children:(M)=>{let P=()=>M.index===e.selectedPalette;return(()=>{var O=I("box"),W=I("text"),Q=I("box");return T(O,W),T(O,Q),h(O,"height",1),h(O,"paddingX",1),h(O,"flexDirection","row"),h(O,"justifyContent","space-between"),h(O,"onMouseDown",()=>e.onSelectPalette(M.index)),L(W,()=>Kd(M.palette.name,f())),h(Q,"height",1),h(Q,"flexDirection","row"),L(Q,Z(vt,{get each(){return M.palette.colors.slice(0,d())},children:(j)=>(()=>{var ee=I("text");return T(ee,Ee("\u25A0")),he((ie)=>h(ee,"fg",Ye(j),ie)),ee})()})),he((j)=>{var ee=u(),ie=P()?E.panelActive:E.panel,z=P()?E.text:E.muted;return ee!==j.e&&(j.e=h(O,"width",ee,j.e)),ie!==j.t&&(j.t=h(O,"backgroundColor",ie,j.t)),z!==j.a&&(j.a=h(W,"fg",z,j.a)),j},{e:void 0,t:void 0,a:void 0}),O})()}})),B})()}),_),h(y,"flexGrow",1),L(v,()=>e.message||"1\u20133 size \xB7 arrows palette \xB7 Enter create \xB7 Esc cancel"),he((x)=>{var B=Math.max(0,Math.floor((e.width-t())/2)),M=Math.max(0,Math.floor((e.height-r())/2)),P=t(),O=r(),W=E.border,Q=E.accent,j=E.panel,ee=E.textPink,ie=i(),z=E.textPink,Be=i(),Pe=e.message?E.warning:E.textPink;return B!==x.e&&(x.e=h(g,"left",B,x.e)),M!==x.t&&(x.t=h(g,"top",M,x.t)),P!==x.a&&(x.a=h(g,"width",P,x.a)),O!==x.o&&(x.o=h(g,"height",O,x.o)),W!==x.i&&(x.i=h(g,"borderColor",W,x.i)),Q!==x.n&&(x.n=h(g,"titleColor",Q,x.n)),j!==x.s&&(x.s=h(A,"backgroundColor",j,x.s)),ee!==x.h&&(x.h=h(b,"fg",ee,x.h)),ie!==x.r&&(x.r=h(w,"height",ie,x.r)),z!==x.d&&(x.d=h(p,"fg",z,x.d)),Be!==x.l&&(x.l=h(_,"height",Be,x.l)),Pe!==x.u&&(x.u=h(v,"fg",Pe,x.u)),x},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0}),g})()}function Y0(e){let t=J(()=>Fd(e.artwork)),r=J(()=>W0(e.artwork)),n=()=>e.selected()===e.index,i=()=>e.cardWidth-2;return(()=>{var s=I("box"),o=I("box"),a=I("box"),l=I("artwork_preview"),c=I("box"),u=I("text"),d=I("text"),f=I("text"),g=I("box"),A=I("box");return T(s,o),T(s,d),T(s,f),T(s,g),T(s,A),h(s,"flexDirection","column"),T(o,a),h(o,"width","100%"),h(o,"height","100%"),h(o,"border",!0),h(o,"borderColor","transparent"),h(o,"flexDirection","column"),T(a,l),T(a,c),T(a,u),h(a,"flexGrow",1),h(a,"width","100%"),h(a,"flexDirection","column"),h(a,"paddingX",1),h(l,"flexGrow",1),h(l,"width","100%"),h(c,"height",1),h(c,"width","100%"),h(c,"flexDirection","row"),h(c,"gap",1),h(c,"overflow","hidden"),L(c,Z(vt,{get each(){return r()},children:(m)=>Z(Un,{get color(){return Ye(m)},get background(){return E.panel},width:1,shape:"circle"})})),L(u,()=>Kd(e.artwork.filename,e.cardWidth-3)),h(d,"position","absolute"),h(d,"left",1),h(d,"top",0),h(d,"height",1),h(d,"zIndex",1),L(d,()=>"\u2580".repeat(i())),h(f,"position","absolute"),h(f,"left",1),h(f,"height",1),h(f,"zIndex",1),L(f,()=>"\u2584".repeat(i())),h(g,"position","absolute"),h(g,"left",0),h(g,"top",0),h(g,"width",1),h(g,"height","100%"),h(g,"zIndex",2),h(A,"position","absolute"),h(A,"top",0),h(A,"width",1),h(A,"height","100%"),h(A,"zIndex",2),he((m)=>{var b=`artwork-card-${e.artwork.id}`,w=e.cardWidth,p=e.cardHeight,C=E.card,_=e.onSelect,y=E.card,v=E.panel,x=`artwork-preview-${e.artwork.id}`,B=t(),M=E.textPink,P=`artwork-card-selection-top-${e.artwork.id}`,O=i(),W=n()?E.orangeActive:E.card,Q=E.panel,j=`artwork-card-selection-bottom-${e.artwork.id}`,ee=e.cardHeight-1,ie=i(),z=n()?E.orangeActive:E.card,Be=E.panel,Pe=`artwork-card-selection-side-${e.artwork.id}`,Je=n()?E.orangeActive:E.card,ze=e.cardWidth-1,pe=n()?E.orangeActive:E.card;return b!==m.e&&(m.e=h(s,"id",b,m.e)),w!==m.t&&(m.t=h(s,"width",w,m.t)),p!==m.a&&(m.a=h(s,"height",p,m.a)),C!==m.o&&(m.o=h(s,"backgroundColor",C,m.o)),_!==m.i&&(m.i=h(s,"onMouseDown",_,m.i)),y!==m.n&&(m.n=h(o,"backgroundColor",y,m.n)),v!==m.s&&(m.s=h(a,"backgroundColor",v,m.s)),x!==m.h&&(m.h=h(l,"id",x,m.h)),B!==m.r&&(m.r=h(l,"grid",B,m.r)),M!==m.d&&(m.d=h(u,"fg",M,m.d)),P!==m.l&&(m.l=h(d,"id",P,m.l)),O!==m.u&&(m.u=h(d,"width",O,m.u)),W!==m.c&&(m.c=h(d,"fg",W,m.c)),Q!==m.w&&(m.w=h(d,"bg",Q,m.w)),j!==m.m&&(m.m=h(f,"id",j,m.m)),ee!==m.f&&(m.f=h(f,"top",ee,m.f)),ie!==m.y&&(m.y=h(f,"width",ie,m.y)),z!==m.g&&(m.g=h(f,"fg",z,m.g)),Be!==m.p&&(m.p=h(f,"bg",Be,m.p)),Pe!==m.b&&(m.b=h(g,"id",Pe,m.b)),Je!==m.T&&(m.T=h(g,"backgroundColor",Je,m.T)),ze!==m.A&&(m.A=h(A,"left",ze,m.A)),pe!==m.O&&(m.O=h(A,"backgroundColor",pe,m.O)),m},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0,u:void 0,c:void 0,w:void 0,m:void 0,f:void 0,y:void 0,g:void 0,p:void 0,b:void 0,T:void 0,A:void 0,O:void 0}),s})()}function ka(e){let t=gt(),r=Hr(),[n,i]=Y([]),[s,o]=Y(0),[a,l]=Y(!0),[c,u]=Y("Loading saved artworks\u2026"),[d,f]=Y(null),[g,A]=Y(!1),[m,b]=Y(16),[w,p]=Y(0),[C,_]=Y(""),y=J(()=>{let F=Math.max(8,r().width-2);return Math.min(28,F,Math.max(12,Math.floor(F/3)))}),v=J(()=>{let F=r().height<18?7:r().height<25?9:12;return Math.max(4,Math.min(F,r().height-6))}),x=J(()=>Math.max(1,Math.floor((r().width-2)/(y()+Hd)))),B=J(()=>x()*y()+Math.max(0,x()-1)*Hd),M=J(()=>Math.max(1,Math.floor((r().height-5)/(v()+1)))),P=J(()=>x()*M()),O=J(()=>Math.floor(s()/P())),W=J(()=>O()*P()),Q=J(()=>{let F=W();return n().slice(F,F+P())});_i(()=>{let F=Math.max(0,n().length-1);if(s()>F)o(F)});let j=0;je(()=>{j++});let ee=async()=>{let F=++j;l(!0),u("Loading saved artworks\u2026");try{let U=await e.repository.listArtworks();if(F!==j)return;i(U),u(U.length===0?"No saved artworks yet":`${U.length} saved artwork${U.length===1?"":"s"}`)}catch(U){if(F!==j)return;u(`Load failed: ${U instanceof Error?U.message:String(U)}`)}finally{if(F===j)l(!1)}};br(()=>void ee());let ie=(F,U)=>{let ae=n().length;if(ae===0)return;let se=Math.max(0,Math.min(ae-1,s()+F+U*x()));o(se),u(n()[se].filename)},z=()=>{let F=n()[s()];if(!F)return;f({artwork:F,session:new Jt(Gd(F))})},Be=()=>{b(16),p(0),_(""),A(!0),u("Choose a size and palette")},Pe=()=>{A(!1),_(""),u("New artwork cancelled")},Je=(F)=>{if(F>e.repository.maxCanvasSize){_(`${F}\xD7${F} is unavailable on this plan`);return}b(F),_("")},ze=(F)=>{p((U)=>Sa(U,F)),_("")},pe=()=>{A(!1),f({artwork:null,session:new Jt(xa(m(),w()))})},te=async(F)=>{let U=d();if(!U)throw Error("No artwork is open");let ae=U.artwork?await e.repository.saveArtwork(U.artwork,F):await e.repository.createArtwork(F);if(j++,l(!1),i((se)=>se.some((be)=>be.id===ae.id)?se.map((be)=>be.id===ae.id?ae:be):[ae,...se]),!U.artwork)o(0);return f((se)=>se===U?{...se,artwork:ae}:se),e.variant==="local"?"Saved locally":"Saved to Flatblox cloud"},q=async()=>{u("Signing out\u2026");try{await e.repository.signOut(),t.destroy()}catch(F){u(`Sign out failed: ${F instanceof Error?F.message:String(F)}`)}};return jr((F)=>{if(F.eventType==="release"||d())return;let U=F.name.toLowerCase();if(g()){let se=Ea(F,Gs(r().width));if(se?.kind==="cancel")Pe();else if(se?.kind==="size")Je(se.size);else if(se?.kind==="palette")ze(se.delta);else if(se?.kind==="create")pe();return}let ae=xr(U);if(F.ctrl&&U==="c")t.destroy();else if(U==="escape"&&e.onBack)e.onBack();else if(U==="q"||U==="escape")t.destroy();else if(ae)ie(ae.dx,ae.dy);else if(U==="n")Be();else if(hr(F))z();else if(U==="r")ee();else if(U==="o"&&e.variant!=="local")q()}),Z(Ie,{get when(){return d()},get fallback(){return(()=>{var F=I("box"),U=I("box"),ae=I("box"),se=I("text"),Ne=I("b"),be=I("box"),rt=I("box"),qe=I("text"),Le=I("box"),Fe=I("box"),Rt=I("text"),H=I("text");return T(F,U),T(F,Le),T(F,Fe),h(F,"width","100%"),h(F,"height","100%"),h(F,"flexDirection","column"),T(U,ae),T(U,be),T(U,rt),h(U,"height",3),h(U,"paddingY",1),h(U,"paddingX",1),h(U,"flexDirection","row"),T(ae,se),h(ae,"height",1),h(ae,"flexBasis",0),h(ae,"flexGrow",1),h(ae,"flexDirection","row"),T(se,Ne),L(Ne,es),h(be,"height",1),h(be,"flexBasis",0),h(be,"flexGrow",1),h(be,"flexDirection","row"),h(be,"justifyContent","center"),L(be,Z(zr,{id:"dashboard-wordmark",width:14,height:1,get backgroundColor(){return E.panel},get foregroundColor(){return E.accent}})),T(rt,qe),h(rt,"height",1),h(rt,"flexBasis",0),h(rt,"flexGrow",1),h(rt,"flexDirection","row"),h(rt,"justifyContent","flex-end"),L(qe,()=>e.repository.username),h(Le,"id","dashboard-content"),h(Le,"flexGrow",1),h(Le,"flexDirection","column"),h(Le,"justifyContent","center"),h(Le,"padding",1),L(Le,Z(Ie,{get when(){return ut(()=>!a())()&&n().length>0},get fallback(){return(()=>{var S=I("box"),fe=I("text");return T(S,fe),h(S,"flexGrow",1),h(S,"alignItems","center"),h(S,"justifyContent","center"),L(fe,c),he((Ge)=>h(fe,"fg",E.muted,Ge)),S})()},get children(){var S=I("box");return h(S,"id","artwork-grid"),h(S,"alignSelf","center"),h(S,"flexDirection","row"),h(S,"flexWrap","wrap"),h(S,"rowGap",1),h(S,"columnGap",2),L(S,Z(vt,{get each(){return Q()},children:(fe,Ge)=>Z(Y0,{artwork:fe,get index(){return W()+Ge()},selected:s,get cardWidth(){return y()},get cardHeight(){return v()},onSelect:()=>o(W()+Ge())})})),he((fe)=>h(S,"width",B(),fe)),S}})),T(Fe,Rt),T(Fe,H),h(Fe,"height",1),h(Fe,"paddingX",1),h(Fe,"flexDirection","row"),h(Fe,"justifyContent","space-between"),L(Rt,c),L(H,()=>e.variant==="local"?"N new | arrows move | Enter edit | R refresh | Esc back | Q quit":"N new | arrows move | Enter edit | R refresh | O sign out | Q quit"),L(F,Z(Ie,{get when(){return g()},get children(){return Z(Ia,{get width(){return r().width},get height(){return r().height},get selectedPalette(){return w()},get selectedSize(){return m()},get maxSize(){return e.repository.maxCanvasSize},get message(){return C()},onSelectPalette:(S)=>{p(S),_("")},onSelectSize:Je})}}),null),he((S)=>{var fe=E.background,Ge=E.panel,At=E.accentText,De=E.muted,lt=E.panel,et=E.panelActive,pt=c().startsWith("Load failed")?E.warning:E.textPink,re=E.muted;return fe!==S.e&&(S.e=h(F,"backgroundColor",fe,S.e)),Ge!==S.t&&(S.t=h(U,"backgroundColor",Ge,S.t)),At!==S.a&&(S.a=h(se,"fg",At,S.a)),De!==S.o&&(S.o=h(qe,"fg",De,S.o)),lt!==S.i&&(S.i=h(Le,"backgroundColor",lt,S.i)),et!==S.n&&(S.n=h(Fe,"backgroundColor",et,S.n)),pt!==S.s&&(S.s=h(Rt,"fg",pt,S.s)),re!==S.h&&(S.h=h(H,"fg",re,S.h)),S},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),F})()},children:(F)=>Z(qr,{get session(){return F().session},saveDocument:te,get promptForFilenameOnSave(){return!F().artwork},onBack:()=>{f(null),u("Returned from editor")}})})}import{readdir as Q0,readFile as J0,stat as Wd}from"fs/promises";import{basename as V0,join as Yd,resolve as Z0}from"path";function Qd(e,t,r,n){let i=t.draft?.data.createdAt;if(typeof i==="string"&&Number.isFinite(Date.parse(i)))r=new Date(i);return{id:e,filename:t.filename,size:t.grid.length,grid:t.grid,palette:t.palette,paletteSaturation:t.paletteColorAdjustment?.saturation??0,paletteLightness:t.paletteColorAdjustment?.lightness??0,artboards:[],activeArtboard:t.draft?.activeArtboard??0,createdAt:r.toISOString(),updatedAt:n.toISOString(),activeColor:t.activeColor,draft:t.draft}}function $0(e){return e.replace(/[\\/]/g,"-").replace(/^\.+$/,"")||"untitled"}function X0(e){return typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string"&&e.code!=="ENOENT"}function z0(e=process.env,t=process.cwd()){return e.INIT_CWD||e.PWD||t}class Ra{username;maxCanvasSize=64;directory;constructor(e=z0()){this.directory=Z0(e),this.username=V0(this.directory)||"Local"}async listArtworks(){let e=await Q0(this.directory,{withFileTypes:!0}),t=[];for(let r=0;r<e.length;r+=16)t.push(...await Promise.all(e.slice(r,r+16).map(async(n)=>{if(!n.isFile()||!n.name.endsWith(".flatblox.json"))return null;let i=Yd(this.directory,n.name);try{let s=Mn(await J0(i,"utf8")),o=await Wd(i),a=o.birthtimeMs>0?o.birthtime:o.mtime;return Qd(i,s,a,o.mtime)}catch(s){if(X0(s))throw s;return null}})));return t.filter((r)=>r!==null).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}async createArtwork(e){let t=Yd(this.directory,`${$0(e.filename)}.flatblox.json`);try{return await this.writeArtwork(t,e,!0)}catch(r){if(r.code==="EEXIST")throw Error(`A local artwork named ${e.filename} already exists`);throw r}}async saveArtwork(e,t){return this.writeArtwork(e.id,t,!1,e.createdAt)}async signOut(){}async writeArtwork(e,t,r=!1,n=new Date().toISOString()){let i={...t,draft:{data:{...t.draft?.data,createdAt:n},activeArtboard:t.draft?.activeArtboard??0}};await $r(e,Nn(i),r);let s=await Wd(e);return Qd(e,i,new Date(n),s.mtime)}}function Jd(e){let t=!1,r=gt(),n=Hr(),[i,s]=Y(0),[o,a]=Y(!1),[l,c]=Y(16),[u,d]=Y(0),[f,g]=Y(null),[A,m]=Y(null),[b,w]=Y(!1),p=e.cloudRepository,[C,_]=Y(p instanceof Promise?null:p??null);if(p instanceof Promise)p.then((te)=>{if(!t&&!C())_(te)},(te)=>{if(!t)P(te instanceof Error?te.message:String(te))});let[y,v]=Y(!1),[x,B]=Y(!1),[M,P]=Y(""),[O,W]=Y(""),Q=null,j=e.localRepository??new Ra,ee=()=>{Q?.abort(),Q=null,B(!1)};je(()=>{t=!0,ee()});let ie=()=>{ee(),w(!0)},z=()=>{ee(),c(16),d(0),a(!0)},Be=()=>{a(!1),m(null),g(new Jt(xa(l(),u())))},Pe=(te)=>{d((q)=>Sa(q,te))},Je=async()=>{if(x())return;let te=new AbortController;Q=te,B(!0),P(""),W("");try{let q=await e.onSignIn(te.signal,W);if(!te.signal.aborted)_(q),v(!0)}catch(q){if(!te.signal.aborted)P(q instanceof Error?q.message:String(q))}finally{if(Q===te)Q=null,B(!1)}},ze=(te)=>{s((q)=>Math.max(0,Math.min(2,q+te)))},pe=()=>{if(C())v(!0);else Je()};return jr((te)=>{if(te.eventType==="release"||f()||b()||y())return;let q=te.name.toLowerCase();if(x()){if(q==="escape"||q==="q"||te.ctrl&&q==="c")ee();return}if(o()){let U=Ea(te,Gs(n().width));if(U?.kind==="cancel")a(!1);else if(U?.kind==="size")c(U.size);else if(U?.kind==="palette")Pe(U.delta);else if(U?.kind==="create")Be();return}let F=xr(q);if(te.ctrl&&q==="c")r.destroy();else if(q==="q"||q==="escape")r.destroy();else if(F?.dy)ze(F.dy);else if(q==="n")z();else if(q==="l")ie();else if(q==="s"||q==="d")pe();else if(hr(te))if(i()===0)z();else if(i()===1)ie();else pe()}),Z(Ie,{get when(){return ut(()=>!!y())()?C():null},get fallback(){return Z(Ie,{get when(){return f()},get fallback(){return Z(Ie,{get when(){return b()},get fallback(){return(()=>{var te=I("box"),q=I("box"),F=I("box"),U=I("box"),ae=I("box"),se=I("text"),Ne=I("box"),be=I("box"),rt=I("text"),qe=I("box"),Le=I("box"),Fe=I("text"),Rt=I("box"),H=I("text");return T(te,q),h(te,"width","100%"),h(te,"height","100%"),h(te,"alignItems","center"),h(te,"justifyContent","center"),T(q,F),T(q,U),T(q,Ne),T(q,qe),T(q,Rt),T(q,H),h(q,"flexDirection","column"),h(q,"alignItems","center"),L(q,Z(zr,{id:"welcome-wordmark",width:32,height:2,get backgroundColor(){return E.background},get foregroundColor(){return E.accent}}),F),h(F,"height",3),T(U,ae),h(U,"id","welcome-new-artwork"),h(U,"width",36),h(U,"height",3),h(U,"border",!0),h(U,"onMouseDown",()=>{s(0),z()}),T(ae,se),h(ae,"width","100%"),h(ae,"height","100%"),h(ae,"alignItems","center"),h(ae,"justifyContent","center"),T(se,Ee("New artwork")),h(se,"id","welcome-new-artwork-label"),T(Ne,be),h(Ne,"id","welcome-load-artwork"),h(Ne,"width",36),h(Ne,"height",3),h(Ne,"border",!0),h(Ne,"onMouseDown",()=>{s(1),ie()}),T(be,rt),h(be,"width","100%"),h(be,"height","100%"),h(be,"alignItems","center"),h(be,"justifyContent","center"),T(rt,Ee("Load artwork")),h(rt,"id","welcome-load-artwork-label"),T(qe,Le),h(qe,"id","welcome-sign-in"),h(qe,"width",36),h(qe,"height",3),h(qe,"border",!0),h(qe,"onMouseDown",()=>{s(2),pe()}),T(Le,Fe),h(Le,"width","100%"),h(Le,"height","100%"),h(Le,"alignItems","center"),h(Le,"justifyContent","center"),h(Fe,"id","welcome-sign-in-label"),L(Fe,()=>C()?"Dashboard":"Sign in"),h(Rt,"height",2),L(H,(()=>{var S=ut(()=>!!x());return()=>S()?ut(()=>!!O())()?`Open this URL: ${O()} \xB7 Esc cancel`:"Complete sign-in in your browser \xB7 Esc cancel":M()||"\u2191/\u2193 select \xB7 Enter open \xB7 Q quit"})()),L(te,Z(Ie,{get when(){return o()},get children(){return Z(Ia,{get width(){return n().width},get height(){return n().height},get selectedPalette(){return u()},get selectedSize(){return l()},maxSize:64,message:"",onSelectPalette:d,onSelectSize:c})}}),null),he((S)=>{var fe=E.background,Ge=O()?Math.max(36,n().width-4):36,At=i()===0?E.accent:E.border,De=i()===0?E.textPink:E.text,lt=i()===1?E.accent:E.border,et=i()===1?E.textPink:E.text,pt=i()===2?E.accent:E.border,re=i()===2?E.textPink:E.text,Oe=M()?E.warning:E.muted;return fe!==S.e&&(S.e=h(te,"backgroundColor",fe,S.e)),Ge!==S.t&&(S.t=h(q,"width",Ge,S.t)),At!==S.a&&(S.a=h(U,"borderColor",At,S.a)),De!==S.o&&(S.o=h(se,"fg",De,S.o)),lt!==S.i&&(S.i=h(Ne,"borderColor",lt,S.i)),et!==S.n&&(S.n=h(rt,"fg",et,S.n)),pt!==S.s&&(S.s=h(qe,"borderColor",pt,S.s)),re!==S.h&&(S.h=h(Fe,"fg",re,S.h)),Oe!==S.r&&(S.r=h(H,"fg",Oe,S.r)),S},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0}),te})()},get children(){return Z(ka,{repository:j,variant:"local",onBack:()=>w(!1)})}})},children:(te)=>Z(qr,{get session(){return te()},saveDocument:async(q)=>{let F=f(),U=A(),ae=U?await j.saveArtwork(U,q):await j.createArtwork(q);if(f()===F&&!t)m(ae);return"Saved locally"},get promptForFilenameOnSave(){return!A()},onBack:()=>{m(null),g(null)}})})},children:(te)=>Z(ka,{get repository(){return te()}})})}var Vd={backgroundColor:E.background,debounceDelay:1,exitOnCtrlC:!1,targetFps:60,useKittyKeyboard:{events:!0,allKeysAsEscapes:!0}};async function q0(e){let t=Ed(),r=kd(t);if(e){try{if(await ba(r,t.authFile))await r.auth.signOut()}finally{await r.auth.stopAutoRefresh(),await fn(t.authFile)}process.stdout.write(`Signed out of Flatblox TUI.
85
+ `);return}let n=Id(r,t.authFile,(s)=>{console.error("Could not persist sign-in:",s instanceof Error?s.message:String(s))}),i=async(s)=>{let{data:o,error:a}=await r.auth.getUser(s);if(a||!o.user){if(!a||pa(a))await fn(t.authFile);throw Error(a?.message??"Could not verify the Supabase session")}let{data:l,error:c}=await r.from("profiles").select("username, tier").eq("id",o.user.id).maybeSingle();if(c)throw Error(c.message);return new va(r,o.user.id,l?.username?.trim()||"Flatblox account",Sl[l?.tier??"tier0"],()=>fn(t.authFile))};try{let s=ba(r,t.authFile).then((o)=>o?i(o.access_token):null);s.catch(()=>{}),await Ud(()=>Z(Jd,{cloudRepository:s,onSignIn:async(o,a)=>{let l=await Rd({dashboardUrl:t.dashboardUrl,announce:a,signal:o});o.throwIfAborted();let c=await Td(r,l);return o.throwIfAborted(),await Ms(t.authFile,c),o.throwIfAborted(),i(c.access_token)}}),Vd)}finally{await n()}}async function eb(e){let t=await Pd(e);if(e.exportFormats){let r=await Hi(t.session.toDocument(),Hn(t.filePath,t.session.filename),e.exportFormats);process.stdout.write(`${r.join(`
86
86
  `)}
87
- `);return}await Xs(()=>Q(Zr,{get session(){return t.session},get filePath(){return t.filePath}}),Od)}async function B0(){try{let e=pd(Bun.argv.slice(2));if(e.help){process.stdout.write(`${na}
88
- `);return}if(e.mode==="cloud")await R0(e.logout);else await T0(e)}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`flatblox-tui: ${t}
87
+ `);return}await Si(()=>Z(qr,{get session(){return t.session},get filePath(){return t.filePath}}),Vd)}async function tb(){try{let e=Bd(Bun.argv.slice(2));if(e.help){process.stdout.write(`${wa}
88
+ `);return}if(e.mode==="cloud")await q0(e.logout);else await eb(e)}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`flatblox-tui: ${t}
89
89
 
90
- ${na}
91
- `),process.exitCode=1}}await B0();
90
+ ${wa}
91
+ `),process.exitCode=1}}await tb();