flatblox-tui 0.2.8 → 0.2.10

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 Zd=Object.create;var{getPrototypeOf:$d,defineProperty:Oa,getOwnPropertyNames:Xd}=Object;var zd=Object.prototype.hasOwnProperty;function qd(e){return this[e]}var eh,th,rh=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var i=t?eh??=new WeakMap:th??=new WeakMap,s=i.get(e);if(s)return s}r=e!=null?Zd($d(e)):{};let o=t||!e||!e.__esModule?Oa(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Xd(e))if(!zd.call(o,a))Oa(o,a,{get:qd.bind(e,a),enumerable:!0})}if(n)i.set(e,o);return o};var nh=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var zc=nh(function(Ex,zi){var xc,Ec,Sc,Ic,kc,Rc,Tc,Bc,Oc,Pc,Dc,Mc,Nc,$i,Fo,Lc,Fc,Gc,qr,Uc,Hc,jc,Kc,Wc,Yc,Qc,Jc,Vc,Xi,Zc,$c,Xc;(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 zi==="object"&&typeof Ex==="object")e(r(t,r(Ex)));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]};xc=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)},Ec=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},Sc=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},Ic=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},kc=function(s,o){return function(a,l){o(a,l,s)}},Rc=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,m=f==="getter"?"get":f==="setter"?"set":"value",A=!o&&s?l.static?s:s.prototype:null,g=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:g.get,set:g.set}:g[m],C);if(f==="accessor"){if(y===void 0)continue;if(y===null||typeof y!=="object")throw TypeError("Object expected");if(b=d(y.get))g.get=b;if(b=d(y.set))g.set=b;if(b=d(y.init))c.unshift(b)}else if(b=d(y))if(f==="field")c.unshift(b);else g[m]=b}if(A)Object.defineProperty(A,l.name,g);w=!0},Tc=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},Bc=function(s){return typeof s==="symbol"?s:"".concat(s)},Oc=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})},Pc=function(s,o){if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(s,o)},Dc=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(g){try{A(l.next(g))}catch(b){d(b)}}function m(g){try{A(l.throw(g))}catch(b){d(b)}}function A(g){g.done?u(g.value):c(g.value).then(f,m)}A((l=l.apply(s,o||[])).next())})},Mc=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(g){return m([A,g])}}function m(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(g){A=[6,g],c=0}finally{l=u=0}if(A[0]&5)throw A[1];return{value:A[0]?A[1]:void 0,done:!0}}},Nc=function(s,o){for(var a in s)if(a!=="default"&&!Object.prototype.hasOwnProperty.call(o,a))Xi(o,s,a)},Xi=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]},$i=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.")},Fo=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},Lc=function(){for(var s=[],o=0;o<arguments.length;o++)s=s.concat(Fo(arguments[o]));return s},Fc=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},Gc=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))},qr=function(s){return this instanceof qr?(this.v=s,this):new qr(s)},Uc=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||m(p,_)})},C)c[p]=C(c[p])}}function m(p,C){try{A(l[p](C))}catch(_){w(u[0][3],_)}}function A(p){p.value instanceof qr?Promise.resolve(p.value.v).then(g,b):w(u[0][2],p)}function g(p){m("next",p)}function b(p){m("throw",p)}function w(p,C){if(p(C),u.shift(),u.length)m(u[0][0],u[0][1])}},Hc=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:qr(s[c](d)),done:!1}:u?u(d):d}:u}},jc=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 $i==="function"?$i(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,m){d=s[u](d),c(f,m,d.done,d.value)})}}function c(u,d,f,m){Promise.resolve(m).then(function(A){u({value:A,done:f})},d)}},Kc=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)};Wc=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")Xi(o,s,a[l])}return r(o,s),o},Yc=function(s){return s&&s.__esModule?s:{default:s}},Qc=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)},Jc=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},Vc=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)},Zc=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};$c=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()},Xc=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",xc),e("__assign",Ec),e("__rest",Sc),e("__decorate",Ic),e("__param",kc),e("__esDecorate",Rc),e("__runInitializers",Tc),e("__propKey",Bc),e("__setFunctionName",Oc),e("__metadata",Pc),e("__awaiter",Dc),e("__generator",Mc),e("__exportStar",Nc),e("__createBinding",Xi),e("__values",$i),e("__read",Fo),e("__spread",Lc),e("__spreadArrays",Fc),e("__spreadArray",Gc),e("__await",qr),e("__asyncGenerator",Uc),e("__asyncDelegator",Hc),e("__asyncValues",jc),e("__makeTemplateObject",Kc),e("__importStar",Wc),e("__importDefault",Yc),e("__classPrivateFieldGet",Qc),e("__classPrivateFieldSet",Jc),e("__classPrivateFieldIn",Vc),e("__addDisposableResource",Zc),e("__disposeResources",$c),e("__rewriteRelativeImportExtension",Xc)})});import{CliRenderer as Th,createCliRenderer as Bh,engine as Oh}from"@opentui/core";import{createTestRenderer as hb}from"@opentui/core/testing";import{ASCIIFontRenderable as Ph,BoxRenderable as Dh,CodeRenderable as Mh,DiffRenderable as Nh,ImageRenderable as Lh,InputRenderable as Fh,LineNumberRenderable as Gh,MarkdownRenderable as Uh,ScrollBoxRenderable as Hh,SelectRenderable as jh,TabSelectRenderable as Kh,TextareaRenderable as Wh,TextAttributes as Ys,TextNodeRenderable as Yh,TextRenderable as Qh}from"@opentui/core";import{engine as gb,Timeline as mb}from"@opentui/core";var $e={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Pa(this.context.count)},getNextContextId(){return Pa(this.context.count++)}};function Pa(e){let t=String(e),r=t.length-1;return $e.context.id+(r?String.fromCharCode(96+r):"")+t}function Ns(e){$e.context=e}function ih(){return{...$e.context,id:$e.getNextContextId(),count:0}}var sh=!1,oh=(e,t)=>e===t,Ls=Symbol("solid-proxy"),ah=typeof Proxy==="function",lh=Symbol("solid-track"),Q0=Symbol("solid-dev-component"),yi={equals:oh},Da=null,Ga=Ya,mt=1,gn=2,Ua={owned:null,cleanups:null,context:null,owner:null};var ue=null,M=null,pn=null,Lr=null,_e=null,Ue=null,tt=null,vi=0;function pr(e,t){let r=_e,n=ue,i=e.length===0,s=t===void 0?n:t,o=i?Ua:{owned:null,cleanups:null,context:s?s.context:null,owner:s},a=i?e:()=>e(()=>pt(()=>sr(o)));ue=o,_e=null;try{return Ht(a,!0)}finally{_e=r,ue=n}}function j(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(M&&M.running&&M.sources.has(r))i=i(r.tValue);else i=i(r.value);return Wa(r,i)};return[Ka.bind(r),n]}function Tt(e,t,r){let n=Us(e,t,!1,mt);if(pn&&M&&M.running)Ue.push(n);else yn(n)}function _i(e,t,r){Ga=hh;let n=Us(e,t,!1,mt),i=Fs&&bn(Fs);if(i)n.suspense=i;if(!r||!r.render)n.user=!0;tt?tt.push(n):yn(n)}function K(e,t,r){r=r?Object.assign({},yi,r):yi;let n=Us(e,t,!0,0);if(n.observers=null,n.observerSlots=null,n.comparator=r.equals||void 0,pn&&M&&M.running)n.tState=mt,Ue.push(n);else yn(n);return Ka.bind(n)}function pt(e){if(!Lr&&_e===null)return e();let t=_e;_e=null;try{if(Lr)return Lr.untrack(e);return e()}finally{_e=t}}function br(e){_i(()=>pt(e))}function ot(e){if(ue===null);else if(ue.cleanups===null)ue.cleanups=[e];else ue.cleanups.push(e);return e}function ch(e){if(M&&M.running)return e(),M.done;let t=_e,r=ue;return Promise.resolve().then(()=>{_e=t,ue=r;let n;if(pn||Fs)n=M||(M={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 Ht(e,!1),_e=ue=null,n?n.done:void 0})}var[J0,Ma]=j(!1);function Ha(e,t){let r=Symbol("context");return{id:r,Provider:Ah(r),defaultValue:e}}function bn(e){let t;return ue&&ue.context&&(t=ue.context[e.id])!==void 0?t:e.defaultValue}function ja(e){let t=K(e),r=K(()=>Gs(t()));return r.toArray=()=>{let n=r();return Array.isArray(n)?n:n!=null?[n]:[]},r}var Fs;function Ka(){let e=M&&M.running;if(this.sources&&(e?this.tState:this.state))if((e?this.tState:this.state)===mt)yn(this);else{let t=Ue;Ue=null,Ht(()=>wi(this),!1),Ue=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&&M.sources.has(this))return this.tValue;return this.value}function Wa(e,t,r){let n=M&&M.running&&M.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(n,t)){if(M){let i=M.running;if(i||!r&&M.sources.has(e))M.sources.add(e),e.tValue=t;if(!i)e.value=t}else e.value=t;if(e.observers&&e.observers.length)Ht(()=>{for(let i=0;i<e.observers.length;i+=1){let s=e.observers[i],o=M&&M.running;if(o&&M.disposed.has(s))continue;if(o?!s.tState:!s.state){if(s.pure)Ue.push(s);else tt.push(s);if(s.observers)Qa(s)}if(!o)s.state=mt;else s.tState=mt}if(Ue.length>1e6)throw Ue=[],Error()},!1)}return t}function yn(e){if(!e.fn)return;sr(e);let t=vi;if(Na(e,M&&M.running&&M.sources.has(e)?e.tValue:e.value,t),M&&!M.running&&M.sources.has(e))queueMicrotask(()=>{Ht(()=>{M&&(M.running=!0),_e=ue=e,Na(e,e.tValue,t),_e=ue=null},!1)})}function Na(e,t,r){let n,i=ue,s=_e;_e=ue=e;try{n=e.fn(t)}catch(o){if(e.pure)if(M&&M.running)e.tState=mt,e.tOwned&&e.tOwned.forEach(sr),e.tOwned=void 0;else e.state=mt,e.owned&&e.owned.forEach(sr),e.owned=null;return e.updatedAt=r+1,Hs(o)}finally{_e=s,ue=i}if(!e.updatedAt||e.updatedAt<=r){if(e.updatedAt!=null&&"observers"in e)Wa(e,n,!0);else if(M&&M.running&&e.pure){if(!M.sources.has(e))e.value=n;M.sources.add(e),e.tValue=n}else e.value=n;e.updatedAt=r}}function Us(e,t,r,n=mt,i){let s={fn:e,state:n,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:ue,context:ue?ue.context:null,pure:r};if(M&&M.running)s.state=0,s.tState=n;if(ue===null);else if(ue!==Ua)if(M&&M.running&&ue.pure)if(!ue.tOwned)ue.tOwned=[s];else ue.tOwned.push(s);else if(!ue.owned)ue.owned=[s];else ue.owned.push(s);if(Lr&&s.fn){let o=s.fn,[a,l]=j(void 0,{equals:!1}),c=Lr.factory(o,l);ot(()=>c.dispose());let u,d=()=>ch(l).then(()=>{if(u)u.dispose(),u=void 0});s.fn=(f)=>{if(a(),M&&M.running){if(!u)u=Lr.factory(o,d);return u.track(f)}return c.track(f)}}return s}function mn(e){let t=M&&M.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===gn)return wi(e);if(e.suspense&&pt(e.suspense.inFallback))return e.suspense.effects.push(e);let r=[e];while((e=e.owner)&&(!e.updatedAt||e.updatedAt<vi)){if(t&&M.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(M.disposed.has(i))return}if((t?e.tState:e.state)===mt)yn(e);else if((t?e.tState:e.state)===gn){let i=Ue;Ue=null,Ht(()=>wi(e,r[0]),!1),Ue=i}}}function Ht(e,t){if(Ue)return e();let r=!1;if(!t)Ue=[];if(tt)r=!0;else tt=[];vi++;try{let n=e();return uh(r),n}catch(n){if(!r)tt=null;Ue=null,Hs(n)}}function uh(e){if(Ue){if(pn&&M&&M.running)dh(Ue);else Ya(Ue);Ue=null}if(e)return;let t;if(M){if(!M.promises.size&&!M.queue.size){let{sources:n,disposed:i}=M;tt.push.apply(tt,M.effects),t=M.resolve;for(let s of tt)"tState"in s&&(s.state=s.tState),delete s.tState;M=null,Ht(()=>{for(let s of i)sr(s);for(let s of n){if(s.value=s.tValue,s.owned)for(let o=0,a=s.owned.length;o<a;o++)sr(s.owned[o]);if(s.tOwned)s.owned=s.tOwned;delete s.tValue,delete s.tOwned,s.tState=0}Ma(!1)},!1)}else if(M.running){M.running=!1,M.effects.push.apply(M.effects,tt),tt=null,Ma(!0);return}}let r=tt;if(tt=null,r.length)Ht(()=>Ga(r),!1);if(t)t()}function Ya(e){for(let t=0;t<e.length;t++)mn(e[t])}function dh(e){for(let t=0;t<e.length;t++){let r=e[t],n=M.queue;if(!n.has(r))n.add(r),pn(()=>{n.delete(r),Ht(()=>{M.running=!0,mn(r)},!1),M&&(M.running=!1)})}}function hh(e){let t,r=0;for(t=0;t<e.length;t++){let n=e[t];if(!n.user)mn(n);else e[r++]=n}if($e.context){if($e.count){$e.effects||($e.effects=[]),$e.effects.push(...e.slice(0,r));return}Ns()}if($e.effects&&($e.done||!$e.count))e=[...$e.effects,...e],r+=$e.effects.length,delete $e.effects;for(t=0;t<r;t++)mn(e[t])}function wi(e,t){let r=M&&M.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===mt){if(i!==t&&(!i.updatedAt||i.updatedAt<vi))mn(i)}else if(s===gn)wi(i,t)}}}function Qa(e){let t=M&&M.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=gn;else n.state=gn;if(n.pure)Ue.push(n);else tt.push(n);n.observers&&Qa(n)}}}function sr(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--)sr(e.tOwned[t]);delete e.tOwned}if(M&&M.running&&e.pure)Ja(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)sr(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(M&&M.running)e.tState=0;else e.state=0}function Ja(e,t){if(!t)e.tState=0,M.disposed.add(e);if(e.owned)for(let r=0;r<e.owned.length;r++)Ja(e.owned[r])}function fh(e){if(e instanceof Error)return e;return Error(typeof e==="string"?e:"Unknown error",{cause:e})}function La(e,t,r){try{for(let n of t)n(e)}catch(n){Hs(n,r&&r.owner||null)}}function Hs(e,t=ue){let r=Da&&t&&t.context&&t.context[Da],n=fh(e);if(!r)throw n;if(tt)tt.push({fn(){La(n,r,t)},state:mt});else La(n,r,t)}function Gs(e){if(typeof e==="function"&&!e.length)return Gs(e());if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++){let n=Gs(e[r]);Array.isArray(n)?t.push.apply(t,n):t.push(n)}return t}return e}function Ah(e,t){return function(n){let i;return Tt(()=>i=pt(()=>(ue.context={...ue.context,[e]:n.value},ja(()=>n.children))),void 0),i}}var gh=Symbol("fallback");function Fa(e){for(let t=0;t<e.length;t++)e[t]()}function mh(e,t,r={}){let n=[],i=[],s=[],o=0,a=t.length>1?[]:null;return ot(()=>Fa(s)),()=>{let l=e()||[],c=l.length,u,d;return l[lh],pt(()=>{let m,A,g,b,w,p,C,_,y;if(c===0){if(o!==0)Fa(s),s=[],n=[],i=[],o=0,a&&(a=[]);if(r.fallback)n=[gh],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{g=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--,_--)g[_]=i[C],b[_]=s[C],a&&(w[_]=a[C]);m=new Map,A=Array(_+1);for(d=_;d>=p;d--)y=l[d],u=m.get(y),A[d]=u===void 0?-1:u,m.set(y,d);for(u=p;u<=C;u++)if(y=n[u],d=m.get(y),d!==void 0&&d!==-1)g[d]=i[u],b[d]=s[u],a&&(w[d]=a[u]),d=A[d],m.set(y,d);else s[u]();for(d=p;d<c;d++)if(d in g){if(i[d]=g[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(m){if(s[d]=m,a){let[A,g]=j(d);return a[d]=g,t(l[d],A)}return t(l[d])}}}var ph=!1;function Va(e,t){if(ph){if($e.context){let r=$e.context;Ns(ih());let n=pt(()=>e(t||{}));return Ns(r),n}}return pt(()=>e(t||{}))}function bi(){return!0}var bh={get(e,t,r){if(t===Ls)return r;return e.get(t)},has(e,t){if(t===Ls)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 Ms(e){return!(e=typeof e==="function"?e():e)?{}:e}function yh(){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&&Ls in a,e[o]=typeof a==="function"?(t=!0,K(a)):a}if(ah&&t)return new Proxy({get(o){for(let a=e.length-1;a>=0;a--){let l=Ms(e[a])[o];if(l!==void 0)return l}},has(o){for(let a=e.length-1;a>=0;a--)if(o in Ms(e[a]))return!0;return!1},keys(){let o=[];for(let a=0;a<e.length;a++)o.push(...Object.keys(Ms(e[a])));return[...new Set(o)]}},bh);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:yh.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 wh=(e)=>`Stale read from <${e}>.`;function bt(e){let t="fallback"in e&&{fallback:()=>e.fallback};return K(mh(()=>e.each,e.children,t||void 0))}function Te(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?pt(()=>s(t?i:()=>{if(!pt(n))throw wh("Show");return r()})):s}return e.fallback},void 0,void 0)}import{BaseRenderable as Al,createTextAttributes as $h,ImageRenderable as nl,InputRenderable as Qs,InputRenderableEvents as vn,isTextNodeRenderable as Xs,isEditBufferRenderable as Xh,parseColor as il,Renderable as zh,RootTextNodeRenderable as qh,ScrollBoxRenderable as ef,SelectRenderable as sl,SelectRenderableEvents as Js,TabSelectRenderable as ol,TabSelectRenderableEvents as Vs,TextNodeRenderable as tf,TextRenderable as gl}from"@opentui/core";var js,vh=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]]),Za=(js=String.fromCodePoint)!==null&&js!==void 0?js:(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 $a(e){var t;if(e>=55296&&e<=57343||e>1114111)return 65533;return(t=vh.get(e))!==null&&t!==void 0?t:e}function Xa(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 za=Xa("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd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YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");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 Ie;(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"})(Ie||(Ie={}));var qa=32;function Ks(e){return e>=Ie.ZERO&&e<=Ie.NINE}function _h(e){return e>=Ie.UPPER_A&&e<=Ie.UPPER_F||e>=Ie.LOWER_A&&e<=Ie.LOWER_F}function Ch(e){return e>=Ie.UPPER_A&&e<=Ie.UPPER_Z||e>=Ie.LOWER_A&&e<=Ie.LOWER_Z||Ks(e)}function xh(e){return e===Ie.EQUALS||Ch(e)}var Qe;(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"})(Qe||(Qe={}));var jt;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(jt||(jt={}));class Ws{constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r,this.state=Qe.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=jt.Strict,this.runConsumed=0}startEntity(e){this.decodeMode=e,this.state=Qe.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case Qe.EntityStart:{if(e.charCodeAt(t)===Ie.NUM)return this.state=Qe.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=Qe.NamedEntity,this.stateNamedEntity(e,t)}case Qe.NumericStart:return this.stateNumericStart(e,t);case Qe.NumericDecimal:return this.stateNumericDecimal(e,t);case Qe.NumericHex:return this.stateNumericHex(e,t);case Qe.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|qa)===Ie.LOWER_X)return this.state=Qe.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=Qe.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){while(t<e.length){let r=e.charCodeAt(t);if(Ks(r)||_h(r)){let n=r<=Ie.NINE?r-Ie.ZERO:(r|qa)-Ie.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(Ks(r))this.result=this.result*10+(r-Ie.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===Ie.SEMI)this.consumed+=1;else if(this.decodeMode===jt.Strict)return 0;if(this.emitCodePoint($a(this.result),this.consumed),this.errors){if(e!==Ie.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===Ie.SEMI&&i!==0&&(n&rt.FLAG13)!==0)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.treeIndex=Sh(r,n,this.treeIndex+Math.max(1,i),s),this.treeIndex<0)return this.result===0||this.decodeMode===jt.Attribute&&(i===0||xh(s))?0:this.emitNotTerminatedNamedEntity();if(n=r[this.treeIndex],i=(n&rt.VALUE_LENGTH)>>14,i!==0){if(s===Ie.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);if(this.decodeMode!==jt.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 Qe.NamedEntity:return this.result!==0&&(this.decodeMode!==jt.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Qe.NumericDecimal:return this.emitNumericEntity(0,2);case Qe.NumericHex:return this.emitNumericEntity(0,3);case Qe.NumericStart:return(e=this.errors)===null||e===void 0||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Qe.EntityStart:return 0}}}function Eh(e){let t="",r=new Ws(e,(n)=>t+=Za(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 Sh(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,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 Ih=Eh(za);function wn(e){return Ih(e,jt.Strict)}var el;(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(el||(el={}));var tl;(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"})(tl||(tl={}));import{BaseRenderable as uf,isTextNodeRenderable as df,TextNodeRenderable as hf,TextRenderable as ff,Yoga as ml}from"@opentui/core";import{BoxRenderable as Rb,RootRenderable as Tb}from"@opentui/core";import{TimeToFirstDrawRenderable as gf}from"@opentui/core";import{createSlotRegistry as Db}from"@opentui/core";class _n extends Yh{_ctx;constructor(e,t){super(t);this._ctx=e}}class Ei extends _n{constructor(e,t){super(null,e);if(t==="b"||t==="strong")this.attributes=(this.attributes||0)|Ys.BOLD;else if(t==="i"||t==="em")this.attributes=(this.attributes||0)|Ys.ITALIC;else if(t==="u")this.attributes=(this.attributes||0)|Ys.UNDERLINE}}class Zs extends Ei{constructor(e){super(e,"b")}}class $s extends Ei{constructor(e){super(e,"i")}}class ul extends Ei{constructor(e){super(e,"u")}}class dl extends _n{constructor(e,t){super(null,t);this.add()}add(){return super.add(`
7
+ `)}}class hl extends _n{constructor(e,t){let r={...t,link:{url:t.href}};super(null,r)}}var Jh={box:Dh,text:Qh,input:Fh,select:jh,textarea:Wh,ascii_font:Ph,tab_select:Kh,scrollbox:Hh,code:Mh,diff:Nh,line_number:Gh,markdown:Uh,image:Lh,span:_n,strong:Zs,b:Zs,em:$s,i:$s,u:ul,br:dl,a:hl},fl={...Jh};function Kt(e){Object.assign(fl,e)}function Vh(){return fl}var to=Ha(),ht=()=>{let e=bn(to);if(!e)throw Error("No renderer found");return e},Zh=(e)=>{let t=ht();br(()=>{t.on("resize",e)}),ot(()=>{t.off("resize",e)})},Ur=()=>{let e=ht(),[t,r]=j({width:e.width,height:e.height});return Zh((i,s)=>{r({width:i,height:s})}),t},Hr=(e,t)=>{let n=ht().keyInput;br(()=>{if(n.on("keypress",e),t?.release)n.on("keyrelease",e)}),ot(()=>{if(n.off("keypress",e),t?.release)n.off("keyrelease",e)})};var rf=(e)=>K(()=>e());function nf({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 m(_,y,x,v);Tt((O)=>m(_,y(),O,v),x)}function m(_,y,v,x,O){while(typeof v==="function")v=v();if(y===v)return v;let D=typeof y,P=x!==void 0;if(D==="string"||D==="number"){if(D==="number")y=y.toString();if(P){let T=v[0];if(T&&i(T))s(T,y);else T=r(y);v=b(_,v,x,T)}else if(v!==""&&typeof v==="string")s(u(_),v=y);else b(_,v,x,r(y)),v=y}else if(y==null||D==="boolean")v=b(_,v,x);else if(D==="function")return Tt(()=>{let T=y();while(typeof T==="function")T=T();v=m(_,T,v,x)}),()=>v;else if(Array.isArray(y)){let T=[];if(A(T,y,O))return Tt(()=>v=m(_,T,v,x,!0)),()=>v;if(T.length===0){let U=b(_,v,x);if(P)return v=U}else if(Array.isArray(v))if(v.length===0)w(_,T,x);else g(_,v,T);else if(v==null||v==="")w(_,T);else g(_,P&&v||[u(_)],T);v=T}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 O=0,D=y.length;O<D;O++){let P=y[O],T;if(P==null||P===!0||P===!1);else if(Array.isArray(P))x=A(_,P)||x;else if((T=typeof P)==="string"||T==="number")_.push(r(P));else if(T==="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 g(_,y,v){let x=v.length,O=y.length,D=x,P=0,T=0,U=d(y[O-1]),V=null;while(P<O||T<D){if(y[P]===v[T]){P++,T++;continue}while(y[O-1]===v[D-1])O--,D--;if(O===P){let Q=D<x?T?d(v[T-1]):v[D-T]:U;while(T<D)o(_,v[T++],Q)}else if(D===T)while(P<O){if(!V||!V.has(y[P]))a(_,y[P]);P++}else if(y[P]===v[D-1]&&v[T]===y[O-1]){let Q=d(y[--O]);o(_,v[T++],d(y[P++])),o(_,v[--D],Q),y[O]=v[D]}else{if(!V){V=new Map;let te=T;while(te<D)V.set(v[te],te++)}let Q=V.get(y[P]);if(Q!=null)if(T<Q&&Q<D){let te=P,ae=1,q;while(++te<O&&te<D){if((q=V.get(y[te]))==null||q!==Q+ae)break;ae++}if(ae>Q-T){let De=y[P];while(T<Q)o(_,v[T++],De)}else p(_,v[T++],y[P++])}else P++;else a(_,y[P++])}}}function b(_,y,v,x){if(v===void 0){let D;while(D=u(_))a(_,D);return x&&o(_,x),x??""}let O=x||n();if(y.length){let D=!1;for(let P=y.length-1;P>=0;P--){let T=y[P];if(O!==T){let U=c(T)===_;if(!D&&!P)U?p(_,O,T):o(_,O,v);else U&&a(_,T)}else D=!0}}else o(_,O,v);return[O]}function w(_,y,v){for(let x=0,O=y.length;x<O;x++)o(_,y[x],v)}function p(_,y,v){o(_,y,v),a(_,v)}function C(_,y,v={},x){if(y||(y={}),!x)Tt(()=>v.children=m(_,y.children,v.children));return Tt(()=>y.ref&&y.ref(_)),Tt(()=>{for(let O in y){if(O==="children"||O==="ref")continue;let D=y[O];if(D===v[O])continue;l(_,O,D,v[O]),v[O]=D}}),v}return{render(_,y){let v;return pr((x)=>{v=x,f(y,_())}),v},insert:f,spread(_,y,v){if(typeof y==="function")Tt((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:Tt,memo:rf,createComponent:Va,use(_,y,v){return pt(()=>_(y,v))}}}function sf(e){let t=nf(e);return t.mergeProps=Ci,t}var xi=new Map;function ro(e){if(!xi.has(e))xi.set(e,0);let t=xi.get(e)+1;return xi.set(e,t),`${e}-${t}`}var Je=(...e)=>{if(process.env.DEBUG)console.log("[Reconciler]",...e)};class Fr extends tf{static fromString(e,t={}){let r=new Fr(t);return r.add(e),r}}var He=(e)=>{if(!e)return;return e.id},zs=(e)=>{let t;if(e instanceof gl)t=e.getTextChildren();else t=e.getChildren();return t};function of(e,t,r){if(Je("Inserting node:",He(t),"into parent:",He(e),"with anchor:",He(r),t instanceof Fr),t instanceof Gr)t.parent=e,t=t.getSlotChild(e);if(r&&r instanceof Gr)r=r.getSlotChild(e);if(Xs(t)){if(!(e instanceof gl)&&!Xs(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 Al))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=zs(e),i=n.indexOf(r);if(i===-1)Je("[INSERT]","Could not find anchor",He(e),He(r),"[children]",...n.map((s)=>s.id));e.add(t,i)}function af(e,t){Je("Removing node:",He(t),"from parent:",He(e));let r;if(t instanceof Gr){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 Al&&!t.parent){t.destroyRecursively();return}})}function al(e,t){Je("Creating text node:",e);let r=ro("text-node");if(typeof e==="number")e=e.toString();return Fr.fromString(t?wn(e):e,{id:r})}function lf(){let e=ro("slot-node");return Je("Creating slot node",e),new Gr(e)}function ll(e){Je("Getting parent of node:",He(e));let t=e.parent??void 0;if(t instanceof qh)t=t.textParent??void 0;let r=t?.parent?.parent?.parent;if(r instanceof ef&&r.content===t)t=r;return t}var{render:cf,effect:fe,memo:lt,createComponent:J,createElement:S,createTextNode:ke,insertNode:R,insert:L,spread:xb,setProp:h,mergeProps:Eb,use:Sb}=sf({createElement(e){Je("Creating element:",e);let t=ro(e),r=bn(to);if(!r)throw Error("No renderer found");let n=Vh();if(!n[e])throw Error(`[Reconciler] Unknown component type: ${e}`);let i=new n[e](r,{id:t});if(i instanceof nl)ot(()=>{i.source=void 0});return Je("Element created with id:",t),i},createTextNode:(e)=>al(e,!0),createDynamicTextNode:(e)=>al(e,!1),createSlotNode:lf,replaceText(e,t){if(Je("Replacing text:",t,"in node:",He(e)),!(e instanceof Fr))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(Xs(e)){if(t==="href"){e.link={url:r};return}if(t==="style"){e.attributes|=$h(r),e.fg=r.fg?il(r.fg):e.fg,e.bg=r.bg?il(r.bg):e.bg;return}return}switch(t){case"id":Je("Id mapped",e.id,"=",r),e[t]=r;break;case"focused":if(!(e instanceof zh))return;if(r)e.focus();else e.blur();break;case"onChange":let i=void 0;if(e instanceof sl)i=Js.SELECTION_CHANGED;else if(e instanceof ol)i=Vs.SELECTION_CHANGED;else if(e instanceof Qs)i=vn.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(vn.INPUT,r);if(n)e.off(vn.INPUT,n)}break;case"onSubmit":if(e instanceof Qs){if(r)e.on(vn.ENTER,r);if(n)e.off(vn.ENTER,n)}else e[t]=r;break;case"onSelect":if(e instanceof sl){if(r)e.on(Js.ITEM_SELECTED,r);if(n)e.off(Js.ITEM_SELECTED,n)}else if(e instanceof ol){if(r)e.on(Vs.ITEM_SELECTED,r);if(n)e.off(Vs.ITEM_SELECTED,n)}break;case"style":let s=r??{},o=n??{};if(Xh(e)&&o.selectionOccupancy&&!s.selectionOccupancy)e.selectionOccupancy=void 0;if(e instanceof nl)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 Fr},insertNode:of,removeNode:af,getParentNode:ll,getFirstChild(e){Je("Getting first child of node:",He(e));let t=zs(e)[0];if(!t){Je("No first child found for node:",He(e));return}return Je("First child found:",He(t),"for node:",He(e)),t},getNextSibling(e){Je("Getting next sibling of node:",He(e));let t=ll(e);if(!t){Je("No parent found for node:",He(e));return}if(e instanceof Gr){let s=e.getSlotChildForRemoval(t);if(s)e=s}let r=zs(t),n=r.indexOf(e);if(n===-1||n===r.length-1){Je("No next sibling found for node:",He(e));return}let i=r[n+1];if(!i){Je("Next sibling is null for node:",He(e));return}return Je("Next sibling found:",He(i),"for node:",He(e)),i}});function cl(e){return e?.getLayoutNode?.()?.constructor}function Af(e){return e?.create?.()??ml.default.Node.create()}class no extends uf{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 hf{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 eo extends no{yogaNode;slotParent;destroyed=!1;yogaNodeConstructor;yogaNodeFreed=!1;constructor(e,t,r){super(e);this._visible=!1,this.slotParent=t,this.yogaNodeConstructor=cl(r),this.yogaNode=Af(this.yogaNodeConstructor),this.yogaNode.setDisplay(ml.Display.None)}getLayoutNode(){return this.yogaNode}updateFromLayout(){}updateLayout(){}onRemove(){}isCompatibleWith(e){return this.yogaNodeConstructor===cl(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 Gr extends no{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 df(e)||e instanceof ff}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 eo(`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 eo&&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()}}Kt({time_to_first_draw:gf});var mf=(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=cf(()=>J(to.Provider,{get value(){return e},get children(){return J(t,{})}}),e.root)}finally{s=!1,e.destroy=a}if(n)l();if(o)a()},io=async(e,t={})=>{let r=t instanceof Th?t:await Bh({...t,onDestroy:()=>{t.onDestroy?.()}});Oh.attach(r),mf(r,e)};var pl={tier0:32,tier1:64,tier2:64};import{basename as tm,dirname as Zi}from"path";var or=1,Si=8;function je(e){if(typeof e!=="number"||!Number.isFinite(e))return 1;return Math.max(1,Math.min(8,Math.round(e)))}function Cn(e,t){let r=je(e);return{primary:r,mirrored:t?r-1:0}}var so=64;var Ub=so*so;var jb=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 oo={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 bf=["positionX","positionY","positionZ","rotationX","rotationY","rotationZ","scaleX","scaleY","scaleZ"];var yf=new Set(bf);function jr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function bl(e,t){if(!jr(e))return[`${t} must be an object`];let r=[];for(let[n,i]of Object.entries(e)){if(!yf.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 wl(e){if(!jr(e))return["Animation catalog must be an object"];let t=[];if(e.version!==1)t.push("Animation catalog version must be 1");if(!jr(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(!jr(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(!jr(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(...bl(n.model,`${i}.model`));if(n.roles!==void 0)if(!jr(n.roles))t.push(`${i}.roles must be an object`);else for(let[s,o]of Object.entries(n.roles))t.push(...bl(o,`${i}.roles.${s}`))}return t}var yl=wl(oo);if(yl.length>0)throw Error(`Invalid character animation catalog:
8
+ ${yl.join(`
9
+ `)}`);var wf=oo,vf=["jump","frontFlip","horseWalk","swim"],_f=Object.keys(wf.clips).filter((e)=>!vf.includes(e));var _l=["top","side","bottom"],Cl=["left","right","bottom","top","back","front"],xl=["humanoid","female","pig","robot","dog","cat","horse","bird","octopus"],Ii=["leftLeg","rightLeg","leftArm","rightArm","leftLegFoot","rightLegFoot","leftArmFoot","rightArmFoot","leftSleeve","rightSleeve"],El=["leftWing","rightWing","carried","muzzle"];var ey=new Set(xl),ty=new Set([...Ii,...El]),ry=new Set(_l),ny=new Set(Cl),iy=["cree","per"].join(""),xn=["H","oof"].join(""),sy=new Map([[`leftLeg${xn}`,"leftLegFoot"],[`rightLeg${xn}`,"rightLegFoot"],[`leftArm${xn}`,"leftArmFoot"],[`rightArm${xn}`,"rightArmFoot"]]),oy=["horse",xn].join("");var Ef=Math.PI*2;var uy=new Set(Ii);var Sl={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 Il(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=Il(t);return e.filter((n)=>r.has(n))}var If=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,kf=/^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)(deg|grad|rad|turn)?$/i,Ri=(e,t,r)=>Math.max(t,Math.min(r,e));function Ti(e){let t=e.trim(),r=t.endsWith("%"),n=r?t.slice(0,-1):t;if(!If.test(n))return null;let i=Number(n);return Number.isFinite(i)?{value:i,percentage:r}:null}function Rl(e){if(e===null)return 1;let t=Ti(e);if(!t)return null;return Ri(t.percentage?t.value/100:t.value,0,1)}function Tl(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 Rf(e){let t=kf.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 En(e){let t=Tl(e,["hsl","hsla"]);if(!t)return null;let r=Rf(t.channels[0]),n=Ti(t.channels[1]),i=Ti(t.channels[2]),s=Rl(t.alpha);if(r===null||!n||!i||s===null)return null;return[r,Ri(n.value,0,100),Ri(i.value,0,100),s]}function Bl(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 Ol({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 Sn({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 kl=(e,t)=>{let r=Math.max(-100,Math.min(100,t))/100;return r>=0?e+(100-e)*r:e*(1+r)};var ki=(e)=>{let t=Math.round(e*1000)/1000;return String(Object.is(t,-0)?0:t)};function lo(e,t,r){if(t===0&&r===0)return e;let n=En(e),i=n?null:Yt(e);if(!n&&!i)return e;let s=n?{h:n[0],s:n[1],l:n[2]}:Ol(i),o=s.s===0?0:kl(s.s,t),a=kl(s.l,r),l=n?.[3]??i?.a??1;return`hsla(${ki(s.h)}, ${ki(o)}%, ${ki(a)}%, ${ki(l)})`}function ct(e){return typeof e==="number"&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function In(e,t,r){let n=ct(t),i=ct(r);if(n===0&&i===0)return e;return e.map((s)=>lo(s,n,i))}function Wt(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=lo(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 Tf(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 Bf(e){let t=Tl(e,["rgb","rgba"]);if(!t)return null;let r=t.channels.map(Ti),n=Rl(t.alpha);if(r.some((l)=>l===null)||n===null)return null;let[i,s,o]=r,a=(l)=>Ri(l.percentage?l.value/100*255:l.value,0,255);return{r:a(i),g:a(s),b:a(o),a:n}}function Yt(e){let t=e.trim(),r=Tf(t);if(r)return r;let n=En(t);if(n)return{...Bl(n[0],n[1],n[2]),a:n[3]};let i=Bf(t);if(i)return i;let s=Sl[t.toLowerCase()];if(!s)return null;return{r:s[0],g:s[1],b:s[2],a:s[3]??1}}function ar(e){let t=Yt(e);return t?{r:t.r,g:t.g,b:t.b}:null}var Bi=1;var co=30;function kn(e){return e.trim().slice(0,30)}var Rn=0.16,uo=0.1;var Kr=0.15,ho=0.12;var yr=0.25;var Oi=[-1,1];function wr(...e){let t=Math.max(0,Math.min(...e));return Math.max(0.22,t*0.5)}var Be=64,fo=Be*Be;var Ao=64,Dl=512,Ly=Dl*Dl,Nf=128,Ll=65535,Lf=20,Ff=/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i,Gf=/^[a-z]+$/i,Uf=/^(?:rgb|rgba|hsl|hsla)\([\d\s.,%+\-/e]*(?:(?:deg|grad|rad|turn)[\d\s.,%+\-/e]*)?\)$/i;function Fl(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Wr(e,t,r){return Number.isInteger(e)&&Number(e)>=t&&Number(e)<=r}function yt(e){if(typeof e!=="string"||e.length===0||e.length>Nf)return!1;return Ff.test(e)||Gf.test(e)||Uf.test(e)}function Hf(e){return Fl(e)&&e.v===2}function Ml(e,t){return e===void 0||Array.isArray(e)&&e.length<=t&&e.every((r)=>Wr(r,0,t-1))}function Nl(e,t,r){return e===void 0||Array.isArray(e)&&e.length===t&&e.every((n)=>Wr(n,0,r))}function jf(e,t,r){let{w:n,h:i,palette:s,cells:o,activeNoColor:a,tiles:l,depths:c,mirrorZ:u}=e;if(!Wr(n,0,t)||!Wr(i,0,t))return!1;let d=n*i;return d<=r&&Array.isArray(s)&&s.length<=d&&s.every(yt)&&Array.isArray(o)&&o.length===d&&o.every((f)=>Wr(f,0,s.length))&&Ml(a,d)&&Nl(l,d,Ll+1)&&Nl(c,d,Lf)&&Ml(u,d)}function Kf(e){if(!Fl(e)||typeof e.active!=="boolean")return!1;if(e.color!==null&&!yt(e.color))return!1;if(e.tileIndex!==void 0&&e.tileIndex!==null&&!Wr(e.tileIndex,0,Ll))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 Wf(e){if(e.length>Be)return null;let t=0,r=[];for(let n of e){if(!Array.isArray(n)||n.length>Be)return null;if(t+=n.length,t>fo||!n.every(Kf))return null;r.push(n.map((i)=>({active:i.active,color:i.color,...i.tileIndex!=null?{tileIndex:i.tileIndex}:{},...je(i.depth)>or?{depth:je(i.depth)}:{},...i.mirrorZ?{mirrorZ:!0}:{}})))}return r}function Yr(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 m=0;m<r;m++){let A=f?.[m],g=d*r+m;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[g]=w}else if(A.active)o.push(g);if(A.tileIndex!=null)a??=Array(r*t).fill(0),a[g]=A.tileIndex+1;let b=je(A.depth);if(b>or)l??=Array(r*t).fill(0),l[g]=b;if(A.mirrorZ)c.push(g)}}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 Tn(e){if(Hf(e))return jf(e,Be,fo)?Yf(e):[];return Array.isArray(e)?Wf(e)??[]:[]}function Yf(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 m=0;m<t;m++){let A=d*t+m,g=i[A];if(g>0)f[m]={active:!0,color:n[g-1]??null};else if(l?.has(A))f[m]={active:!0,color:null};else f[m]={active:!1,color:null};let b=o?.[A];if(b)f[m].tileIndex=b-1;let w=je(a?.[A]);if(w>or)f[m].depth=w;if(c?.has(A))f[m].mirrorZ=!0}u[d]=f}return u}var Qf={top:0,side:1,bottom:2};var Jf=/^data:image\/(?:png|gif|webp);base64,[a-z\d+/=]+$/i;var Vf=/^[\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 go(e,t){return Number.isInteger(e)&&Number(e)>0&&Number(e)<=t}function Zf(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 $f(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 mo(e){if(!e||e.v!==2&&e.v!==3)return!1;if(!Zf(e.name)||!go(e.tileSize,64)||!go(e.cols,256)||!go(e.rows,256))return!1;if(e.faceLayout!==void 0&&e.faceLayout!=="top-side-bottom")return!1;if(!$f(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 Xf(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"||!Vf.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 po(e){if(!mo(e))return null;if(e.v===2)return e.imageDataUrl.length<=16777216&&Jf.test(e.imageDataUrl)?e.imageDataUrl:null;if(e.v===3)return Xf(e.url,e.path);return null}function Bn(e,t,r="top"){if(!mo(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?Qf[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 bo(e){if(!mo(e))return null;return{width:e.cols*e.tileSize*(e.faceLayout?3:1),height:e.rows*e.tileSize}}function zf(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},On={corners:[[0,1,1],[0,1,0],[1,1,0],[1,1,1]],shade:0.97},Qr={corners:[[1,0,1],[1,0,0],[1,1,0],[1,1,1]],shade:0.94},_r=0.5,qf=0.75,eA="rgba(0, 0, 0, 0.16)",tA=0.92,rA="#92929a";function nA(e){if(!Number.isFinite(e))return _r;return Math.max(0,Math.min(1,e))}function Gl(e,t){if(t<_r){let n=t/_r,i=e*qf;return i+(e-i)*n}let r=(t-_r)/(1-_r);return e+(1-e)*r}function de(e){return e.toFixed(2)}function Bt(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("'","&apos;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Ul(e){return`${de(e[0])},${de(e[1])}`}function iA([e,t]){let r=Ul(e),n=Ul(t);return r<n?`${r} ${n}`:`${n} ${r}`}function Hl(e,t){return`<polygon points="${e.map(([n,i])=>`${de(n)},${de(i)}`).join(" ")}" fill="${Bt(t)}"/>`}function jl(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 sA(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=jl(s,o,t),c=jl(s,a,t);n+=`${i===0?"M":"L"}${de(l[0])},${de(l[1])}`,n+=`Q${de(s[0])},${de(s[1])} ${de(c[0])},${de(c[1])}`}return`${n}Z`}function Kl(e,t,r,n){return`<path d="${e}" fill="${Bt(t)}" stroke="${Bt(r)}" stroke-width="${de(n)}" stroke-linejoin="round"/>`}function oA(e,t){if(e.length===0)return"";return`<path d="${e.map(([n,i])=>`M${de(n[0])},${de(n[1])}L${de(i[0])},${de(i[1])}`).join("")}" fill="none" stroke="${Bt(t)}" stroke-width="1" stroke-linejoin="round" vector-effect="non-scaling-stroke"/>`}function yo(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,m=s&&d!=="jelly"?eA:void 0,A=nA(o),g=po(l),b=l&&g?l:null,w=bo(b),p=w?.width??0,C=w?.height??0,_=g&&c&&/^[a-z_][\w:.-]{0,127}$/i.test(c)?c:null,y=g?_??zf(g):"",v=u||!_,x=t.slice(0,Be),O=Math.min(Number.isInteger(n)&&n>0?n:0,x.length,Be),D=x.reduce((B,W)=>Math.max(B,Array.isArray(W)?W.length:0),0),P=Math.min(Number.isInteger(r)&&r>0?r:0,D,Be),T=f,U=f/Math.sqrt(3),V=f*2/Math.sqrt(3),Q=d==="jelly"?T*Rn:0,te=(B)=>B?.tileIndex!=null?Bn(b,B.tileIndex):null,ae=(B)=>{if(yt(B?.color))return B.color;return te(B)?rA:null},q=(B,W,pe)=>[(B-W)*T,(B+W)*U-pe*V],De=(B,W)=>{let pe=t[W]?.[B];return pe?.active&&ae(pe)?je(pe.depth):0},Se=[];for(let B=0;B<O;B++)for(let W=0;W<P;W++){let pe=t[B]?.[W],at=ae(pe);if(pe?.active&&at)Se.push({x:W,y:B,color:at,tileIndex:pe.tileIndex??null,depth:je(pe.depth),mirrorZ:!!pe.mirrorZ})}if(Se.length===0)return'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 0 0"/>';Se.sort((B,W)=>B.x+B.y-(W.x+W.y)||B.depth-W.depth);let z=[],Z=1/0,le=-1/0,ge=1/0,N=-1/0,ne=!1,ie=Gl(Qr.shade,A),ce=Gl(On.shade,A),Ze=(B)=>B===vr?B.shade:B===Qr?ie:ce,me=(B,W)=>{if(B<Z)Z=B;if(B>le)le=B;if(W<ge)ge=W;if(W>N)N=W};for(let{x:B,y:W,color:pe,tileIndex:at,depth:vt,mirrorZ:Ne}of Se){let it=En(pe),Ye=[],gr=[],{primary:ee,mirrored:hn}=Cn(vt,Ne),_t=(Ae)=>it?`hsla(${it[0]}, ${it[1]}%, ${Math.max(0,Math.min(100,it[2]*Ae))}%, ${it[3]})`:pe,mr=(Ae,Ce=0,Le=ee)=>Ae.corners.map(([xe,he,se])=>q(B+xe,W+he,se===0?Ce:Le)),fn=(Ae,Ce=0,Le=ee)=>{let xe=mr(Ae,Ce,Le);if(Q>0){let he=Ze(Ae),se=_t(he),oe=sA(xe,Q),Fe=Ae===vr?_t(Math.min(1.18,he+0.13)):_t(he*tA);Ye.push(Kl(oe,se,se,Q),Kl(oe,"none",Fe,Q*0.3))}else Ye.push(Hl(xe,_t(Ze(Ae))));for(let[he,se]of xe)me(he,se)},zt=Ne?-hn:De(B+1,W),Gt=Ne?-hn:De(B,W+1),Rt=a&&!Ne?0:zt,Nr=a&&!Ne?0:Gt,fi=a||Ne||Rt<ee,Ai=a||Ne||Nr<ee;if(fi)fn(Qr,Rt,ee);if(Ai)fn(On,Nr,ee);if(fn(vr,ee,ee),m){let Ae=new Set,Ce=(se,oe)=>{let Fe=iA([se,oe]);if(Ae.has(Fe))return;Ae.add(Fe),gr.push([se,oe])},Le=(se)=>{for(let oe=0;oe<se.length;oe++)Ce(se[oe],se[(oe+1)%se.length])},xe=(se,oe)=>{let[Fe,Ge]=se.corners.filter(([,,Me])=>Me===0);for(let Me=Math.floor(oe)+1;Me<ee;Me++)Ce(q(B+Fe[0],W+Fe[1],Me),q(B+Ge[0],W+Ge[1],Me))},he=mr(vr,ee,ee);if(Ce(he[0],he[1]),De(B+1,W)!==ee)Ce(he[1],he[2]);if(De(B,W+1)!==ee)Ce(he[2],he[3]);if(Ce(he[3],he[0]),Ne||zt<ee)Le(mr(Qr,zt,ee)),xe(Qr,zt);if(Ne||Gt<ee)Le(mr(On,Gt,ee)),xe(On,Gt)}let gi=at==null?null:Bn(b,at);if(gi){ne=!0;let Ae=(xe,he,se,oe,Fe,Ge,Me,qe)=>{let et=Bn(b,at,xe);if(!et)return;let Ct=1-qe;Ye.push(`<g transform="matrix(${he} ${se} ${oe} ${Fe} ${de(Ge)} ${de(Me)})"><svg x="0" y="0" width="1" height="1" viewBox="${et.sx} ${et.sy} ${et.tileSize} ${et.tileSize}" preserveAspectRatio="none"><use href="#${y}" xlink:href="#${y}"/></svg>`+(Ct>0?`<rect x="0" y="0" width="1" height="1" fill="#000" opacity="${Ct.toFixed(2)}"/>`:"")+"</g>")};if(fi){let[xe,he]=q(B+1,W,ee);Ae("side",-T,U,0,V*(ee-Rt),xe,he,Ze(Qr))}if(Ai){let[xe,he]=q(B,W+1,ee);Ae("side",T,U,0,V*(ee-Nr),xe,he,Ze(On))}let[Ce,Le]=q(B,W,ee);Ae("top",T,U,-T,U,Ce,Le,vr.shade)}if(m)Ye.push(oA(gr,m));if(d!=="normal"&&!gi){if(d==="lego"){let Ae=Math.SQRT2*Kr*T,Ce=Math.SQRT2*Kr*U,Le=_t(ie),xe=_t(vr.shade),he=[[-1,-1],[-1,1],[1,-1],[1,1]];for(let[se,oe]of he){let Fe=B+0.5+se*yr,Ge=W+0.5+oe*yr,[Me,qe]=q(Fe,Ge,ee),[,et]=q(Fe,Ge,ee+ho);me(Me-Ae,qe+Ce),me(Me+Ae,et-Ce);let Ct='shape-rendering="geometricPrecision"';Ye.push(`<ellipse cx="${de(Me)}" cy="${de(qe)}" rx="${de(Ae)}" ry="${de(Ce)}" fill="${Bt(Le)}" ${Ct}/>`,`<rect x="${de(Me-Ae)}" y="${de(et)}" width="${de(Ae*2)}" height="${de(qe-et)}" fill="${Bt(Le)}" ${Ct}/>`,`<ellipse cx="${de(Me)}" cy="${de(et)}" rx="${de(Ae)}" ry="${de(Ce)}" fill="${Bt(xe)}" ${Ct}/>`)}}else if(d==="voxel"){let Ae=(se,oe,Fe,Ge,Me,qe)=>{let et=(Ct,An)=>{for(let[mi,qt]of Ct)me(mi,qt);Ye.push(Hl(Ct,_t(An)))};et([q(oe,Fe,qe),q(oe,Fe,Me),q(oe,Ge,Me),q(oe,Ge,qe)],ie),et([q(se,Ge,qe),q(se,Ge,Me),q(oe,Ge,Me),q(oe,Ge,qe)],ce),et([q(se,Fe,qe),q(oe,Fe,qe),q(oe,Ge,qe),q(se,Ge,qe)],vr.shade)},Ce=uo,Le=wr(1,1),xe=Ne||zt<ee?zt:null,he=Ne||Gt<ee?Gt:null;if(Ae(B+0.5-Le/2,B+0.5+Le/2,W+0.5-Le/2,W+0.5+Le/2,ee,ee+Ce),xe!==null){let se=wr(1,ee-xe),oe=(ee+xe)/2;Ae(B+1,B+1+Ce,W+0.5-se/2,W+0.5+se/2,oe-se/2,oe+se/2)}if(he!==null){let se=wr(1,ee-he),oe=(ee+he)/2;Ae(B+0.5-se/2,B+0.5+se/2,W+1,W+1+Ce,oe-se/2,oe+se/2)}}}if(a)z.push(`<g data-color="${Bt(pe)}">${Ye.join("")}</g>`);else z.push(...Ye)}let Re=2+Q/2,At=Z-Re,Xe=ge-Re,ze=le-Z+Re*2,re=N-ge+Re*2,kt=ne&&b&&g&&v?`<defs><image id="${y}" href="${Bt(g)}" xlink:href="${Bt(g)}" 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="${de(At)} ${de(Xe)} ${de(ze)} ${de(re)}" shape-rendering="crispEdges">`,kt,...z,"</svg>"].join("")}var aA="hsla(278, 100%, 70%, 1)",lA=/hsla\(278, 100%, ([\d.]+)%, 1\)/g,Pn=(e)=>yo({grid:[[{active:!0,color:aA}]],numCols:1,numRows:1,blockStyle:e,sideLighting:0.15}).replaceAll(lA,"hsl(var(--block-style-icon-hs, 278 100%) $1% / 1)"),cA=[{style:"normal",label:"Normal",icon:Pn("normal")},{style:"voxel",label:"Voxel",icon:Pn("voxel")},{style:"lego",label:"Lego",icon:Pn("lego")},{style:"jelly",label:"Jelly",icon:Pn("jelly")}];function uA(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function wo(e,t,r,n,i=1){let s=uA(t),o=`<rect x="${r}" y="${n}" width="${i}" height="${i}" fill="${s}"/>`;if(e==="normal")return o;if(e==="jelly"){let c=i*Rn,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,m=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="${m}"/>`,`<path d="M${u+c} ${d}V${d+c}H${u}" fill="none" stroke="rgba(0, 0, 0, 0.12)" stroke-width="${m}"/>`].join("")}let a=i*Kr,l=(c)=>Oi.flatMap((u)=>Oi.map((d)=>{let f=r+i*(0.5+u*yr+c),m=n+i*(0.5+d*yr+c);return`M${f+a} ${m}A${a} ${a} 0 1 1 ${f-a} ${m}A${a} ${a} 0 1 1 ${f+a} ${m}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 dA=16777216,hA=16;function Jr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function fA(e){if(!Array.isArray(e))return[...ut[0].colors];let t=e.slice(0,hA).flatMap((r)=>{if(typeof r==="string"&&yt(r))return[r];if(Jr(r)&&yt(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 AA(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 gA(e){let t=Jr(e)?e:{};return{saturation:ct(t.saturation),lightness:ct(t.lightness)}}function Dn(e){if(e.length>dA)throw Error("Draft is too large");let t=JSON.parse(e);if(!Jr(t)||t.version!==1)throw Error("Not a Flatblox version-1 draft");let r=Tn(t.grid),n=t.gridSize===void 0?r.length:t.gridSize;if(!Number.isInteger(n)||Number(n)<1||Number(n)>Be||r.length!==n||!r.every((o)=>o.length===n))throw Error("Draft contains an invalid grid");let i=fA(t.palette),s=yt(t.activeColor)?t.activeColor:i[0];return{filename:typeof t.filename==="string"?kn(t.filename):"untitled",grid:r,palette:i,activeColor:s,paletteColorAdjustment:gA(t.paletteColorAdjustment),draft:{data:t,activeArtboard:AA(t)}}}function mA(e,t){let r=Array.isArray(t)?t:[];return e.map((n,i)=>{let s=r[i];if(!Jr(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 pA(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]=Jr(s)&&"grid"in s?{...s,grid:t}:t}return{artboards:n,activeArtboard:i}}function Mn(e){let t=e.draft?.data,r=Yr(e.grid),n=mA(e.palette,t?.palette),{artboards:i,activeArtboard:s}=pA(e,r),o=e.paletteColorAdjustment??{saturation:0,lightness:0},a=Jr(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 Vr(e){return e==="rectangle"||e==="circle"}function bA(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 yA(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,m=d+f+u*l*l;o+=c+1>>1,a=o-u;let A=8*l*l,g=8*c*c;do{n(s,o),n(i,o),n(i,a),n(s,a);let b=2*m;if(b<=f)o++,a--,f+=A,m+=f;if(b>=d||2*m>f)i++,s--,d+=g,m+=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 vo(e,t,r){let n=e==="circle"?yA(t,r):bA(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 Wl=16,wA=100;function _o(e,t,r){return Math.max(t,Math.min(r,e))}function Nn(e){return e.map((t)=>t.map((r)=>({...r})))}function vA(e){return Array.from({length:e},()=>Array.from({length:e},()=>({active:!1,color:null})))}function Yl(e){if(!Number.isInteger(e)||e<1||e>Be)throw Error(`Grid size must be between 1 and ${Be}`);return e}function Fn(e=Wl){let t=[...ut[0].colors];return{filename:"untitled",grid:vA(Yl(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 Qt{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=Yl(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:_o(Math.round(e),0,this.size-1),y:_o(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?je(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=je(s.depth),a=_o(o+r,or,Si);if(a===o)continue;this.currentGrid[i.y][i.x]={...s,depth:a},n=!0}return n})}applyShape(e,t,r){if(!Vr(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 vo(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>wA)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 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.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 _A}from"net";var CA="127.0.0.1",xA=47642,EA=3000,SA=32,IA=1048576,kA=16384,Ql=[0.57,0.57,0.6,1],Jl=new Map;function RA(e){if(!e)return[...Ql];let t=Jl.get(e);if(!t){let r=Yt(e);t=r?[r.r/255,r.g/255,r.b/255,r.a]:[...Ql],Jl.set(e,t)}return t}function TA(e){if(!e?.active)return{active:!1,color:null,depth:1,mirrorZ:!1};return{active:!0,color:RA(e.color),depth:je(e.depth),mirrorZ:!!e.mirrorZ}}function Zl(e,t,r){return{x:t%r,y:Math.floor(t/r),...e}}function BA(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 $l(e){let{saturation:t,lightness:r}=e.paletteColorAdjustment??{saturation:0,lightness:0},n=Wt(e.grid,t,r),i=n.length,s=n[0]?.length??0;return Array.from({length:s*i},(o,a)=>TA(n[Math.floor(a/s)]?.[a%s]))}function OA(e){let t=e.grid.length,r=e.grid[0]?.length??0,n=$l(e);return{message:{protocol:Bi,type:"snapshot",columns:r,rows:t,cells:n.flatMap((i,s)=>i.active?[Zl(i,s,r)]:[])},state:n}}function PA(e,t,r){return t.flatMap((n,i)=>e[i]&&BA(e[i],n)?[]:[Zl(n,i,r)])}function Vl(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 Co{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=_A){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:CA,port:xA})}catch(t){let r={state:"error",message:Vl(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,Vl(t))),e.on("close",()=>this.handleClose(e)),this.connectTimer=setTimeout(()=>{this.fail(e,"Timed out waiting for the Blender add-on.")},EA),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(),SA)}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=$l(e);for(let i of PA(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)>kA){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.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}=OA(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: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){if(!this.socket?.writable||this.status.state!=="connected")return!1;let t=Buffer.from(`${JSON.stringify(e)}
11
+ `);if(t.length>IA)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 Eo}from"@opentui/core";import{parseColor as DA,Renderable as MA,RGBA as NA}from"@opentui/core";var xo=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 xo.get(e)??null;let i=n.width/t,s=n.height/r,o=xo.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)xo.set(e,a);return a??o??null}function Pi(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 lr(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 Di(e){return Boolean(xt(e)&&lr(e.capabilities))}var LA={width:8,height:16};function FA(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 MA{_source=null;_background=NA.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=DA(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||!lr(this._ctx.capabilities)){this.releaseFrame();return}let r=xt(this._ctx)??LA,n=FA(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 Xl=new WeakMap;function Zr(){let e=ht(),t=Xl.get(e);if(t)return t;let r=pr(()=>{let[n,i]=j(lr(e.capabilities));return e.on("capabilities",()=>i(lr(e.capabilities))),n});return Xl.set(e,r),r}Kt({fitted_image:Gn});var So=32;function GA(e){let[t,r,n]=Eo(e).toInts();return ql.fromRgba(new Uint8Array([t,r,n,255]),1,1)}function UA(e,t,r=So){let n=Eo(e).toInts(),i=Eo(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 zl=new Map;function HA(e,t){let r=`${e}|${t}`,n=zl.get(r);if(!n)n=UA(e,t),zl.set(r,n);return ql.fromRgba(n,So,So)}function Un(e){let t=Zr(),r=()=>e.width??2,n=()=>e.shape??"square",i=K(()=>{let s=n()==="circle"?HA(e.color,e.background):GA(e.color);return ot(()=>s.dispose()),s});return J(Te,{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())})()),fe((o)=>h(s,"fg",e.color,o)),s})()},get children(){var s=S("fitted_image");return h(s,"height",1),h(s,"align","start"),fe((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 WA,statSync as YA}from"fs";import{homedir as QA}from"os";import{basename as JA,join as VA,resolve as Io}from"path";import{deflateSync as ZA}from"zlib";var Jt=Math.PI/4,cr=Math.asin(1/Math.sqrt(3)),jA=1,KA=2500000;function ec(e,t,r,n,i={}){let{density:s=jA,maxPixels:o=KA}=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 Mi(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}=Cn(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 tc(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 Ot=["svg","obj","png"],$A=512,XA=512,zA=new Uint8Array([137,80,78,71,13,10,26,10]);function rc(e){return Ot.includes(e)}function Hn(e,t){return(e??t).replace(/\.flatblox\.json$/i,"").replace(/\.json$/i,"")}function Ni(e,t,r){let n=e.trim();if(!n)return Io(r);let i=n.startsWith("~/")?VA(QA(),n.slice(2)):n;if(/[\\/]$/.test(i)||WA(i)&&YA(i).isDirectory())return Io(i,t);return Io(Hn(i,i).replace(/\.(svg|obj|mtl|png)$/i,""))}function nc(e){return e.reduce((t,r)=>Math.max(t,r.length),0)}function ic(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 sc(e){return e.active&&!!e.color}function qA(e){let t=e.length,r=nc(e),n=[];for(let o=0;o<t;o++)for(let a=0;a<e[o].length;a++){let l=e[o][a];if(sc(l))n.push(wo("normal",l.color,a,o))}let{width:i,height:s}=ic(r,t,$A);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 eg(e,t){let r=ar(e);return`color_${r?[r.r,r.g,r.b].map((i)=>i.toString(16).padStart(2,"0")).join(""):String(t)}`}function $r(e){return Number(e.toFixed(4)).toString()}function tg(e,t){let r=Mi(e),n=new Map,i=[`mtllib ${t}`],s=[],o=0;for(let a of r){let l=n.get(a.color);if(!l){l=eg(a.color,n.size),n.set(a.color,l);let w=ar(a.color)??{r:255,g:255,b:255};s.push(`newmtl ${l}`,`Kd ${$r(w.r/255)} ${$r(w.g/255)} ${$r(w.b/255)}`,"")}let c=a.x-0.5,u=a.x+0.5,d=a.y-a.height/2,f=a.y+a.height/2,m=a.z-0.5,A=a.z+0.5,g=[[c,d,m],[u,d,m],[u,f,m],[c,f,m],[c,d,A],[u,d,A],[u,f,A],[c,f,A]];for(let[w,p,C]of g)i.push(`v ${$r(w)} ${$r(p)} ${$r(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.8",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 60% 9%)"),panel:je("hsl(275 60% 11%)"),panelActive:je("hsl(275 60% 14%)"),card:je("hsl(275 60% 16%)"),border:je("hsl(275 60% 28%)"),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 ko(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 rg(e,t){let r=e.length,n=nc(e),{width:i,height:s}=t===void 0?ic(n,r,XA):{width:n*t,height:r*t},o=i*4+1,a=new Uint8Array(o*s),l=e.map((A)=>A.map((g)=>sc(g)?Yt(g.color):null));for(let A=0;A<s;A++){let g=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[g]?.[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=[zA,ko("IHDR",c),ko("IDAT",new Uint8Array(ZA(a))),ko("IEND",new Uint8Array(0))],f=new Uint8Array(d.reduce((A,g)=>A+g.length,0)),m=0;for(let A of d)f.set(A,m),m+=A.length;return f}function ng(e,t,r=Ot){let n=[],{saturation:i,lightness:s}=e.paletteColorAdjustment??{saturation:0,lightness:0},o=Wt(e.grid,i,s);for(let a of r)if(a==="svg")n.push({path:`${t}.svg`,content:qA(o)});else if(a==="obj"){let l=`${t}.mtl`,{obj:c,mtl:u}=tg(o,JA(l));n.push({path:`${t}.obj`,content:c}),n.push({path:l,content:u})}else n.push({path:`${t}.png`,content:rg(o)});return n}async function Li(e,t,r=Ot,n=(i,s)=>Bun.write(i,s)){let i=ng(e,t,r);for(let s of i)await n(s.path,s.content);return i.map((s)=>s.path)}import{mkdir as ig,readFile as sg,writeFile as og}from"fs/promises";import{homedir as ag}from"os";import{dirname as lg,join as oc}from"path";function ac(e=process.env){if(e.FLATBLOX_TUI_EXPORT_FILE)return e.FLATBLOX_TUI_EXPORT_FILE;let t=e.XDG_CONFIG_HOME||oc(ag(),".config");return oc(t,"flatblox","tui-export.json")}async function lc(e=ac()){try{let t=JSON.parse(await sg(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 cc(e,t=ac()){await ig(lg(t),{recursive:!0,mode:448}),await og(t,`${JSON.stringify({directory:e},null,2)}
16
+ `)}function ur(e){let t=e.name.toLowerCase();return t==="return"||t==="enter"||t==="space"||e.sequence===" "}function Cr(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 Ro,NativeImage as Fi,parseColor as bg,Renderable as yg,RGBA as jn,TextAttributes as dc}from"@opentui/core";import{RGBA as cg}from"@opentui/core";var ug={r:88,g:88,b:88,a:1},dg={r:108,g:108,b:108,a:1},uc=new Map;function hg(e){let t=uc.get(e);if(t!==void 0)return t;let r=Yt(e);return uc.set(e,r),r}function fg(e,t){return(e+t)%2===0?ug:dg}function Ag(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 gg(e,t,r){let n=fg(t,r),i=e?.active&&e.color?hg(e.color):null;return i?Ag(i,n):n}var mg=[new Map,new Map],pg=4096;function Vt(e,t,r){let n=mg[(t+r)%2],i=e?.active&&e.color?e.color:"",s=n.get(i);if(!s){if(n.size>=pg)n.clear();let o=gg(e,t,r);s=cg.fromInts(o.r,o.g,o.b),n.set(i,s)}return s}var Gi=jn.fromInts(22,8,33),hc=jn.fromInts(33,22,41),To=4,ji=jn.fromInts(255,255,255),Ki=jn.fromInts(8,10,16),wg=0.25,Bo=3,Oo=5,vg=[[],[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]],Ui=512,fc=16384,_g=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:bg(e.color)}}function Hi(e){let[t,r,n]=e.toInts(),i=(0.2126*t+0.7152*r+0.0722*n)/255,[s,o,a]=i>0.55?Ki.toInts():ji.toInts(),l=(c,u)=>Math.round(c+(u-c)*wg);return jn.fromInts(l(t,s),l(r,o),l(n,a))}function gc(e,t,r){return Math.max(0,Math.min(r-t,e-Math.floor(t/2)))}function Cg(e,t){let r=Math.ceil(e/Ui)*Ui,n=Math.ceil(t/Ui)*Ui;if(r>fc||n>fc||r*n>_g)return null;return{width:r,height:n}}function xg(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 Eg(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 Po extends yg{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=Pi(this._ctx),n=xt(this._ctx),i=n!==null&&Di(this._ctx);if(i)this.textFrame=null;else if(this.sameTextFrame(r))return;if(e.clear(Gi),t===0||this.width<=0||this.height<=0){this.viewport.columns=0,this.viewport.pixelRows=0;return}let s=n&&i?Eg(this.width,this.height,t,this.currentModel.zoom,n.width,n.height):null,o=s??xg(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=gc(this.currentModel.cursor.x,a,t),m=gc(this.currentModel.cursor.y,l,t),A=Math.floor((this.width-c)/2),g=Math.floor((this.height-d)/2);if(s&&n){if(!this.drawWorldGridImage(e,A,g,n.width,n.height))this.drawWorldGrid(e,A,g,r)}else this.releaseWorldImage(),this.drawWorldGrid(e,A,g,r);if(this.viewport={originX:A,originY:g,startX:f,startY:m,columns:a,pixelRows:l,columnZoom:o.columnZoom,subrowZoom:o.subrowZoom,renderedSubrows:u},s){this.drawArtworkImage(e,s,A,g,f,m);return}this.releaseArtworkImage();let{grid:b,cursor:w}=this.currentModel,p=Ac(this.currentModel.preview,t),{subrowZoom:C,columnZoom:_}=o;for(let y=0;y<d;y++){let v=y*2,x=v+1,O=m+Math.floor(v/C),D=m+Math.floor(x/C),P=b[O],T=b[D];for(let U=0;U<c;U++){let V=f+Math.floor(U/_),Q=p?.cells.has(O*t+V)?p.color:Vt(P?.[V],V,O),te=x<u&&D<t?p?.cells.has(D*t+V)?p.color:Vt(T?.[V],V,D):Gi,ae=w.x===V&&w.y===O,q=w.x===V&&w.y===D;e.setCell(A+U,g+y,"\u2580",ae?Hi(Q):Q,q?Hi(te):te)}}if(this.currentModel.depthLabels)this.drawDepthLabels(e,A,g,f,m)}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,m=Math.ceil(d*u/2),A=Math.floor((d+1)*u/2)-1;if(A<m)continue;let g=m+Math.floor((A-m)/2);for(let b=0;b<a;b++){let w=n+b,p=s[f]?.[w];if(!p?.active)continue;let C=Vt(p,w,f);if(o.x===w&&o.y===f)C=Hi(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+g,String(je(p.depth)),x?Ki: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=Ac(this.currentModel.preview,c),d=new Uint8Array(t.columns*t.pixelRows*4);for(let A=0;A<t.pixelRows;A++){let g=s+A;for(let b=0;b<t.columns;b++){let w=i+b,p=u?.cells.has(g*c+w)?u.color:Vt(this.currentModel.grid[g]?.[w],w,g);if(o.x===w&&o.y===g)p=Hi(p);let[C,_,y]=p.toInts(),v=(A*t.columns+b)*4;d[v]=C,d[v+1]=_,d[v+2]=y,d[v+3]=255}}let f=Fi.fromRgba(d,t.columns,t.pixelRows),m=this.currentModel.depthLabels?this.imageWithDepthLabels(d,t,i,s):f.resize({width:t.pixelWidth,height:t.pixelHeight,kernel:"nearest"});f.dispose(),this.releaseArtworkImage(),this.artworkImage=m,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 g=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=(g*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/(Oo+3))),d=Bo*u,f=Oo*u;if(d>l||f>l)return Fi.fromRgba(c,o,a);let{grid:m}=this.currentModel;for(let A=0;A<s;A++)for(let g=0;g<i;g++){let b=m[n+A]?.[r+g];if(!b?.active)continue;let w=(A*i+g)*4,p=e[w]*0.299+e[w+1]*0.587+e[w+2]*0.114,C=p>140?Ki:ji,_=p>140?ji:Ki,y=vg[je(b.depth)],v=Math.floor(g*l+(l-d)/2),x=Math.floor(A*l+(l-f)/2);for(let O of[_,C]){let[D,P,T]=O.toInts(),U=O===_?[-1,0,1]:[0];for(let V=0;V<Oo;V++)for(let Q=0;Q<Bo;Q++){if(!(y[V]&1<<Bo-1-Q))continue;for(let te=0;te<u;te++)for(let ae=0;ae<u;ae++)for(let q of U)for(let De of U){let Se=v+Q*u+ae+De,z=x+V*u+te+q;if(Se<0||z<0||Se>=o||z>=a)continue;let Z=(z*o+Se)*4;c[Z]=D,c[Z+1]=P,c[Z+2]=T}}}}return Fi.fromRgba(c,o,a)}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(To*n)),l=Math.round(t*n),c=Math.round(r*i),u=s+a,d=o+a,f=Cg(u,d);if(!f)return this.releaseWorldImage(),!1;if(!this.worldImage||a!==this.worldImageSide||u>this.worldImageWidth||d>this.worldImageHeight){let{width:g,height:b}=f,w=new Uint8Array(g*b*4),[p,C,_]=Gi.toInts(),[y,v,x]=hc.toInts(),O=g*4,D=new Uint8Array(O),P=new Uint8Array(O);for(let T=0;T<g;T++){let U=T*4,V=T%a===0;D[U]=V?y:p,D[U+1]=V?v:C,D[U+2]=V?x:_,D[U+3]=255,P[U]=y,P[U+1]=v,P[U+2]=x,P[U+3]=255}for(let T=0;T<b;T++)w.set(T%a===0?P:D,T*O);this.releaseWorldImage(),this.worldImage=Fi.fromRgba(w,g,b),this.worldImageSide=a,this.worldImageWidth=g,this.worldImageHeight=b}if(!this.worldImage)return!1;let m=(-l%a+a)%a,A=(-c%a+a)%a;return e.drawImage(this.worldImage,0,0,this.width,this.height,s,o,m,A,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(To/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)%To===0;if(!a&&!c)continue;e.setCell(l,s,c?"\u258F":" ",hc,Gi,a?dc.UNDERLINE:dc.NONE)}}}destroySelf(){this.releaseArtworkImage(),this.releaseWorldImage(),super.destroySelf()}handleMouse(e){if(e.button!==Ro.LEFT&&e.button!==Ro.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===Ro.RIGHT?{tool:"erase"}:{}})}}import{RGBA as Dg}from"@opentui/core";import{SuperSampleType as Mg,ThreeRenderable as Ng}from"@opentui/three";import{appendFileSync as Sg}from"fs";var mc=process.env.FLATBLOX_TUI_TIMING;function xr(e,t){if(!mc)return;let r=(performance.now()-t).toFixed(0);Sg(mc,`${e} ${r}ms
17
+ `)}import{RGBA as Ig}from"@opentui/core";var Do="Loading voxel preview\u2026",kg=Ig.fromInts(175,129,202);function Wi(e,t,r,n){if(t<1||r<1)return;let i=t>=Do.length?Do:Do.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 Ee}from"@opentui/three";var Rg=1.12,Tg=[0.76,0.64,1,0.42,0.9,0.72],pc=128,Bg=2,bc=6710886,Og=new Uint8Array([76,76,76,255,96,96,96,255,96,96,96,255,76,76,76,255]);function Pg(e,t){let r=[];for(let n of Tg){let i=t?n**2.2:n;for(let s=0;s<4;s+=1)r.push(i,i,i)}e.setAttribute("color",new Ee.Float32BufferAttribute(r,3))}class Kn{scene=new Ee.Scene;camera=new Ee.OrthographicCamera(-1,1,1,-1,0.1,1000);boxGeometry=new Ee.BoxGeometry(1,1,1);boxMaterial;sceneHalfExtents=new Ee.Vector3(2,2,2);groundGeometry;groundMaterial;groundTexture;ground;worldGrid;mesh=null;model;aspect=1;sceneCenterY=0;constructor(e,t){if(this.model=e,Pg(this.boxGeometry,t==="raster"),this.boxMaterial=new Ee.MeshBasicMaterial({toneMapped:!1,vertexColors:!0}),t==="raster"){this.groundGeometry=new Ee.PlaneGeometry(1,1),this.groundTexture=new Ee.DataTexture(Og,2,2),this.groundTexture.colorSpace=Ee.SRGBColorSpace,this.groundTexture.magFilter=Ee.NearestFilter,this.groundTexture.minFilter=Ee.NearestFilter,this.groundTexture.wrapS=Ee.RepeatWrapping,this.groundTexture.wrapT=Ee.RepeatWrapping,this.groundTexture.needsUpdate=!0,this.groundMaterial=new Ee.MeshBasicMaterial({map:this.groundTexture,toneMapped:!1}),this.ground=new Ee.Mesh(this.groundGeometry,this.groundMaterial),this.ground.rotation.x=-Math.PI/2,this.scene.add(this.ground),this.worldGrid=new Ee.GridHelper(pc,pc/Bg,bc,bc);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=Mi(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.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(e.length===0){this.mesh=null;return}let s=new Ee.InstancedMesh(this.boxGeometry,this.boxMaterial,e.length),o=new Ee.Object3D,a=new Ee.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=ar(c.color)??{r:255,g:255,b:255};s.setColorAt(l,a.setRGB(u.r/255,u.g/255,u.b/255,Ee.SRGBColorSpace))}if(s.instanceMatrix.needsUpdate=!0,s.instanceColor)s.instanceColor.needsUpdate=!0;this.scene.add(s),this.mesh=s}updateCamera(){let e=new Ee.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 Ee.Vector3(0,this.sceneCenterY,0);this.camera.position.copy(t).addScaledVector(e,100),this.camera.lookAt(t);let r=new Ee.Vector3(Math.sin(Jt)*Math.cos(cr),Math.sin(cr),Math.cos(Jt)*Math.cos(cr)),n=new Ee.Vector3(Math.cos(Jt),0,-Math.sin(Jt)),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)*Rg*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 Yi(){return{grid:[],yaw:Jt,pitch:cr,zoom:1}}var yc=Dg.fromInts(22,8,33),Lg=250;class Mo extends Ng{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??Yi(),a=new Kn(o,"terminal");super(e,{...s,scene:a.scene,camera:a.camera,autoAspect:!1,live:!1,renderer:{backgroundColor:yc,superSample:Mg.GPU,...i}});this.currentModel=o,this.sceneController=a,this.initErrorHandler=n,this.sceneController.setAspect(this.aspectRatio),setTimeout(()=>void this.warmUp(),Lg);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(xr("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),xr("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)Wi(e,this.width,this.height,yc)}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 Fg,Renderable as Gg,RGBA as Ug}from"@opentui/core";import{CLICanvas as Hg,SuperSampleType as jg,THREE as Qi}from"@opentui/three";import{createWebGPUDevice as Kg,setupGlobals as Wg}from"bun-webgpu";import{WebGPURenderer as Yg}from"three/webgpu";var Ji=[22,8,33],wc=Ug.fromInts(...Ji),Qg=250,vc=64,Jg=250,Vg=150,Zg=0.4;class No extends Gg{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??Yi(),this.sceneController=new Kn(this.currentModel,"raster"),this.initErrorHandler=n,this.scheduleRender(),setTimeout(()=>void this.warmUp(),Qg)}async warmUp(){if(this.warmedUp||this.rendering||this.failed||this.destroyRequested)return;this.rendering=!0;try{if(await this.ensureRenderer(vc,vc),this.destroyRequested)return;this.sceneController.update(this.currentModel,1);let e=performance.now();await this.webgpuRenderer.render(this.sceneController.scene,this.sceneController.camera),xr("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<Jg,this.lastModelUpdate=t,this.refineTimer)clearTimeout(this.refineTimer);this.refineTimer=setTimeout(()=>{if(this.refineTimer=null,!this.lowDetail)return;this.lowDetail=!1,this.scheduleRender()},Vg),this.scheduleRender()}set onInitError(e){this.initErrorHandler=e}renderSelf(e){e.clear(wc);let t=this.frame,r=xt(this._ctx);if(!t||!r||!lr(this._ctx.capabilities)){if(!t&&!this.failed)Wi(e,this.width,this.height,wc);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.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 ec(this.width,this.height,e.width,e.height,this.lowDetail?{density:Zg}: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 Wg();let n=await Kg();xr("voxel raster device",r);let i=new Hg(n,e,t,jg.NONE),s=new Yg({canvas:i,device:n,alpha:!0});s.outputColorSpace=Qi.SRGBColorSpace,s.toneMapping=Qi.NoToneMapping,s.setClearColor(new Qi.Color().setRGB(Ji[0]/255,Ji[1]/255,Ji[2]/255,Qi.SRGBColorSpace),1),s.setSize(e,t,!1),await s.init(),xr("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=Fg.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 _c={name:"flatblox-tui",version:"0.2.10",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 Vi=`v${_c.version}`;import{NativeImage as Cc,parseColor as Xg}from"@opentui/core";Kt({fitted_image:Gn});var zg=new URL("./flatblox-logo.png",import.meta.url),qg=Cc.load(zg),Lo=new Map;function em(e){let t=Lo.get(e);if(!t)t=qg.then((r)=>{let[n,i,s]=Xg(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=Cc.fromRgba(o,r.width,r.height);try{return a.composite(r)}finally{a.dispose()}}),t.catch(()=>Lo.delete(e)),Lo.set(e,t);return t}function Xr(e){let t=ht(),r=Zr(),[n,i]=j(),s=!1;return br(()=>{em(e.backgroundColor).then((o)=>{if(!s)i(o),t.requestRender()},()=>{})}),ot(()=>{s=!0}),J(Te,{get when(){return lt(()=>!!r())()&&n()},get fallback(){return(()=>{var o=S("box");return h(o,"alignItems","center"),h(o,"justifyContent","center"),L(o,J(Te,{get when(){return e.height>=2},get fallback(){return(()=>{var a=S("text"),l=S("b");return R(a,l),R(l,ke("FLATBLOX")),fe((c)=>h(a,"fg",e.foregroundColor,c)),a})()},get children(){var a=S("ascii_font");return h(a,"text","FLATBLOX"),h(a,"font","tiny"),fe((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}})),fe((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 fe((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}})}Kt({pixel_grid:Po,voxel_raster:No,voxel_preview:Mo});var E={background:Ke("hsl(275 45% 12%)"),panel:Ke("hsl(275 45% 14%)"),panelActive:Ke("hsl(275 45% 17%)"),card:Ke("hsl(275 45% 19%)"),border:Ke("hsl(275 45% 31%)"),text:Ke("hsl(278 100% 80%)"),muted:Ke("hsl(278 41% 65%)"),accent:Ke("hsl(315 68% 71%)"),accentText:Ke("hsl(278 70% 80%)"),warning:Ke("hsl(37 100% 71%)"),textPink:Ke("hsl(308, 50%, 75%)"),orangeActive:Ke("hsl(28, 80%, 38%)")};function Ke(e){let t=ar(e);return t?Sn(t):"#ffffff"}function Zt(e){return e[0].toUpperCase()+e.slice(1)}function rm(e){let t=e.depthAt(e.cursor.x,e.cursor.y);return t===null?"-":String(t)}function nm(e){return(()=>{var t=S("box");return h(t,"flexDirection","column"),h(t,"gap",0),L(t,J(bt,{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=ke(" ");return R(o,a),h(o,"height",1),h(o,"flexDirection","row"),h(o,"paddingX",1),L(o,J(Un,{get color(){return Ke(r)},get background(){return lt(()=>!!i())()?E.panelActive:E.panel}}),a),R(a,l),L(a,()=>i()?" \u203A ":" ",l),L(a,s,l),L(a,()=>Ke(r),null),fe((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 im(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}`,depth:rm(e.session)}));return(()=>{var r=S("box"),n=S("box"),i=S("box"),s=S("text"),o=ke("Tool: "),a=S("text"),l=ke("Cursor: "),c=S("text"),u=ke("Depth: "),d=S("box"),f=S("box"),m=S("box"),A=S("text"),g=ke("Mirror X: "),b=S("text"),w=ke("Mirror Y: ");return R(r,n),h(r,"id","sidebar"),h(r,"flexDirection","column"),h(r,"paddingY",1),R(n,i),R(n,d),R(n,f),R(n,m),h(n,"width","100%"),h(n,"flexDirection","column"),h(n,"paddingX",1),R(i,s),R(i,a),R(i,c),h(i,"flexDirection","column"),R(s,o),L(s,()=>t().tool,null),R(a,l),L(a,()=>t().cursor,null),R(c,u),L(c,()=>t().depth,null),h(d,"height",1),L(n,J(nm,{get session(){return e.session},get colors(){return e.colors},get refresh(){return e.refresh}}),f),h(f,"height",1),R(m,A),R(m,b),h(m,"flexDirection","column"),R(A,g),L(A,()=>t().mirrorX,null),R(b,w),L(b,()=>t().mirrorY,null),fe((p)=>{var C=e.visible?28:0,_=e.visible,y=E.panel,v=E.textPink,x=E.textPink,O=E.textPink,D=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)),O!==p.n&&(p.n=h(c,"fg",O,p.n)),D!==p.s&&(p.s=h(A,"fg",D,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 sm(e){let t=K(()=>{e.refresh();let r=`${e.session.mirrorX?"X":"-"}${e.session.mirrorY?"Y":"-"}`;return{tool:Zt(e.session.tool),color:Ke(e.colors[e.session.selectedColorIndex]??e.session.activeColor),mirror:r}});return(()=>{var r=S("box"),n=S("text"),i=ke("Tool "),s=ke(" Color "),o=S("text"),a=ke(" "),l=ke(" Mirror ");return R(r,n),R(r,o),h(r,"border",!0),h(r,"borderStyle","rounded"),h(r,"paddingX",1),h(r,"flexDirection","row"),R(n,i),R(n,s),L(n,()=>t().tool,s),L(r,J(Un,{get color(){return t().color},get background(){return E.panel}}),o),R(o,a),R(o,l),L(o,()=>t().color,l),L(o,()=>t().mirror,null),fe((c)=>{var u=e.visible?3:0,d=e.visible,f=E.border,m=E.panel,A=E.textPink,g=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)),m!==c.o&&(c.o=h(r,"backgroundColor",m,c.o)),A!==c.i&&(c.i=h(n,"fg",A,c.i)),g!==c.n&&(c.n=h(o,"fg",g,c.n)),c},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),r})()}var om=11;function am(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 lm(e){let t=K(()=>am(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,J(bt,{get each(){return t()},children:([s,o])=>(()=>{var a=S("box"),l=S("text"),c=S("text");return R(a,l),R(a,c),h(a,"flexDirection","row"),L(l,()=>s.padEnd(om)),L(c,o),fe((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})()})),fe((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,m=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)),m!==s.h&&(s.h=h(i,"titleColor",m,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 cm(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 R(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"),R(s,o),R(s,a),R(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",co),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"),fe((c)=>{var u=Math.max(0,Math.floor((e.width-t())/2)),d=Math.max(0,Math.floor((e.height-r())/2)),f=t(),m=r(),A=E.border,g=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,O=e.onSubmit,D=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)),m!==c.o&&(c.o=h(i,"height",m,c.o)),A!==c.i&&(c.i=h(i,"borderColor",A,c.i)),g!==c.n&&(c.n=h(i,"backgroundColor",g,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)),O!==c.m&&(c.m=h(o,"on:enter",O,c.m)),D!==c.f&&(c.f=h(a,"height",D,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 um={svg:"SVG flat vector",obj:"OBJ voxel mesh (+ .mtl)",png:"PNG 16px per cell"};function dm(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 R(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"),R(i,s),R(i,o),R(i,a),R(i,l),R(i,c),h(i,"flexGrow",1),h(i,"width","100%"),h(i,"padding",1),h(i,"flexDirection","column"),L(i,J(bt,{each:Ot,children:(u,d)=>(()=>{var f=S("box"),m=S("text");return R(f,m),h(f,"flexDirection","row"),L(m,()=>e.focus==="formats"&&e.cursor===d()?"\u203A ":" ",null),L(m,()=>e.formats.includes(u)?"[x] ":"[ ] ",null),L(m,()=>um[u],null),fe((A)=>h(m,"fg",e.focus==="formats"&&e.cursor===d()?E.accent:E.text,A)),f})()}),s),h(s,"height",1),R(o,ke("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")),fe((u)=>{var d=Math.max(0,Math.floor((e.width-t())/2)),f=Math.max(0,Math.floor((e.height-r())/2)),m=t(),A=r(),g=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,O=E.text,D=e.focus==="path",P=e.onPathInput,T=e.onSubmit,U=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)),m!==u.a&&(u.a=h(n,"width",m,u.a)),A!==u.o&&(u.o=h(n,"height",A,u.o)),g!==u.i&&(u.i=h(n,"borderColor",g,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)),O!==u.w&&(u.w=h(a,"focusedTextColor",O,u.w)),D!==u.m&&(u.m=h(a,"focused",D,u.m)),P!==u.f&&(u.f=h(a,"onInput",P,u.f)),T!==u.y&&(u.y=h(a,"on:enter",T,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=Zr(),n=Ur(),[i,s]=j(0),[o,a]=j("Ready"),[l,c]=j(!1),[u,d]=j(null),[f,m]=j(null),[A,g]=j(!1),[b,w]=j(!1),[p,C]=j(""),[_,y]=j(""),[v,x]=j(!1),[O,D]=j(["svg"]),[P,T]=j(0),[U,V]=j("formats"),[Q,te]=j(""),[ae,q]=j(""),[De,Se]=j(2),[z,Z]=j(2),[le,ge]=j(!1),[N,ne]=j(!1),[ie,ce]=j(""),Ze=tc(),[me,Re]=j(Jt),[At,Xe]=j(cr),[ze,re]=j(null),kt=!e.blenderLive,B=e.blenderLive??new Co(()=>e.session.toDocument()),[W,pe]=j(B.getStatus()),at=B.onStatus(pe);ot(()=>{if(at(),kt)B.dispose()});let vt=K(()=>n().width>=88&&n().height>=19),Ne=()=>i(),it=()=>N()&&!le()?"50%":"100%",[Ye,gr]=j(0),ee=(k=!1)=>{if(s((I)=>I+1),k)gr((I)=>I+1),B.sync()},hn=()=>(i(),e.session.dirty),_t=K(()=>(i(),In(e.session.palette,e.session.paletteColorAdjustment.saturation,e.session.paletteColorAdjustment.lightness))),mr=K(()=>(Ye(),Wt(e.session.grid,e.session.paletteColorAdjustment.saturation,e.session.paletteColorAdjustment.lightness))),fn=K(()=>{i();let k=u(),I=e.session.tool;if(!k||!Vr(I))return;let F=e.session;return{points:F.shapePreview(I,k,F.cursor).flatMap((be)=>Ln(F.size,be,F.mirrorX,F.mirrorY)),color:Ke(_t()[F.selectedColorIndex]??F.activeColor)}}),zt=K(()=>(i(),{grid:mr(),revision:Ye(),cursor:e.session.cursor,zoom:De(),preview:fn(),depthLabels:e.session.tool==="extrude"})),Gt=K(()=>({grid:mr(),revision:Ye(),yaw:me(),pitch:At(),zoom:z()})),Rt=()=>{if(f())m(null)},Nr=(k,I)=>{if(!Vr(k))return!1;let F=u();if(!F)return d({...I}),a(`${Zt(k)} from ${I.x+1}, ${I.y+1} \xB7 Space or click to finish \xB7 Esc cancels`),ee(),!0;let ve=e.session.applyShape(k,F,I);return d(null),ee(ve),a(ve?`${Zt(k)} drawn`:"No change"),!0},fi=()=>{if(!u())return!1;return d(null),a(`${Zt(e.session.tool)} cancelled`),ee(),!0},Ai=(k=e.session.tool)=>{if(Rt(),Nr(k,e.session.cursor))return;let I=e.session.applyAtCursor(k);ee(I),a(I?`${Zt(k)} applied`:"No change")},gi=(k,I)=>{Rt(),e.session.moveCursor(k,I);let F=ze(),ve=F?e.session.applyAtCursor(F):!1;ee(ve),a(F&&ve?`${Zt(F)} at ${e.session.cursor.x+1}, ${e.session.cursor.y+1}`:`Cell ${e.session.cursor.x+1}, ${e.session.cursor.y+1}`)},Ae=(k)=>{let I=k==="undo"?e.session.undo():e.session.redo();a(I?k==="undo"?"Undo":"Redo":`Nothing to ${k}`),ee(I)},Ce=(k)=>{e.session.selectNextColor(k),Rt(),a(`Color ${e.session.selectedColorIndex+1}`),ee()},Le=async()=>{if(A())return;let k=e.session.revision,I=e.session.toDocument();g(!0),a("Saving\u2026");try{let F;if(e.saveDocument)F=await e.saveDocument(I);else{let be=e.filePath??`${e.session.filename}.flatblox.json`,gt=Mn(I);if(e.writeFile)await e.writeFile(be,gt);else await Bun.write(be,gt);F=`Saved ${be}`}let ve=e.session.markSaved(k);m(null),a(ve?F||"Saved":`${F||"Saved"}; newer edits remain unsaved`),ee()}catch(F){let ve=F instanceof Error?F.message:String(F);a(`Save failed: ${ve}`)}finally{g(!1)}},xe=()=>Ni("",e.session.filename,Hn(e.filePath,e.session.filename)),he="",se=async()=>{if(A())return;let k=await lc();he=k?Ni(`${k}/`,e.session.filename,xe()):xe(),te(he),q(""),T(0),V("formats"),x(!0),a("Choose export formats and destination")},oe=()=>{x(!1),a("Export cancelled")},Fe=(k)=>{D((I)=>I.includes(k)?I.filter((F)=>F!==k):Ot.filter((F)=>F===k||I.includes(F))),q("")},Ge=async()=>{let k=O();if(k.length===0){q("Select at least one format");return}let I=Ni(Q(),e.session.filename,xe());x(!1),g(!0),a("Exporting\u2026");try{let ve=(await Li(e.session.toDocument(),I,k,e.writeFile)).map((be)=>tm(be));if(a(`Exported ${ve.join(", ")} to ${Zi(I)}`),Zi(I)!==Zi(he))await cc(Zi(I)).catch(()=>{})}catch(F){let ve=F instanceof Error?F.message:String(F);a(`Export failed: ${ve}`)}finally{g(!1)}},Me=(k)=>{let I=k.name.toLowerCase();if(I==="escape")oe();else if(I==="tab")V((F)=>F==="path"?"formats":"path");else if(U()==="path")return;else if(I==="return"||I==="enter")Ge();else if(I==="up"||I==="k")T((F)=>(F+Ot.length-1)%Ot.length);else if(I==="down"||I==="j")T((F)=>(F+1)%Ot.length);else if(ur(k))Fe(Ot[P()])},qe=()=>{if(e.promptForFilenameOnSave){C(""),y(""),w(!0),a("Name artwork before saving");return}Le()},et=(k)=>{let I=kn(k);if(!I){y("Enter an artwork name");return}e.session.rename(I),y(""),w(!1),ee(),Le()},Ct=()=>{w(!1),y(""),a("Save cancelled")},An=(k)=>{if(!hn()||f()===k){if(k==="back"&&e.onBack)e.onBack();else t.destroy();return}m(k),a(k==="back"?"Unsaved changes \u2014 press Escape again to return":"Unsaved changes \u2014 press Q again to quit")},mi=(k)=>{Rt();let{x:I,y:F}=e.session.cursor,ve=e.session.extrudeAt(I,F,k);ee(ve);let be=e.session.depthAt(I,F);a(be===null?"No cell to extrude":ve?`Depth ${be}`:`Depth ${be} (${k>0?"max":"min"})`)},qt=(k)=>{e.session.setTool(k),d(null),Rt(),a(`${Zt(k)} tool`),ee()},pi=(k)=>{let I=le(),F=I?z():De(),ve=I?0.25:1,be=I&&k>0&&F<1?1:F+k,gt=Math.max(ve,Math.min(8,be));if(I)Z(gt);else Se(gt);a(`Zoom ${gt}\xD7`)},Ud=()=>{if(!le()&&!Ze){a("3D preview is unavailable on this platform");return}if(!le()&&ie()){a(`3D unavailable: ${ie()}`);return}re(null),d(null),ge((k)=>(a(k?"2D editor":"Voxel preview"),!k))},Hd=()=>{if(!N()&&!Ze){a("3D preview is unavailable on this platform");return}if(!N()&&ie()){a(`3D unavailable: ${ie()}`);return}ge(!1),ne((k)=>(a(k?"2D editor":"Split view"),!k))},jd=(k,I)=>{Re((F)=>F+k*0.16),Xe((F)=>Math.max(0.18,Math.min(1.15,F-I*0.12))),a("3D orbit")},Kd=()=>{Re(Jt),Xe(cr),a("Rotation reset")},va=(k)=>{if(ce(k),ne(!1),!le())return;ge(!1),a(`3D unavailable: ${k}`)},Wd=async()=>{let k=B.getStatus();if(k.state==="connected"||k.state==="connecting"){B.disconnect(),a("Blender Live disconnected");return}a("Connecting to Blender\u2026");let I=await B.connect();a(I.state==="connected"?"Drawing live in Blender":I.message??"Blender Live disconnected")},Yd=(k)=>{e.session.setCursor(k.x,k.y);let I=k.tool??e.session.tool;if(Rt(),Nr(I,{x:k.x,y:k.y}))return;let F=e.session.applyAt(k.x,k.y,I);a(F?`${Zt(I)} at ${k.x+1}, ${k.y+1}`:`Cell ${k.x+1}, ${k.y+1}`),ee(F)};Hr((k)=>{let I=k.name.toLowerCase(),F=k.sequence,ve=ur(k),be=Cr(I);if(k.eventType==="release"){if(ve)re(null);return}if(b())return;if(v()){Me(k);return}if(l()){if(I==="escape"||F==="?")c(!1);return}let gt=I==="q"||I==="escape"||k.ctrl&&I==="c";if(f()&&!gt)m(null);if(k.ctrl){if(I==="s")qe();else if(I==="e")se();else if(I==="z"&&k.shift)Ae("redo");else if(I==="z")Ae("undo");else if(I==="y")Ae("redo");else if(I==="c")An("quit");return}if(F==="?"){c(!0);return}if(I==="escape"&&fi())return;if(I==="escape"&&e.onBack){An("back");return}if(I==="q"||I==="escape"){An("quit");return}if(I==="c"){Ud();return}if(I==="p"){Hd();return}if(le()){if(I==="r")Kd();else if(be)jd(be.dx,be.dy);else if(F==="+"||I==="+"||I==="=")pi(1);else if(F==="-"||I==="-")pi(-1);return}if(be)gi(be.dx,be.dy);else if(ve){let st=e.session.tool;re(k.source==="kitty"&&(st==="draw"||st==="erase")?st:null),Ai(st)}else if(I==="b")Wd();else if(I==="d")qt("draw");else if(I==="e")qt("erase");else if(I==="f")qt("fill");else if(I==="r")qt("rectangle");else if(I==="o")qt("circle");else if(I==="x"&&(k.shift||F==="X"))e.session.toggleMirrorX(),a(`Mirror X ${e.session.mirrorX?"on":"off"}`),ee();else if(I==="y"&&(k.shift||F==="Y"))e.session.toggleMirrorY(),a(`Mirror Y ${e.session.mirrorY?"on":"off"}`),ee();else if(I==="x")qt(e.session.tool==="extrude"?"draw":"extrude");else if(I==="s")mi(1);else if(I==="a")mi(-1);else if(I==="u")Ae("undo");else if(F==="+"||I==="+"||I==="=")pi(1);else if(F==="-"||I==="-")pi(-1);else if(F==="[")Ce(-1);else if(F==="]")Ce(1);else if(/^[0-9]$/.test(I))e.session.selectColor(I==="0"?9:Number(I)-1),a(`Color ${e.session.selectedColorIndex+1}`),ee()},{release:!0});let Qd=()=>{i();let k=e.session.dirty?" \u25CF":"";return`${e.session.filename}${k} ${e.session.size}\xD7${e.session.size}`},Jd=()=>{switch(W().state){case"connecting":return"connecting";case"connected":return"live";case"error":return"error";default:return"off"}},_a=K(()=>`Blender:${Jd()} | ${o()}`),Ca=K(()=>`C ${le()?"2D":"3D"} \xB7 P split \xB7 ${le()?"R reset \xB7 ":""}`+"-/+ zoom \xB7 ? help \xB7 Ctrl+S save \xB7 Ctrl+E export \xB7 "+`${e.onBack?"Esc artworks \xB7 ":""}Q quit`),Vd=K(()=>_a().length+Ca().length+1<=n().width-2);return(()=>{var k=S("box"),I=S("box"),F=S("text"),ve=S("b"),be=S("box"),gt=S("text"),st=S("box"),er=S("box"),tr=S("pixel_grid"),Ut=S("box"),Ds=S("text");return R(k,I),R(k,st),R(k,Ut),h(k,"width","100%"),h(k,"height","100%"),h(k,"flexDirection","column"),R(I,F),R(I,be),R(I,gt),h(I,"height",3),h(I,"paddingX",1),h(I,"paddingY",1),h(I,"flexDirection","row"),h(I,"justifyContent","space-between"),R(F,ve),L(ve,Vi),h(be,"height",1),h(be,"flexBasis",0),h(be,"flexGrow",1),h(be,"flexDirection","row"),h(be,"justifyContent","center"),L(be,J(Xr,{id:"dashboard-wordmark",width:14,height:1,get backgroundColor(){return E.panel},get foregroundColor(){return E.accent}})),L(gt,Qd),R(st,er),h(st,"flexGrow",1),h(st,"flexDirection","row"),h(st,"paddingLeft",1),h(st,"paddingY",1),h(st,"gap",1),R(er,tr),h(er,"flexGrow",1),h(er,"flexDirection","row"),h(er,"gap",1),h(er,"overflow","hidden"),h(tr,"id","pixel-grid"),h(tr,"height","100%"),h(tr,"flexGrow",1),h(tr,"onCell",Yd),L(er,J(Te,{when:Ze,get children(){return J(Te,{get when(){return r()},get fallback(){return(()=>{var H=S("voxel_preview");return h(H,"id","voxel-preview"),h(H,"height","100%"),h(H,"flexGrow",1),h(H,"onInitError",va),fe((ye)=>{var rr=it(),nr=le()||N(),ir=Gt();return rr!==ye.e&&(ye.e=h(H,"width",rr,ye.e)),nr!==ye.t&&(ye.t=h(H,"visible",nr,ye.t)),ir!==ye.a&&(ye.a=h(H,"model",ir,ye.a)),ye},{e:void 0,t:void 0,a:void 0}),H})()},get children(){var H=S("voxel_raster");return h(H,"id","voxel-preview"),h(H,"height","100%"),h(H,"flexGrow",1),h(H,"onInitError",va),fe((ye)=>{var rr=it(),nr=le()||N(),ir=Gt();return rr!==ye.e&&(ye.e=h(H,"width",rr,ye.e)),nr!==ye.t&&(ye.t=h(H,"visible",nr,ye.t)),ir!==ye.a&&(ye.a=h(H,"model",ir,ye.a)),ye},{e:void 0,t:void 0,a:void 0}),H}})}}),null),L(st,J(Te,{get when(){return lt(()=>!!vt())()&&!le()},get children(){return J(im,{get session(){return e.session},get colors(){return _t()},refresh:Ne,visible:!0})}}),null),L(k,J(Te,{get when(){return lt(()=>!vt())()&&!le()},get children(){return J(sm,{get session(){return e.session},get colors(){return _t()},refresh:Ne,visible:!0})}}),Ut),R(Ut,Ds),h(Ut,"height",1),h(Ut,"paddingX",1),h(Ut,"flexDirection","row"),h(Ut,"justifyContent","space-between"),L(Ds,_a),L(Ut,J(Te,{get when(){return Vd()},get children(){var H=S("text");return L(H,Ca),fe((ye)=>h(H,"fg",E.muted,ye)),H}}),null),L(k,J(lm,{get width(){return n().width},get height(){return n().height},get visible(){return l()},get canGoBack(){return Boolean(e.onBack)}}),null),L(k,J(Te,{get when(){return v()},get children(){return J(dm,{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 Q()},get error(){return ae()},onPathInput:(H)=>{if(te(H),ae())q("")},onSubmit:()=>void Ge(),onCancel:oe})}}),null),L(k,J(Te,{get when(){return b()},get children(){return J(cm,{get width(){return n().width},get height(){return n().height},get value(){return p()},get error(){return _()},onInput:(H)=>{if(C(H),_())y("")},onSubmit:et,onCancel:Ct})}}),null),fe((H)=>{var{background:ye,panel:rr}=E,nr=W().state==="error"?E.warning:E.accentText,ir=hn()?E.warning:E.muted,xa=vt()&&!le()?0:1,Ea=E.background,Sa=E.background,Ia=it(),ka=!le(),Ra=zt(),Ta=E.panelActive,Ba=o().startsWith("Save failed")||W().state==="error"?E.warning:E.textPink;return ye!==H.e&&(H.e=h(k,"backgroundColor",ye,H.e)),rr!==H.t&&(H.t=h(I,"backgroundColor",rr,H.t)),nr!==H.a&&(H.a=h(F,"fg",nr,H.a)),ir!==H.o&&(H.o=h(gt,"fg",ir,H.o)),xa!==H.i&&(H.i=h(st,"paddingRight",xa,H.i)),Ea!==H.n&&(H.n=h(st,"backgroundColor",Ea,H.n)),Sa!==H.s&&(H.s=h(er,"backgroundColor",Sa,H.s)),Ia!==H.h&&(H.h=h(tr,"width",Ia,H.h)),ka!==H.r&&(H.r=h(tr,"visible",ka,H.r)),Ra!==H.d&&(H.d=h(tr,"model",Ra,H.d)),Ta!==H.l&&(H.l=h(Ut,"backgroundColor",Ta,H.l)),Ba!==H.u&&(H.u=h(Ds,"fg",Ba,H.u)),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,u:void 0}),k})()}import{chmod as n0,mkdir as i0,readFile as s0,rename as o0,unlink as a0,writeFile as l0}from"fs/promises";import{homedir as c0}from"os";import{dirname as u0,join as Ad}from"path";var qc=rh(zc(),1),{__extends:Sx,__assign:Ix,__rest:Er,__decorate:kx,__param:Rx,__esDecorate:Tx,__runInitializers:Bx,__propKey:Ox,__setFunctionName:Px,__metadata:Dx,__awaiter:eu,__generator:Mx,__exportStar:Nx,__createBinding:Lx,__values:Fx,__read:Gx,__spread:Ux,__spreadArrays:Hx,__spreadArray:jx,__await:Kx,__asyncGenerator:Wx,__asyncDelegator:Yx,__asyncValues:Qx,__makeTemplateObject:Jx,__importStar:Vx,__importDefault:Zx,__classPrivateFieldGet:$x,__classPrivateFieldSet:Xx,__classPrivateFieldIn:zx,__addDisposableResource:qx,__disposeResources:eE,__rewriteRelativeImportExtension:tE}=qc.default;var tu=(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 qi 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 es{constructor(e,{headers:t={},customFetch:r,region:n=Wn.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=tu(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return eu(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 m=new URL(`${this.url}/${t}`);if(f&&f!=="any")d["x-region"]=f,m.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 g=c;if(u)if(s=new AbortController,i=setTimeout(()=>s.abort(),u),c)g=s.signal,c.addEventListener("abort",()=>s.abort());else g=s.signal;let b=yield this.fetch(m.toString(),{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),o),body:A,signal:g}).catch((_)=>{throw new qi(_)}),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 ru=(e)=>Math.min(1000*2**e,30000),hm=[520,503],ou=["GET","HEAD","OPTIONS"],au=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 nu(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 fm(e,t,r,n){if(!n||r>=3)return!1;if(!ou.includes(e))return!1;if(!hm.includes(t))return!1;return!0}var Am=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(!ou.includes(r.method))throw d;if(r.retryEnabled&&o<3){let f=ru(o);o++,await nu(f,r.signal);continue}throw d}if(fm(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:ru(o);await u.text(),o++,await nu(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,m,A,g;let p=(f=d===null||d===void 0?void 0:d.message)!==null&&f!==void 0?f:"",C=(m=d===null||d===void 0?void 0:d.code)!==null&&m!==void 0?m:"";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: ${(g=d===null||d===void 0?void 0:d.name)!==null&&g!==void 0?g:"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 au(r)}return{success:r===null,error:r,data:n,count:i,status:s,statusText:o}}returns(){return this}overrideTypes(){return this}},gm=class extends Am{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}},iu=new RegExp("[,()]"),en=class extends gm{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"&&iu.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"&&iu.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}},mm=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 en({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 en({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 en({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 en({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 en({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 pm(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 bm(e){var t=pm(e,"string");return Vn(t)=="symbol"?t:t+""}function ym(e,t,r){return(t=bm(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function su(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 ts(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?su(Object(r),!0).forEach(function(n){ym(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):su(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var lu=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),m=u===null||u===void 0?void 0:u.signal;if(m){if(m.aborted)return clearTimeout(f),l(c,u);let A=()=>{clearTimeout(f),d.abort()};return m.addEventListener("abort",A,{once:!0}),l(c,ts(ts({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(f),m.removeEventListener("abort",A)})}return l(c,ts(ts({},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 mm(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=(m)=>m!==null&&typeof m==="object"&&(!Array.isArray(m)||m.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(([m,A])=>A!==void 0).map(([m,A])=>[m,Array.isArray(A)?`{${A.join(",")}}`:`${A}`]).forEach(([m,A])=>{l.searchParams.append(m,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 en({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 cu{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 Go=cu;var uu="2.103.0";var du=`realtime-js/${uu}`,hu="1.0.0",Uo="2.0.0",fu=Uo;var Au=1e4;var gu=100;var Pt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},rs={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 ns{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),m=new DataView(f),A=0;m.setUint8(A++,this.KINDS.userBroadcastPush),m.setUint8(A++,a.length),m.setUint8(A++,o.length),m.setUint8(A++,s.length),m.setUint8(A++,l.length),m.setUint8(A++,u.length),m.setUint8(A++,t),Array.from(a,(b)=>m.setUint8(A++,b.charCodeAt(0))),Array.from(o,(b)=>m.setUint8(A++,b.charCodeAt(0))),Array.from(s,(b)=>m.setUint8(A++,b.charCodeAt(0))),Array.from(l,(b)=>m.setUint8(A++,b.charCodeAt(0))),Array.from(u,(b)=>m.setUint8(A++,b.charCodeAt(0)));var g=new Uint8Array(f.byteLength+r.byteLength);return g.set(new Uint8Array(f),0),g.set(new Uint8Array(r),f.byteLength),g.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,m={type:this.BROADCAST_EVENT,event:c,payload:f};if(s>0)m.meta=JSON.parse(u);return{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:m}}_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 we;(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"})(we||(we={}));var jo=(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]=wm(o,e,t,i),s),{})},wm=(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 mu(s,o);return Ho(o)},mu=(e,t)=>{if(e.charAt(0)==="_"){let r=e.slice(1,e.length);return xm(t,r)}switch(e){case we.bool:return vm(t);case we.float4:case we.float8:case we.int2:case we.int4:case we.int8:case we.numeric:case we.oid:return _m(t);case we.json:case we.jsonb:return Cm(t);case we.timestamp:return Em(t);case we.abstime:case we.date:case we.daterange:case we.int4range:case we.int8range:case we.money:case we.reltime:case we.text:case we.time:case we.timestamptz:case we.timetz:case we.tsrange:case we.tstzrange:return Ho(t);default:return Ho(t)}},Ho=(e)=>e,vm=(e)=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},_m=(e)=>{if(typeof e==="string"){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},Cm=(e)=>{if(typeof e==="string")try{return JSON.parse(e)}catch(t){return e}return e},xm=(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)=>mu(t,a))}return e},Em=(e)=>{if(typeof e==="string")return e.replace(" ","T");return e},is=(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}},Im=typeof self<"u"?self:null,rn=typeof window<"u"?window:null,Dt=Im||rn||globalThis,km="2.0.0",Rm=1e4,Tm=1000,Mt={connecting:0,open:1,closing:2,closed:3},dt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},$t={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Ko={longpoll:"longpoll",websocket:"websocket"},Bm={complete:4},Wo="base64url.bearer.phx.",ss=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})}},pu=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))}},Om=class{constructor(e,t,r){this.state=dt.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 ss(this,$t.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new pu(()=>{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 ss(this,$t.leave,$n({}),this.timeout).send(),this.state=dt.errored,this.joinPush.reset(),this.socket.isConnected())this.rejoinTimer.scheduleTimeout()}),this.on($t.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($t.close,e)}onError(e){return this.on($t.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 ss(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($t.close,"leave")},r=new ss(this,$t.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=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}},as=class{static request(e,t,r,n,i,s,o){if(Dt.XDomainRequest){let a=new Dt.XDomainRequest;return this.xdomainRequest(a,e,t,n,i,s,o)}else if(Dt.XMLHttpRequest){let a=new Dt.XMLHttpRequest;return this.xhrRequest(a,e,t,r,n,i,s,o)}else if(Dt.fetch&&Dt.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 Dt.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===Bm.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)}`}},Pm=(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)},tn=class{constructor(e,t){if(t&&t.length===2&&t[1].startsWith(Wo))this.authToken=atob(t[1].slice(Wo.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=Mt.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Ko.websocket),"$1/"+Ko.longpoll)}endpointURL(){return as.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=Mt.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Mt.open||this.readyState===Mt.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=Mt.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=Pm(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=Mt.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=as.request(e,this.endpointURL(),t,r,this.timeout,o,(a)=>{if(this.reqs.delete(s),this.isActive())i(a)}),this.reqs.add(s)}},bu=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((g)=>g.phx_ref),f=u.metas.map((g)=>g.phx_ref),m=c.metas.filter((g)=>f.indexOf(g.phx_ref)<0),A=u.metas.filter((g)=>d.indexOf(g.phx_ref)<0);if(m.length>0)o[l]=c,o[l].metas=m;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))}},os={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),m={status:d,response:f};return{join_ref:l,ref:c,topic:u,event:$t.reply,payload:m}},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}}},yu=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||Rm,this.transport=t.transport||Dt.WebSocket||tn,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||Dt&&Dt.sessionStorage,this.establishedConnections=0,this.defaultEncoder=os.encode.bind(os),this.defaultDecoder=os.decode.bind(os),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!==tn)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(rn&&rn.addEventListener)rn.addEventListener("pagehide",(n)=>{if(this.conn)this.disconnect(),r=this.connectClock}),rn.addEventListener("pageshow",(n)=>{if(r===this.connectClock)r=null,this.connect()}),rn.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}/${Ko.websocket}`,this.vsn=t.vsn||km,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new pu(()=>{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 tn}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=as.appendParams(as.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!==tn)this.connectWithFallback(tn,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 tn:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e=void 0;if(this.authToken)e=["phoenix",`${Wo}${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(),Tm,"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===Mt.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($t.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Mt.connecting:return"connecting";case Mt.open:return"open";case Mt.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 Om(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=Mm(t);this.presence=new bu(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=Dm(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let n=e[r];return t[r]=ls(n),t},{})}static onJoinPayload(e,t,r){let n=wu(t),i=ls(r);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,t,r){let n=wu(t),i=ls(r);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}}function ls(e){return e.metas.map((t)=>(t.presence_ref=t.phx_ref,delete t.phx_ref,delete t.phx_ref_prev,t))}function Dm(e){return JSON.parse(JSON.stringify(e))}function Mm(e){return(e===null||e===void 0?void 0:e.events)&&{events:e.events}}function wu(e){return(e===null||e===void 0?void 0:e.metas)?ls(e):[]}var Yo;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(Yo||(Yo={}));class Xn{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new Sr(this.channel.channelAdapter,t)}}class cs{constructor(e,t,r){let n=Nm(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>gu){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===Pt.joined}isJoined(){return this.state===Pt.joined}isJoining(){return this.state===Pt.joining}isClosed(){return this.state===Pt.closed}isLeaving(){return this.state===Pt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function Nm(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 Nt;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(Nt||(Nt={}));class dr{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 cs(this.socket.socketAdapter,e,this.params),this.presence=new Xn(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=is(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&((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(Nt.CHANNEL_ERROR,f)}),this._onClose(()=>e===null||e===void 0?void 0:e(Nt.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(Nt.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",(f)=>{this.state=Pt.errored,e===null||e===void 0||e(Nt.CHANNEL_ERROR,Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e===null||e===void 0||e(Nt.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&&dr.isFilterValueEqual(f.schema,c)&&dr.isFilterValueEqual(f.table,u)&&dr.isFilterValueEqual(f.filter,d))s.push(Object.assign(Object.assign({},a),{id:f.id}));else{this.unsubscribe(),this.state=Pt.errored,t===null||t===void 0||t(Nt.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}if(this.bindings.postgres_changes=s,this.state!=Pt.errored&&t)t(Nt.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,m=(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))&&(m==="*"||(m===null||m===void 0?void 0:m.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}=rs;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=jo(e.columns,e.record);if(e.type==="UPDATE"||e.type==="DELETE")t.old=jo(e.columns,e.old_record);return t}}class us{constructor(e,t){this.socket=new yu(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 Lm={HEARTBEAT_INTERVAL:25000,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Fm=[1000,2000,5000,1e4],Gm=1e4,Um=`
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 ns,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 us(e,n),this.httpEndpoint=is(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 dr(`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:du};if(t&&n.updateJoinPayload(i),n.joinedOnce&&n.channelAdapter.isJoined())n.channelAdapter.push(rs.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([Um],{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:Lm.HEARTBEAT_INTERVAL,u.transport=(s=e===null||e===void 0?void 0:e.transport)!==null&&s!==void 0?s:Go.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)=>Fm[A-1]||Gm;let d,f,m=(a=e===null||e===void 0?void 0:e.vsn)!==null&&a!==void 0?a:fu;switch(m){case hu:d=(A,g)=>g(JSON.stringify(A)),f=(A,g)=>g(JSON.parse(A));break;case Uo: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=m,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 Hm(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 jm(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 Km(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:i,body:s,headers:o}){let a=Hm(e.baseUrl,n,i),l=await jm(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 m=d?f:void 0,A=m?.error;throw new qn(A?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:A?.type,icebergCode:A?.code,details:m})}return{status:c.status,headers:c.headers,data:f}}}}function ds(e){return e.join("\x1F")}var Wm=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:ds(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/${ds(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ds(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ds(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 nn(e){return e.join("\x1F")}var Ym=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/${nn(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/${nn(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/${nn(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/${nn(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/${nn(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/${nn(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}}},vu=class{constructor(e){let t="v1";if(e.catalogName)t+=`/${e.catalogName}`;let r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Km({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new Wm(this.client,t),this.tableOps=new Ym(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 fs=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 As(e){return typeof e==="object"&&e!==null&&"__isStorageError"in e}var hs=class extends fs{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}}},Eu=class extends fs{constructor(e,t,r="storage"){super(e,r);this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};var Qm=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)},Jm=(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)},Jo=(e)=>{if(Array.isArray(e))return e.map((r)=>Jo(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]=Jo(n)}),t},Vm=(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 Zm(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 $m(e){var t=Zm(e,"string");return ti(t)=="symbol"?t:t+""}function Xm(e,t,r){return(t=$m(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _u(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?_u(Object(r),!0).forEach(function(n){Xm(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_u(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var Cu=(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)},zm=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 hs(Cu(o),s,a,n))}).catch(()=>{let o=s+"";t(new hs(i.statusText||`HTTP ${s} error`,s,o,n))})}else t(new Eu(Cu(e),e,n))},qm=(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(Jm(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=ep(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 ep(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,qm(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)=>zm(c,l,n,o))})}function Su(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 tp=Su("storage"),{get:ri,post:Et,put:Vo,head:rp,remove:Zo}=tp,ft=Su("vectors"),sn=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=Qm(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(As(r))return{data:null,error:r};throw r}}},np=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(As(t))return{data:null,error:t};throw t}}},Iu;Iu=Symbol.toStringTag;var ip=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Iu]="BlobDownloadBuilder",this.promise=null}asStream(){return new np(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(As(t))return{data:null,error:t};throw t}}},sp={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},xu={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},op=class extends sn{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({},xu),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"?Vo:Et)(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({},xu),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 Vo(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 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 fs("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}`,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 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)=>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 ip(()=>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()=>Jo(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 rp(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(i){if(t.shouldThrowOnError)throw i;if(As(i)){var n;let s=i instanceof hs?i.status:i instanceof Eu?(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 Zo(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({},sp),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=X({},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}},ap="2.103.0",ni={"X-Client-Info":`storage-js/${ap}`},lp=class extends sn{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 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 Vo(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 Zo(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():""}},cp=class extends sn{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 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 ri(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await Zo(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!Vm(e))throw new fs("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 vu({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}}}}})}},up=class extends sn{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 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})||{})}},dp=class extends sn{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 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})||{})}},hp=class extends sn{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 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})||{})}},fp=class extends hp{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Ap(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)}},Ap=class extends up{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 gp(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},gp=class extends dp{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}))}},ku=class extends lp{constructor(e,t={},r,n){super(e,t,r,n)}from(e){return new op(this.url,this.headers,e,this.fetch)}get vectors(){return new fp(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new cp(this.url+"/iceberg",this.headers,this.fetch)}};var gs="2.103.0";var kr=30000,ms=3,ps=ms*kr,Ru="http://localhost:9999",Tu="supabase.auth.token";var Bu={"X-Client-Info":`gotrue-js/${gs}`};var ii="X-Supabase-Api-Version",$o={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Ou=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Pu=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 Xo extends Rr{constructor(e,t,r){super(e,t,r);this.name="AuthApiError",this.status=t,this.code=r}}function Du(e){return G(e)&&e.name==="AuthApiError"}class St extends Rr{constructor(e,t){super(e);this.name="AuthUnknownError",this.originalError=t}}class Lt extends Rr{constructor(e,t,r,n){super(e,r,n);this.name=t,this.status=r}}class nt extends Lt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function si(e){return G(e)&&e.name==="AuthSessionMissingError"}class hr extends Lt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class on extends Lt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class an extends Lt{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 Mu(e){return G(e)&&e.name==="AuthImplicitGrantRedirectError"}class bs extends Lt{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 zo extends Lt{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 Lt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function ys(e){return G(e)&&e.name==="AuthRetryableFetchError"}class ws extends Lt{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password");this.reasons=r}}class ln extends Lt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}var vs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Nu=`
44
+ \r=`.split(""),mp=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Nu.length;t+=1)e[Nu[t].charCodeAt(0)]=-2;for(let t=0;t<vs.length;t+=1)e[vs[t].charCodeAt(0)]=t;return e})();function Lu(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(vs[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(vs[n]),t.queuedBits-=6}}}function Fu(e,t,r){let n=mp[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 qo(e){let t=[],r=(o)=>{t.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=(o)=>{yp(o,n,r)};for(let o=0;o<e.length;o+=1)Fu(e.charCodeAt(o),i,s);return t.join("")}function pp(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 bp(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}pp(n,t)}}function yp(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 fr(e){let t=[],r={queue:0,queuedBits:0},n=(i)=>{t.push(i)};for(let i=0;i<e.length;i+=1)Fu(e.charCodeAt(i),r,n);return new Uint8Array(t)}function Gu(e){let t=[];return bp(e,(r)=>t.push(r)),new Uint8Array(t)}function Xt(e){let t=[],r={queue:0,queuedBits:0},n=(i)=>{t.push(i)};return e.forEach((i)=>Lu(i,r,n)),Lu(null,r,n),t.join("")}function Uu(e){return Math.round(Date.now()/1000)+e}function Hu(){return Symbol("auth-callback")}var We=()=>typeof window<"u"&&typeof document<"u",Tr={tested:!1,writable:!1},_s=()=>{if(!We())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 ju(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 Cs=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)},Ku=(e)=>typeof e==="object"&&e!==null&&("status"in e)&&("ok"in e)&&("json"in e)&&typeof e.json==="function",Br=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},Ar=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(n){return r}},Ve=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 ln("Invalid JWT structure");for(let n=0;n<t.length;n++)if(!Ou.test(t[n]))throw new ln("JWT not in base64url format");return{header:JSON.parse(qo(t[0])),payload:JSON.parse(qo(t[1])),signature:fr(t[2]),raw:{header:t[0],payload:t[1]}}}async function Wu(e){return await new Promise((t)=>{setTimeout(()=>t(null),e)})}function Yu(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 wp(e){return("0"+e.toString(16)).substr(-2)}function vp(){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,wp).join("")}async function _p(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 Cp(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 _p(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Or(e,t,r=!1){let n=vp(),i=n;if(r)i+="/PASSWORD_RECOVERY";await Br(e,`${t}-code-verifier`,i);let s=await Cp(n);return[s,n===s?"plain":"s256"]}var xp=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Qu(e){let t=e.headers.get(ii);if(!t)return null;if(!t.match(xp))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(r){return null}}function Ju(e){if(!e)throw Error("Missing exp claim");let t=Math.floor(Date.now()/1000);if(e<=t)throw Error("JWT has expired")}function Vu(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 Ep=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Pr(e){if(!Ep.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function xs(){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 Zu(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 ea(e){return JSON.parse(JSON.stringify(e))}var Dr=(e)=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Sp=[502,503,504];async function $u(e){var t;if(!Ku(e))throw new oi(Dr(e),0);if(Sp.includes(e.status))throw new oi(Dr(e),e.status);let r;try{r=await e.json()}catch(s){throw new St(Dr(s),s)}let n=void 0,i=Qu(e);if(i&&i.getTime()>=$o["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 ws(Dr(r),e.status,r.weak_password.reasons)}else if(n==="weak_password")throw new ws(Dr(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 Xo(Dr(r),e.status||500,n)}var Ip=(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 Y(e,t,r,n){var i;let s=Object.assign({},n===null||n===void 0?void 0:n.headers);if(!s[ii])s[ii]=$o["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 kp(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 kp(e,t,r,n,i,s){let o=Ip(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 $u(a);if(n===null||n===void 0?void 0:n.noResolveJson)return a;try{return await a.json()}catch(l){await $u(l)}}function wt(e){var t;let r=null;if(Rp(e)){if(r=Object.assign({},e),!e.expires_at)r.expires_at=Uu(e.expires_in)}let n=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:r,user:n},error:null}}function ta(e){let t=wt(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 Ft(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function Xu(e){return{data:e,error:null}}function zu(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 ra(e){return e}function Rp(e){return e.access_token&&e.refresh_token&&e.expires_in}var Es=["global","local","others"];class cn{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Cs(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=Es[0]){if(Es.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${Es.join(", ")}`);try{return await Y(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 Y(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Ft})}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 Y(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:zu,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 Y(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ft})}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 Y(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:ra});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((m)=>{let A=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(m.split(";")[1].split("=")[1]);l[`${g}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 Y(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ft})}catch(t){if(G(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Pr(e);try{return await Y(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Ft})}catch(r){if(G(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){Pr(e);try{return await Y(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Ft})}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 Y(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 Y(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 Y(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:ra});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((m)=>{let A=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(m.split(";")[1].split("=")[1]);l[`${g}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 Y(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 Y(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 Y(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 Y(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 Y(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 Y(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 Y(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 Y(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 Y(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 Y(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 na(e={}){return{getItem:(t)=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:(t)=>{delete e[t]}}}var It={debug:!!(globalThis&&_s()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Is extends Error{constructor(e){super(e);this.isAcquireTimeout=!0}}class Ss extends Is{}async function ia(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 Ss(`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 Ss(`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 sa(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function ed(e){return parseInt(e,16)}function td(e){let t=new TextEncoder().encode(e);return"0x"+Array.from(t,(n)=>n.toString(16).padStart(2,"0")).join("")}function rd(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 m=sa(e.address),A=u?`${u}://${n}`:n,g=e.statement?`${e.statement}
46
+ `:"",b=`${A} wants you to sign in with your Ethereum account:
47
+ ${m}
48
48
 
49
- ${m}`,v=`URI: ${d}
50
- Version: ${A}
49
+ ${g}`,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 Oe 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 un extends Oe{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e});this.name="WebAuthnUnknownError",this.originalError=t}}function nd({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 Oe({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 Oe({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 Oe({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 Oe({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 Oe({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});else if(e.name==="NotAllowedError")return new Oe({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 Oe({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e});return new Oe({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(!oa(o))return new Oe({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});else if(s.rp.id!==o)return new Oe({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 Oe({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 Oe({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 Oe({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function id({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 Oe({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="NotAllowedError")return new Oe({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if(e.name==="SecurityError"){let n=window.location.hostname;if(!oa(n))return new Oe({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});else if(r.rpId!==n)return new Oe({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 Oe({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 Oe({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class od{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 Tp=new od;function ad(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=fr(t).buffer,o=Object.assign(Object.assign({},r),{id:fr(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:fr(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function ld(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=fr(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:fr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function cd(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:Xt(new Uint8Array(e.response.attestationObject)),clientDataJSON:Xt(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:(t=r.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function ud(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:Xt(new Uint8Array(i.authenticatorData)),clientDataJSON:Xt(new Uint8Array(i.clientDataJSON)),signature:Xt(new Uint8Array(i.signature)),userHandle:i.userHandle?Xt(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(t=r.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function oa(e){return e==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function sd(){var e,t;return!!(We()&&("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 Bp(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new un("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new un("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:nd({error:t,options:e})}}}async function Op(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new un("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new un("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:id({error:t,options:e})}}}var Pp={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Dp={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function ks(...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]=ks(a,o);else n[s]=ks(o)}else n[s]=o}}return n}function Mp(e,t){return ks(Pp,e,t||{})}function Np(e,t){return ks(Dp,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:Tp.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,m=((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}:${m}`}else c.name=`${c.id}:${u}`}if(!c.displayName)c.displayName=c.name}switch(o.webauthn.type){case"create":{let c=Mp(o.webauthn.credential_options.publicKey,i===null||i===void 0?void 0:i.create),{data:u,error:d}=await Bp({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=Np(o.webauthn.credential_options.publicKey,i===null||i===void 0?void 0:i.request),{data:u,error:d}=await Op(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 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 Rr("rpId is required for WebAuthn authentication")};try{if(!sd())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(G(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 Rr("rpId is required for WebAuthn registration")};try{if(!sd())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(G(s))return{data:null,error:s};return{data:null,error:new St("Unexpected error in register",s)}}}}qu();var Lp={url:Ru,storageKey:Tu,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Bu,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5000,skipAutoInitialize:!1};async function dd(e,t,r){return await r()}var dn={};class ci{get jwks(){var e,t;return(t=(e=dn[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){dn[this.storageKey]=Object.assign(Object.assign({},dn[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=dn[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){dn[this.storageKey]=Object.assign(Object.assign({},dn[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({},Lp),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&&We()){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 cn({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Cs(i.fetch),this.lock=i.lock||dd,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&&We()&&((r=globalThis===null||globalThis===void 0?void 0:globalThis.navigator)===null||r===void 0?void 0:r.locks))this.lock=ia;else this.lock=dd;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(_s())this.storage=globalThis.localStorage;else this.memoryStorage={},this.storage=na(this.memoryStorage);if(i.userStorage)this.userStorage=i.userStorage}else this.memoryStorage={},this.storage=na(this.memoryStorage);if(We()&&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} (${gs}) ${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(We()){if(t=ju(window.location.href),this._isImplicitGrantCallback(t))r="implicit";else if(await this._isPKCECallback(t))r="pkce"}if(We()&&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),Mu(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 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 Y(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:wt}),{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,m=null;if(this.flowType==="pkce")[f,m]=await Or(this.storage,this.storageKey);i=await Y(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:m},xform:wt})}else if("phone"in e){let{phone:c,password:u,options:d}=e;i=await Y(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:wt})}else throw new on("You must provide either an email or phone number and a password");let{data:s,error:o}=i;if(o||!s)return await Ve(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 Ve(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 Y(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:ta})}else if("phone"in e){let{phone:i,password:s,options:o}=e;t=await Y(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:ta})}else throw new on("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 hr;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,m;if("message"in e)f=e.message,m=e.signature;else{let{chain:A,wallet:g,statement:b,options:w}=e,p;if(!We()){if(typeof g!=="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=g}else if(typeof g==="object")p=g;else{let O=window;if("ethereum"in O&&typeof O.ethereum==="object"&&"request"in O.ethereum&&typeof O.ethereum.request==="function")p=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 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((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 y=sa(_[0]),v=(r=w===null||w===void 0?void 0:w.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!v){let O=await p.request({method:"eth_chainId"});v=ed(O)}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=rd(x),m=await p.request({method:"personal_sign",params:[td(f),y]})}try{let{data:A,error:g}=await Y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:m},((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:wt});if(g)throw g;if(!A||!A.session||!A.user){let b=new hr;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:g})}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 m,A;if("message"in e)m=e.message,A=e.signature;else{let{chain:g,wallet:b,statement:w,options:p}=e,C;if(!We()){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)m=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");m=[`${_.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(m),"utf8");if(!y||!(y instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");A=y}}try{let{data:g,error:b}=await Y(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:m,signature:Xt(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:wt});if(b)throw b;if(!g||!g.session||!g.user){let w=new hr;return this._returnResult({data:{user:null,session:null},error:w})}if(g.session)await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session);return this._returnResult({data:Object.assign({},g),error:b})}catch(g){if(G(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async _exchangeCodeForSession(e){let t=await Ar(this.storage,`${this.storageKey}-code-verifier`),[r,n]=(t!==null&&t!==void 0?t:"").split("/");try{if(!r&&this.flowType==="pkce")throw new zo;let{data:i,error:s}=await Y(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:wt});if(await Ve(this.storage,`${this.storageKey}-code-verifier`),s)throw s;if(!i||!i.session||!i.user){let o=new hr;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 Ve(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 Y(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:wt}),{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 hr;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 Or(this.storage,this.storageKey);let{error:u}=await Y(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 Y(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 on("You must provide either an email or phone number.")}catch(o){if(await Ve(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 Y(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:wt});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 Or(this.storage,this.storageKey);let l=await Y(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:Xu});if(((i=l.data)===null||i===void 0?void 0:i.url)&&We()&&!((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 Ve(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 nt;let{error:n}=await Y(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 Y(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 Y(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 on("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 Ar(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()<ps:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){let s=await Ar(this.userStorage,this.storageKey+"-user");if(s===null||s===void 0?void 0:s.user)e.user=s.user;else e.user=xs()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let s={value:this.suppressGetSessionWarning};if(e.user=Zu(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 Y(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ft});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 Y(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:Ft})})}catch(t){if(G(t)){if(si(t))await this._removeSession(),await Ve(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 Or(this.storage,this.storageKey);let{data:l,error:c}=await Y(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:Ft});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 Ve(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 nt;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 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(G(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!We())throw new an("No browser detected.");if(e.error||e.error_description||e.error_code)throw new an(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 bs("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new an("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 bs("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 an("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 m=d-u;if(c-m>=120)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",m,d,c);else if(c-m<0)console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",m,d,c);let{data:A,error:g}=await this._getUser(i);if(g)throw g;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 Ar(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(!(Du(o)&&(o.status===404||o.status===401||o.status===403)||si(o)))return this._returnResult({error:o})}}if(e!=="others")await this._removeSession(),await Ve(this.storage,`${this.storageKey}-code-verifier`);return this._returnResult({error:null})})}onAuthStateChange(e){let t=Hu(),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 Or(this.storage,this.storageKey,!0);try{return await Y(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 Ve(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 Y(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(We()&&!((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 Y(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:wt}),{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 hr});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 Ve(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 Y(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 Yu(async(n)=>{if(n>0)await Wu(200*Math.pow(2,n-1));return this._debug(t,"refreshing attempt",n),await Y(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:wt})},(n,i)=>{let s=200*Math.pow(2,n);return i&&ys(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),We()&&!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 Ar(this.storage,this.storageKey);if(n&&this.userStorage){let s=await Ar(this.userStorage,this.storageKey+"-user");if(!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!s)s={user:n.user},await Br(this.userStorage,this.storageKey+"-user",s);n.user=(e=s===null||s===void 0?void 0:s.user)!==null&&e!==void 0?e:xs()}else if(n&&!n.user){if(!n.user){let s=await Ar(this.storage,this.storageKey+"-user");if(s&&(s===null||s===void 0?void 0:s.user))n.user=s.user,await Ve(this.storage,this.storageKey+"-user"),await Br(this.storage,this.storageKey,n);else n.user=xs()}}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()<ps;if(this._debug("#_recoverAndRefresh()",`session has${i?"":" not"} expired with margin of ${ps}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:s}=await this._callRefreshToken(n.refresh_token);if(s){if(console.error(s),!ys(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 ai;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),G(i)){let s={data:null,error:i};if(!ys(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 Ve(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 Br(this.userStorage,this.storageKey+"-user",{user:t.user});let n=Object.assign({},t);delete n.user;let i=ea(n);await Br(this.storage,this.storageKey,i)}else{let n=ea(t);await Br(this.storage,this.storageKey,n)}}async _removeSession(){if(this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Ve(this.storage,this.storageKey),await Ve(this.storage,this.storageKey+"-code-verifier"),await Ve(this.storage,this.storageKey+"-user"),this.userStorage)await Ve(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&&We()&&(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 ${ms} ticks`),n<=ms)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 Is)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!We()||!(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 Or(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 Y(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 Y(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"?cd(e.webauthn.credential_response):ud(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await Y(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 Y(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:ad(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:ld(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),m=null;if(f.aal)m=f.aal;let A=m,{data:{user:g},error:b}=await this.getUser(e);if(b)return this._returnResult({data:null,error:b});if(((r=(t=g===null||g===void 0?void 0:g.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:m,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 nt});return await Y(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 nt});let s=await Y(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(We()&&!(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 nt});let s=await Y(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(We()&&!(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 nt});return await Y(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 nt});return await Y(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+Pu>n)return r;let{data:i,error:s}=await Y(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:m}=await this.getSession();if(m||!f.session)return this._returnResult({data:null,error:m});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))Ju(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=Vu(n.alg),u=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!await crypto.subtle.verify(c,u,s,Gu(`${o}.${a}`)))throw new ln("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 la=ci;var Fp=la,ca=Fp;var Gp="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 Up={"X-Client-Info":`supabase-js-${ui}/${Gp}`},Hp={headers:Up},jp={schema:"public"},Kp={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Wp={};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 Yp(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 Qp(e){var t=Yp(e,"string");return di(t)=="symbol"?t:t+""}function Jp(e,t,r){return(t=Qp(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function hd(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 Pe(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?hd(Object(r),!0).forEach(function(n){Jp(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):hd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var Vp=(e)=>{if(e)return(...t)=>e(...t);return(...t)=>fetch(...t)},Zp=()=>Headers,$p=(e,t,r)=>{let n=Vp(r),i=Zp();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,Pe(Pe({},o),{},{headers:c}))}};function Xp(e){return e.endsWith("/")?e:e+"/"}function zp(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:Pe(Pe({},l),i),auth:Pe(Pe({},c),s),realtime:Pe(Pe({},u),o),storage:{},global:Pe(Pe(Pe({},d),a),{},{headers:Pe(Pe({},(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 qp(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(Xp(t))}catch(r){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var e0=class extends ca{constructor(e){super(e)}},t0=class{constructor(e,t,r){var n,i;this.supabaseUrl=e,this.supabaseKey=t;let s=qp(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:jp,realtime:Wp,auth:Pe(Pe({},Kp),{},{storageKey:o}),global:Hp},l=zp(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=$p(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Pe({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 lu(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 ku(this.storageUrl.href,this.headers,this.fetch,r===null||r===void 0?void 0:r.storage),!l.accessToken)this._listenForAuthEvents()}get functions(){return new es(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 e0({url:this.authUrl.href,headers:Pe(Pe({},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((m)=>m.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new zn(this.realtimeUrl.href,Pe(Pe({},e),{},{params:Pe(Pe({},{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}}},fd=(e,t,r)=>new t0(e,t,r);function r0(){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(r0())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 d0=300000,gd=16384,md=4096;function pd(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 bd(e=process.env){let t=pd(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=pd(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(c0(),".config");return{supabaseUrl:t,publishableKey:r,dashboardUrl:i,authFile:e.FLATBLOX_TUI_AUTH_FILE??Ad(s,"flatblox","tui-auth.json")}}function h0(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.accessToken==="string"&&t.accessToken.length>0&&t.accessToken.length<=gd&&typeof t.refreshToken==="string"&&t.refreshToken.length>0&&t.refreshToken.length<=gd}async function f0(e){try{let t=JSON.parse(await s0(e,"utf8"));if(!h0(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 Rs(e,t){await i0(u0(e),{recursive:!0,mode:448});let r=`${e}.${process.pid}.tmp`;await l0(r,`${JSON.stringify({accessToken:t.access_token,refreshToken:t.refresh_token})}
61
+ `,{mode:384}),await o0(r,e),await n0(e,384)}async function Mr(e){try{await a0(e)}catch(t){if(t.code!=="ENOENT")throw t}}function yd(e){return fd(e.supabaseUrl,e.publishableKey,{auth:{autoRefreshToken:!0,detectSessionInUrl:!1,persistSession:!1}})}async function wd(e,t){let r=await f0(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 Mr(t),null;return await Rs(t,n.session),n.session}function A0(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 g0(e){try{return Bun.spawn(A0(e),{stdout:"ignore",stderr:"ignore"}).unref(),!0}catch{return!1}}function m0(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 vd(e){let t=e.launch??g0,r=e.timeoutMs??d0,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 m0(o);if(w.method!=="POST"||p.pathname!=="/token")return new Response("Not found",{status:404});let C=await w.text();if(C.length>md+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>md)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`,m=new URL("tui-auth",i.endsWith("/")?i:`${i}/`);m.searchParams.set("callback",f),m.searchParams.set("state",o);let A=m.toString();n(A),t(A);let g=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(g),await d.stop(!1)}}async function _d(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 p0,resolve as Cd}from"path";var da=`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-${Be}> 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 ua(e,t,r){let n=e[t+1];if(!n||n.startsWith("-"))throw Error(`${r} needs a value`);return n}function xd(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(ua(e,u,d)),c=!0,u++;else if(d==="-o"||d==="--output")r=ua(e,u,d),c=!0,u++;else if(d==="-e"||d==="--export"){let f=ua(e,u,d),m=f==="all"?["svg","obj","png"]:f.split(",");n=n??[];for(let A of m){if(!rc(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>Be)throw Error(`Grid size must be between 1 and ${Be}`);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 b0(e){return p0(e).replace(/\.flatblox\.json$/i,"").replace(/\.json$/i,"")}async function Ed(e){let t=e.filePath?Cd(e.filePath):void 0,r=t?Bun.file(t):void 0,n=r&&await r.exists()?Dn(await r.text()):{...Fn(e.size),filename:t?b0(t):"untitled"},i=Cd(e.outputPath??t??`${n.filename}.flatblox.json`);return{session:new Qt(n),filePath:i}}var Ts="id, filename, num_cols, num_rows, grid, palette, palette_saturation, palette_lightness, artboards, created_at, updated_at",Id=16;function kd(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Sd(e,t){let r=Tn(e);return r.length===t&&r.every((n)=>n.length===t)?r:null}function Rd(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 y0(e){if(!Array.isArray(e))return[];return e.slice(0,Ao).flatMap((t,r)=>{if(!kd(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 w0(e){if(!Array.isArray(e))return[...ut[0].colors];let t=e.filter(yt).slice(0,Id);return t.length>0?t:[...ut[0].colors]}function Bs(e){if(!kd(e))return null;let t=Number(e.num_cols);if(!Number.isInteger(t)||t<1||t>Be||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=Sd(e.grid,t);if(!r)return null;let n=y0(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=Sd(o.grid,t);return a?Rd(a,r):!1});return{id:e.id,filename:e.filename||"Untitled",size:t,grid:r,palette:w0(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 Td(e){return Wt(e.grid,e.paletteSaturation,e.paletteLightness)}function Bd(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 v0(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=Yr(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 _0(e,t,r=new Date().toISOString()){let n=e.grid.length;if(n<1||n>Be||!e.grid.every((o)=>o.length===n))throw Error("Artwork grid is invalid");let i=e.palette.filter(yt).slice(0,Id);if(i.length===0)throw Error("Artwork palette is invalid");let s=Yr(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 ha{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(Ts).eq("user_id",this.userId).order("created_at",{ascending:!1});if(t)throw Error(t.message);return(e??[]).flatMap((r)=>{let n=Bs(r);return n?[n]:[]})}async createArtwork(e){let t=_0(e,this.userId),{data:r,error:n}=await this.client.from("pixel_art").insert(t).select(Ts).single();if(n)throw Error(n.message);let i=Bs(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||!Rd(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=v0(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(Ts).maybeSingle();if(i)throw Error(i.message);if(!n)return null;let s=Bs(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(Ts).eq("id",e).eq("user_id",this.userId).maybeSingle();if(r)throw Error(r.message);return t?Bs(t):null}async signOut(){let{error:e}=await this.client.auth.signOut();if(e)throw Error(e.message);await this.afterSignOut?.()}}import{NativeImage as C0,Renderable as x0,RGBA as E0}from"@opentui/core";var hi=E0.fromInts(14,16,24),Os=new Map,S0=256;function I0(e,t,r,n){let i=`${e}|${t}|${r}|${n}`,s=Os.get(i);if(s)return s;if(Os.size>=S0)Os.clear();let o=k0(e,t,r,n);return Os.set(i,o),o}function k0(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 m=1;m<=a;m++){let A=m*n/2,g=Math.min(f,A),b=Math.abs(Math.log(A/f));if(g>u||g===u&&b<d)l=f,c=m,u=g,d=b}return{sampleCount:s,columnScale:l,subrowScale:c,columns:s*l,subrows:s*c}}function R0(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 fa extends x0{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&&Di(this._ctx)){if(this.textFrame=null,e.clear(hi),t===0||this.width<=0||this.height<=0)return;this.drawArtworkImage(e,t,r.width,r.height);return}let n=Pi(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(hi),t===0||this.width<=0||this.height<=0)return;this.releaseArtworkImage();let s=this.height*2,o=I0(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:m,sampleCount:A}=o,g=(b)=>{let w=b-u;if(w<0||w>=l)return-1;let p=Math.floor(w/m);return Math.min(t-1,Math.floor(p*t/A))};for(let b=0;b<this.height;b++){let w=g(b*2),p=g(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?hi:Vt(d[w]?.[y],y,w),x=p<0?hi:Vt(d[p]?.[y],y,p);e.setCell(c+C,b,"\u2580",v,x)}}}drawArtworkImage(e,t,r,n){let i=R0(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 m=Math.min(t-1,Math.floor(f*t/i.sampleCount));for(let A=0;A<i.sampleCount;A++){let g=Math.min(t-1,Math.floor(A*t/i.sampleCount)),[b,w,p]=Vt(this.currentGrid[m]?.[g],g,m).toInts(),C=(f*i.sampleCount+A)*4;a[C]=b,a[C+1]=w,a[C+2]=p,a[C+3]=255}}let l=C0.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:hi.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()}}Kt({artwork_preview:fa});var Aa=[16,32,64],Pd=74,Od=2;function ga(e,t){let r=Fn(e),n=ut[t];return r.palette=[...n.colors],r.activeColor=r.palette[0],r}function ma(e,t){let r=e.name.toLowerCase(),n=Number(r)-1;if(r==="escape")return{kind:"cancel"};if(Number.isInteger(n)&&Aa[n])return{kind:"size",size:Aa[n]};let i=Cr(r);if(i)return{kind:"palette",delta:i.dx+i.dy*t};if(ur(e))return{kind:"create"}}function T0(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function Dd(e,t){if(e.length<=t)return e;return`${e.slice(0,Math.max(1,t-1))}\u2026`}function B0(e){return In(ao(e.palette,e.grid),e.paletteSaturation,e.paletteLightness)}function pa(e,t){return Math.max(0,Math.min(ut.length-1,e+t))}function Ps(e){return Math.max(1,Math.min(Pd,e-4))>=64?2:1}function ba(e){let t=K(()=>Math.max(1,Math.min(Pd,e.width-4))),r=K(()=>Math.max(1,Math.min(19,e.height-2))),n=K(()=>Ps(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 m=a();return ut.slice(m,m+o()).map((A,g)=>({palette:A,index:m+g}))}),c=K(()=>T0(l(),n())),u=K(()=>Math.max(1,Math.floor((t()-4-(n()-1))/n()))),d=K(()=>Math.max(3,Math.min(10,u()-8))),f=K(()=>Math.max(1,u()-d()-4));return(()=>{var m=S("box"),A=S("box"),g=S("box"),b=S("text"),w=S("box"),p=S("text"),C=ke("Choose a palette | "),_=S("box"),y=S("box"),v=S("text");return R(m,A),h(m,"id","new-artwork-modal"),h(m,"position","absolute"),h(m,"zIndex",30),h(m,"border",!0),h(m,"title"," New artwork "),h(m,"flexDirection","column"),R(A,g),R(A,w),R(A,p),R(A,_),R(A,y),R(A,v),h(A,"flexGrow",1),h(A,"width","100%"),h(A,"padding",1),h(A,"flexDirection","column"),R(g,b),h(g,"height",1),h(g,"flexDirection","row"),h(g,"gap",1),R(b,ke("Grid size")),L(g,J(bt,{each:Aa,children:(x,O)=>{let D=()=>x<=e.maxSize,P=()=>x===e.selectedSize;return(()=>{var T=S("box"),U=S("text"),V=ke(" "),Q=ke("\xD7");return R(T,U),h(T,"height",1),h(T,"paddingX",1),h(T,"onMouseDown",()=>e.onSelectSize(x)),R(U,V),R(U,Q),L(U,()=>O()+1,V),L(U,x,Q),L(U,x,null),fe((te)=>{var ae=P()?E.panelActive:E.panel,q=D()?P()?E.accentText:E.muted:E.border;return ae!==te.e&&(te.e=h(T,"backgroundColor",ae,te.e)),q!==te.t&&(te.t=h(U,"fg",q,te.t)),te},{e:void 0,t:void 0}),T})()}}),null),R(p,C),L(p,()=>ut[e.selectedPalette].name,null),L(A,J(bt,{get each(){return c()},children:(x)=>(()=>{var O=S("box");return h(O,"height",1),h(O,"flexDirection","row"),h(O,"gap",1),L(O,J(bt,{each:x,children:(D)=>{let P=()=>D.index===e.selectedPalette;return(()=>{var T=S("box"),U=S("text"),V=S("box");return R(T,U),R(T,V),h(T,"height",1),h(T,"paddingX",1),h(T,"flexDirection","row"),h(T,"justifyContent","space-between"),h(T,"onMouseDown",()=>e.onSelectPalette(D.index)),L(U,()=>Dd(D.palette.name,f())),h(V,"height",1),h(V,"flexDirection","row"),L(V,J(bt,{get each(){return D.palette.colors.slice(0,d())},children:(Q)=>(()=>{var te=S("text");return R(te,ke("\u25A0")),fe((ae)=>h(te,"fg",Ke(Q),ae)),te})()})),fe((Q)=>{var te=u(),ae=P()?E.panelActive:E.panel,q=P()?E.text:E.muted;return te!==Q.e&&(Q.e=h(T,"width",te,Q.e)),ae!==Q.t&&(Q.t=h(T,"backgroundColor",ae,Q.t)),q!==Q.a&&(Q.a=h(U,"fg",q,Q.a)),Q},{e:void 0,t:void 0,a:void 0}),T})()}})),O})()}),_),h(y,"flexGrow",1),L(v,()=>e.message||"1\u20133 size \xB7 arrows palette \xB7 Enter create \xB7 Esc cancel"),fe((x)=>{var O=Math.max(0,Math.floor((e.width-t())/2)),D=Math.max(0,Math.floor((e.height-r())/2)),P=t(),T=r(),U=E.border,V=E.accent,Q=E.panel,te=E.textPink,ae=i(),q=E.textPink,De=i(),Se=e.message?E.warning:E.textPink;return O!==x.e&&(x.e=h(m,"left",O,x.e)),D!==x.t&&(x.t=h(m,"top",D,x.t)),P!==x.a&&(x.a=h(m,"width",P,x.a)),T!==x.o&&(x.o=h(m,"height",T,x.o)),U!==x.i&&(x.i=h(m,"borderColor",U,x.i)),V!==x.n&&(x.n=h(m,"titleColor",V,x.n)),Q!==x.s&&(x.s=h(A,"backgroundColor",Q,x.s)),te!==x.h&&(x.h=h(b,"fg",te,x.h)),ae!==x.r&&(x.r=h(w,"height",ae,x.r)),q!==x.d&&(x.d=h(p,"fg",q,x.d)),De!==x.l&&(x.l=h(_,"height",De,x.l)),Se!==x.u&&(x.u=h(v,"fg",Se,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}),m})()}function O0(e){let t=K(()=>Td(e.artwork)),r=K(()=>B0(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"),f=S("text"),m=S("box"),A=S("box");return R(s,o),R(s,d),R(s,f),R(s,m),R(s,A),h(s,"flexDirection","column"),R(o,a),h(o,"width","100%"),h(o,"height","100%"),h(o,"border",!0),h(o,"borderColor","transparent"),h(o,"flexDirection","column"),R(a,l),R(a,c),R(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,J(bt,{get each(){return r()},children:(g)=>J(Un,{get color(){return Ke(g)},get background(){return E.panel},width:1,shape:"circle"})})),L(u,()=>Dd(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(m,"position","absolute"),h(m,"left",0),h(m,"top",0),h(m,"width",1),h(m,"height","100%"),h(m,"zIndex",2),h(A,"position","absolute"),h(A,"top",0),h(A,"width",1),h(A,"height","100%"),h(A,"zIndex",2),fe((g)=>{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}`,O=t(),D=E.textPink,P=`artwork-card-selection-top-${e.artwork.id}`,T=i(),U=n()?E.orangeActive:E.card,V=E.panel,Q=`artwork-card-selection-bottom-${e.artwork.id}`,te=e.cardHeight-1,ae=i(),q=n()?E.orangeActive:E.card,De=E.panel,Se=`artwork-card-selection-side-${e.artwork.id}`,z=n()?E.orangeActive:E.card,Z=e.cardWidth-1,le=n()?E.orangeActive:E.card;return b!==g.e&&(g.e=h(s,"id",b,g.e)),w!==g.t&&(g.t=h(s,"width",w,g.t)),p!==g.a&&(g.a=h(s,"height",p,g.a)),C!==g.o&&(g.o=h(s,"backgroundColor",C,g.o)),_!==g.i&&(g.i=h(s,"onMouseDown",_,g.i)),y!==g.n&&(g.n=h(o,"backgroundColor",y,g.n)),v!==g.s&&(g.s=h(a,"backgroundColor",v,g.s)),x!==g.h&&(g.h=h(l,"id",x,g.h)),O!==g.r&&(g.r=h(l,"grid",O,g.r)),D!==g.d&&(g.d=h(u,"fg",D,g.d)),P!==g.l&&(g.l=h(d,"id",P,g.l)),T!==g.u&&(g.u=h(d,"width",T,g.u)),U!==g.c&&(g.c=h(d,"fg",U,g.c)),V!==g.w&&(g.w=h(d,"bg",V,g.w)),Q!==g.m&&(g.m=h(f,"id",Q,g.m)),te!==g.f&&(g.f=h(f,"top",te,g.f)),ae!==g.y&&(g.y=h(f,"width",ae,g.y)),q!==g.g&&(g.g=h(f,"fg",q,g.g)),De!==g.p&&(g.p=h(f,"bg",De,g.p)),Se!==g.b&&(g.b=h(m,"id",Se,g.b)),z!==g.T&&(g.T=h(m,"backgroundColor",z,g.T)),Z!==g.A&&(g.A=h(A,"left",Z,g.A)),le!==g.O&&(g.O=h(A,"backgroundColor",le,g.O)),g},{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 ya(e){let t=ht(),r=Ur(),[n,i]=j([]),[s,o]=j(0),[a,l]=j(!0),[c,u]=j("Loading saved artworks\u2026"),[d,f]=j(null),[m,A]=j(!1),[g,b]=j(16),[w,p]=j(0),[C,_]=j(""),y=K(()=>{let N=Math.max(8,r().width-2);return Math.min(28,N,Math.max(12,Math.floor(N/3)))}),v=K(()=>{let N=r().height<18?7:r().height<25?9:12;return Math.max(4,Math.min(N,r().height-6))}),x=K(()=>Math.max(1,Math.floor((r().width-2)/(y()+Od)))),O=K(()=>x()*y()+Math.max(0,x()-1)*Od),D=K(()=>Math.max(1,Math.floor((r().height-5)/(v()+1)))),P=K(()=>x()*D()),T=K(()=>Math.floor(s()/P())),U=K(()=>T()*P()),V=K(()=>{let N=U();return n().slice(N,N+P())});_i(()=>{let N=Math.max(0,n().length-1);if(s()>N)o(N)});let Q=async()=>{l(!0),u("Loading saved artworks\u2026");try{let N=await e.repository.listArtworks();i(N),u(N.length===0?"No saved artworks yet":`${N.length} saved artwork${N.length===1?"":"s"}`)}catch(N){u(`Load failed: ${N instanceof Error?N.message:String(N)}`)}finally{l(!1)}};br(()=>void Q());let te=(N,ne)=>{let ie=n().length;if(ie===0)return;let ce=Math.max(0,Math.min(ie-1,s()+N+ne*x()));o(ce),u(n()[ce].filename)},ae=()=>{let N=n()[s()];if(!N)return;f({artwork:N,session:new Qt(Bd(N))})},q=()=>{b(16),p(0),_(""),A(!0),u("Choose a size and palette")},De=()=>{A(!1),_(""),u("New artwork cancelled")},Se=(N)=>{if(N>e.repository.maxCanvasSize){_(`${N}\xD7${N} is unavailable on this plan`);return}b(N),_("")},z=(N)=>{p((ne)=>pa(ne,N)),_("")},Z=()=>{A(!1),f({artwork:null,session:new Qt(ga(g(),w()))})},le=async(N)=>{let ne=d();if(!ne)throw Error("No artwork is open");let ie=ne.artwork?await e.repository.saveArtwork(ne.artwork,N):await e.repository.createArtwork(N);if(i((ce)=>ce.some((me)=>me.id===ie.id)?ce.map((me)=>me.id===ie.id?ie:me):[ie,...ce]),!ne.artwork)o(0);return f((ce)=>ce===ne?{...ce,artwork:ie}:ce),e.variant==="local"?"Saved locally":"Saved to Flatblox cloud"},ge=async()=>{u("Signing out\u2026");try{await e.repository.signOut(),t.destroy()}catch(N){u(`Sign out failed: ${N instanceof Error?N.message:String(N)}`)}};return Hr((N)=>{if(N.eventType==="release"||d())return;let ne=N.name.toLowerCase();if(m()){let ce=ma(N,Ps(r().width));if(ce?.kind==="cancel")De();else if(ce?.kind==="size")Se(ce.size);else if(ce?.kind==="palette")z(ce.delta);else if(ce?.kind==="create")Z();return}let ie=Cr(ne);if(N.ctrl&&ne==="c")t.destroy();else if(ne==="escape"&&e.onBack)e.onBack();else if(ne==="q"||ne==="escape")t.destroy();else if(ie)te(ie.dx,ie.dy);else if(ne==="n")q();else if(ur(N))ae();else if(ne==="r")Q();else if(ne==="o"&&e.variant!=="local")ge()}),J(Te,{get when(){return d()},get fallback(){return(()=>{var N=S("box"),ne=S("box"),ie=S("box"),ce=S("text"),Ze=S("b"),me=S("box"),Re=S("box"),At=S("text"),Xe=S("box"),ze=S("box"),re=S("text"),kt=S("text");return R(N,ne),R(N,Xe),R(N,ze),h(N,"width","100%"),h(N,"height","100%"),h(N,"flexDirection","column"),R(ne,ie),R(ne,me),R(ne,Re),h(ne,"height",3),h(ne,"paddingY",1),h(ne,"paddingX",1),h(ne,"flexDirection","row"),R(ie,ce),h(ie,"height",1),h(ie,"flexBasis",0),h(ie,"flexGrow",1),h(ie,"flexDirection","row"),R(ce,Ze),L(Ze,Vi),h(me,"height",1),h(me,"flexBasis",0),h(me,"flexGrow",1),h(me,"flexDirection","row"),h(me,"justifyContent","center"),L(me,J(Xr,{id:"dashboard-wordmark",width:14,height:1,get backgroundColor(){return E.panel},get foregroundColor(){return E.accent}})),R(Re,At),h(Re,"height",1),h(Re,"flexBasis",0),h(Re,"flexGrow",1),h(Re,"flexDirection","row"),h(Re,"justifyContent","flex-end"),L(At,()=>e.repository.username),h(Xe,"id","dashboard-content"),h(Xe,"flexGrow",1),h(Xe,"flexDirection","column"),h(Xe,"justifyContent","center"),h(Xe,"padding",1),L(Xe,J(Te,{get when(){return lt(()=>!a())()&&n().length>0},get fallback(){return(()=>{var B=S("box"),W=S("text");return R(B,W),h(B,"flexGrow",1),h(B,"alignItems","center"),h(B,"justifyContent","center"),L(W,c),fe((pe)=>h(W,"fg",E.muted,pe)),B})()},get children(){var B=S("box");return h(B,"id","artwork-grid"),h(B,"alignSelf","center"),h(B,"flexDirection","row"),h(B,"flexWrap","wrap"),h(B,"rowGap",1),h(B,"columnGap",2),L(B,J(bt,{get each(){return V()},children:(W,pe)=>J(O0,{artwork:W,get index(){return U()+pe()},selected:s,get cardWidth(){return y()},get cardHeight(){return v()},onSelect:()=>o(U()+pe())})})),fe((W)=>h(B,"width",O(),W)),B}})),R(ze,re),R(ze,kt),h(ze,"height",1),h(ze,"paddingX",1),h(ze,"flexDirection","row"),h(ze,"justifyContent","space-between"),L(re,c),L(kt,()=>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(N,J(Te,{get when(){return m()},get children(){return J(ba,{get width(){return r().width},get height(){return r().height},get selectedPalette(){return w()},get selectedSize(){return g()},get maxSize(){return e.repository.maxCanvasSize},get message(){return C()},onSelectPalette:(B)=>{p(B),_("")},onSelectSize:Se})}}),null),fe((B)=>{var W=E.background,pe=E.panel,at=E.accentText,vt=E.muted,Ne=E.panel,it=E.panelActive,Ye=c().startsWith("Load failed")?E.warning:E.textPink,gr=E.muted;return W!==B.e&&(B.e=h(N,"backgroundColor",W,B.e)),pe!==B.t&&(B.t=h(ne,"backgroundColor",pe,B.t)),at!==B.a&&(B.a=h(ce,"fg",at,B.a)),vt!==B.o&&(B.o=h(At,"fg",vt,B.o)),Ne!==B.i&&(B.i=h(Xe,"backgroundColor",Ne,B.i)),it!==B.n&&(B.n=h(ze,"backgroundColor",it,B.n)),Ye!==B.s&&(B.s=h(re,"fg",Ye,B.s)),gr!==B.h&&(B.h=h(kt,"fg",gr,B.h)),B},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),N})()},children:(N)=>J(zr,{get session(){return N().session},saveDocument:le,get promptForFilenameOnSave(){return!N().artwork},onBack:()=>{f(null),u("Returned from editor")}})})}import{readdir as P0,readFile as D0,stat as Md,writeFile as M0}from"fs/promises";import{basename as N0,join as Nd,resolve as L0}from"path";function Ld(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 F0(e){return e.replace(/[\\/]/g,"-").replace(/^\.+$/,"")||"untitled"}function G0(e){return typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string"&&e.code!=="ENOENT"}function U0(e=process.env,t=process.cwd()){return e.INIT_CWD||e.PWD||t}class wa{username;maxCanvasSize=64;directory;constructor(e=U0()){this.directory=L0(e),this.username=N0(this.directory)||"Local"}async listArtworks(){let e=await P0(this.directory,{withFileTypes:!0});return(await Promise.all(e.map(async(r)=>{if(!r.isFile()||!r.name.endsWith(".flatblox.json"))return null;let n=Nd(this.directory,r.name);try{let i=Dn(await D0(n,"utf8")),s=await Md(n),o=s.birthtimeMs>0?s.birthtime:s.mtime;return Ld(n,i,o,s.mtime)}catch(i){if(G0(i))throw i;return null}}))).filter((r)=>r!==null).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}async createArtwork(e){let t=Nd(this.directory,`${F0(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 M0(e,Mn(t));let r=await Md(e),n=r.birthtimeMs>0?r.birthtime:r.mtime;return Ld(e,t,n,r.mtime)}}function Fd(e){let t=ht(),r=Ur(),[n,i]=j(0),[s,o]=j(!1),[a,l]=j(16),[c,u]=j(0),[d,f]=j(null),[m,A]=j(null),[g,b]=j(!1),w=e.cloudRepository,[p,C]=j(w instanceof Promise?null:w??null);if(w instanceof Promise)w.then(C,(z)=>D(z instanceof Error?z.message:String(z)));let[_,y]=j(!1),[v,x]=j(!1),[O,D]=j(""),[P,T]=j(""),U=null,V=e.localRepository??new wa,Q=()=>{l(16),u(0),o(!0)},te=()=>{o(!1),A(null),f(new Qt(ga(a(),c())))},ae=(z)=>{u((Z)=>pa(Z,z))},q=async()=>{if(v())return;let z=new AbortController;U=z,x(!0),D(""),T("");try{let Z=await e.onSignIn(z.signal,T);if(!z.signal.aborted)C(Z),y(!0)}catch(Z){if(!z.signal.aborted)D(Z instanceof Error?Z.message:String(Z))}finally{if(U===z)U=null;x(!1)}},De=(z)=>{i((Z)=>Math.max(0,Math.min(2,Z+z)))},Se=()=>{if(p())y(!0);else q()};return Hr((z)=>{if(z.eventType==="release"||d()||g()||_())return;let Z=z.name.toLowerCase();if(v()){if(Z==="escape"||Z==="q"||z.ctrl&&Z==="c")U?.abort();return}if(s()){let ge=ma(z,Ps(r().width));if(ge?.kind==="cancel")o(!1);else if(ge?.kind==="size")l(ge.size);else if(ge?.kind==="palette")ae(ge.delta);else if(ge?.kind==="create")te();return}let le=Cr(Z);if(z.ctrl&&Z==="c")t.destroy();else if(Z==="q"||Z==="escape")t.destroy();else if(le?.dy)De(le.dy);else if(Z==="n")Q();else if(Z==="l")b(!0);else if(Z==="s"||Z==="d")Se();else if(ur(z))if(n()===0)Q();else if(n()===1)b(!0);else Se()}),J(Te,{get when(){return lt(()=>!!_())()?p():null},get fallback(){return J(Te,{get when(){return d()},get fallback(){return J(Te,{get when(){return g()},get fallback(){return(()=>{var z=S("box"),Z=S("box"),le=S("box"),ge=S("box"),N=S("box"),ne=S("text"),ie=S("box"),ce=S("box"),Ze=S("text"),me=S("box"),Re=S("box"),At=S("text"),Xe=S("box"),ze=S("text");return R(z,Z),h(z,"width","100%"),h(z,"height","100%"),h(z,"alignItems","center"),h(z,"justifyContent","center"),R(Z,le),R(Z,ge),R(Z,ie),R(Z,me),R(Z,Xe),R(Z,ze),h(Z,"flexDirection","column"),h(Z,"alignItems","center"),L(Z,J(Xr,{id:"welcome-wordmark",width:32,height:2,get backgroundColor(){return E.background},get foregroundColor(){return E.accent}}),le),h(le,"height",3),R(ge,N),h(ge,"id","welcome-new-artwork"),h(ge,"width",36),h(ge,"height",3),h(ge,"border",!0),h(ge,"onMouseDown",()=>{i(0),Q()}),R(N,ne),h(N,"width","100%"),h(N,"height","100%"),h(N,"alignItems","center"),h(N,"justifyContent","center"),R(ne,ke("New artwork")),h(ne,"id","welcome-new-artwork-label"),R(ie,ce),h(ie,"id","welcome-load-artwork"),h(ie,"width",36),h(ie,"height",3),h(ie,"border",!0),h(ie,"onMouseDown",()=>{i(1),b(!0)}),R(ce,Ze),h(ce,"width","100%"),h(ce,"height","100%"),h(ce,"alignItems","center"),h(ce,"justifyContent","center"),R(Ze,ke("Load artwork")),h(Ze,"id","welcome-load-artwork-label"),R(me,Re),h(me,"id","welcome-sign-in"),h(me,"width",36),h(me,"height",3),h(me,"border",!0),h(me,"onMouseDown",()=>{i(2),Se()}),R(Re,At),h(Re,"width","100%"),h(Re,"height","100%"),h(Re,"alignItems","center"),h(Re,"justifyContent","center"),h(At,"id","welcome-sign-in-label"),L(At,()=>p()?"Dashboard":"Sign in"),h(Xe,"height",2),L(ze,(()=>{var re=lt(()=>!!v());return()=>re()?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(z,J(Te,{get when(){return s()},get children(){return J(ba,{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),fe((re)=>{var kt=E.background,B=P()?Math.max(36,r().width-4):36,W=n()===0?E.accent:E.border,pe=n()===0?E.textPink:E.text,at=n()===1?E.accent:E.border,vt=n()===1?E.textPink:E.text,Ne=n()===2?E.accent:E.border,it=n()===2?E.textPink:E.text,Ye=O()?E.warning:E.muted;return kt!==re.e&&(re.e=h(z,"backgroundColor",kt,re.e)),B!==re.t&&(re.t=h(Z,"width",B,re.t)),W!==re.a&&(re.a=h(ge,"borderColor",W,re.a)),pe!==re.o&&(re.o=h(ne,"fg",pe,re.o)),at!==re.i&&(re.i=h(ie,"borderColor",at,re.i)),vt!==re.n&&(re.n=h(Ze,"fg",vt,re.n)),Ne!==re.s&&(re.s=h(me,"borderColor",Ne,re.s)),it!==re.h&&(re.h=h(At,"fg",it,re.h)),Ye!==re.r&&(re.r=h(ze,"fg",Ye,re.r)),re},{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}),z})()},get children(){return J(ya,{repository:V,variant:"local",onBack:()=>b(!1)})}})},children:(z)=>J(zr,{get session(){return z()},saveDocument:async(Z)=>{let le=m(),ge=le?await V.saveArtwork(le,Z):await V.createArtwork(Z);return A(ge),"Saved locally"},get promptForFilenameOnSave(){return!m()},onBack:()=>{A(null),f(null)}})})},children:(z)=>J(ya,{get repository(){return z()}})})}var Gd={backgroundColor:E.background,debounceDelay:1,exitOnCtrlC:!1,targetFps:60,useKittyKeyboard:{events:!0,allKeysAsEscapes:!0}};async function H0(e){let t=bd(),r=yd(t),n=await wd(r,t.authFile);if(e){if(n)await r.auth.signOut();await Mr(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((f,m)=>{if(m)Rs(t.authFile,m);else Mr(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 Mr(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 Mr(t.authFile),Error(u.message);return new ha(r,a.user.id,c?.username?.trim()||"Flatblox account",pl[c?.tier??"tier0"],()=>Mr(t.authFile))};try{let o=n?s(n.access_token):void 0;await io(()=>J(Fd,{cloudRepository:o,onSignIn:async(a,l)=>{let c=await vd({dashboardUrl:t.dashboardUrl,announce:l,signal:a}),u=await _d(r,c);return await Rs(t.authFile,u),s(u.access_token)}}),Gd)}finally{if(i)i(),await r.auth.stopAutoRefresh()}}async function j0(e){let t=await Ed(e);if(e.exportFormats){let r=await Li(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 io(()=>J(zr,{get session(){return t.session},get filePath(){return t.filePath}}),Gd)}async function K0(){try{let e=xd(Bun.argv.slice(2));if(e.help){process.stdout.write(`${da}
88
+ `);return}if(e.mode==="cloud")await H0(e.logout);else await j0(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
+ ${da}
91
+ `),process.exitCode=1}}await K0();