@synnaxlabs/pluto 0.44.2 → 0.44.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Animated-D5cL3URg.js → Animated-BHxq6Pmm.js} +2 -2
- package/dist/{Animated-DnsZ5vvU.cjs → Animated-DEXELMDa.cjs} +1 -1
- package/dist/LinePlot-BJ10hKs7.cjs +53 -0
- package/dist/{provider-Bp-CLkh2.js → LinePlot-VIcFjuPQ.js} +4543 -4448
- package/dist/{Toggle-Dol9oHzM.js → Toggle-C--I90ch.js} +1 -1
- package/dist/{Toggle-Ckdi4fKV.cjs → Toggle-CCsw0kkq.cjs} +1 -1
- package/dist/{Video-BidrtYj_.cjs → Video-BbRLzkdH.cjs} +1 -1
- package/dist/{Video-Cm8ZBqid.js → Video-DdsVXhnt.js} +1 -1
- package/dist/button.cjs +1 -1
- package/dist/button.js +1 -1
- package/dist/color.cjs +1 -1
- package/dist/color.js +1 -1
- package/dist/{css-Dl9aM7Jz.js → css-BKrX40Df.js} +713 -685
- package/dist/css-TyQvZIXQ.cjs +8 -0
- package/dist/css.cjs +1 -1
- package/dist/css.js +2 -2
- package/dist/dialog.cjs +1 -1
- package/dist/dialog.js +1 -1
- package/dist/eraser-Bxknv-HS.cjs +63 -0
- package/dist/{eraser-CZknVTjw.js → eraser-DtXU7kOS.js} +4811 -4746
- package/dist/ether.cjs +1 -1
- package/dist/ether.js +66 -63
- package/dist/{external-CU_XHLqP.js → external-BApQK7XP.js} +3 -3
- package/dist/{external-CkvXTCCL.cjs → external-BBXhtVjD.cjs} +1 -1
- package/dist/{external-xfHaehZH.js → external-BOmNpcyI.js} +20 -20
- package/dist/{external-ClD4VLgc.cjs → external-BPF50O_x.cjs} +1 -1
- package/dist/{external-DOd9BcLC.js → external-BT0nByPv.js} +2 -2
- package/dist/{external-BGCkpetp.cjs → external-BUAnicLg.cjs} +1 -1
- package/dist/{external-_eEnQPcq.cjs → external-BaRBYE0N.cjs} +1 -1
- package/dist/{external-B8qSW3N8.js → external-BmfZaFKB.js} +3 -3
- package/dist/external-BsyCwXWB.cjs +1 -0
- package/dist/{external-B5RyMtMy.js → external-Bt-WjDvD.js} +8 -8
- package/dist/{external-B_NFroo8.js → external-CEMgElRx.js} +10 -10
- package/dist/{external-DFsKdN71.cjs → external-COBt6FnN.cjs} +1 -1
- package/dist/{external-DXY1bIut.cjs → external-CZSk2V5E.cjs} +1 -1
- package/dist/{external-CY2bvy20.cjs → external-Cw5iYImi.cjs} +1 -1
- package/dist/{external-Ylv9Wts9.js → external-Dgui980d.js} +74 -75
- package/dist/external-Dwfn2jsF.js +42 -0
- package/dist/external-EMhi5ISu.cjs +1 -0
- package/dist/{external-DPqPAgoV.cjs → external-Jee63xkv.cjs} +1 -1
- package/dist/{external-CJZTgfAH.js → external-NUi5IwGn.js} +20 -20
- package/dist/{external-DnnHYQqD.js → external-ONwuyKzG.js} +27 -27
- package/dist/{external-DZqxSCvz.cjs → external-TAYJZFme.cjs} +1 -1
- package/dist/external-bvOijYCw.cjs +1 -0
- package/dist/{external-pm79tCDD.js → external-dkXc0y5z.js} +20 -20
- package/dist/{external-BYJw6DJV.js → external-n4gJTJfw.js} +23 -23
- package/dist/{external-b2X_jilF.js → external-tHxdTvxn.js} +2 -2
- package/dist/{external-BJ91nMtQ.cjs → external-yddEc8os.cjs} +1 -1
- package/dist/flex.cjs +1 -1
- package/dist/flex.js +1 -1
- package/dist/{fontString-BptzSQcY.cjs → fontString-BWGnZU-8.cjs} +1 -1
- package/dist/{fontString-Bm52S4Lo.js → fontString-D2-HUuI_.js} +2 -2
- package/dist/header.cjs +1 -1
- package/dist/header.js +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.js +10291 -10365
- package/dist/input.cjs +1 -1
- package/dist/input.js +1 -1
- package/dist/list.cjs +1 -1
- package/dist/list.js +1 -1
- package/dist/menu.cjs +1 -1
- package/dist/menu.js +1 -1
- package/dist/pluto.css +1 -1
- package/dist/src/channel/AliasInput.d.ts +3 -1
- package/dist/src/channel/AliasInput.d.ts.map +1 -1
- package/dist/src/channel/Select.d.ts.map +1 -1
- package/dist/src/channel/external.d.ts +0 -2
- package/dist/src/channel/external.d.ts.map +1 -1
- package/dist/src/channel/queries.d.ts +84 -6
- package/dist/src/channel/queries.d.ts.map +1 -1
- package/dist/src/dialog/Frame.d.ts.map +1 -1
- package/dist/src/flux/Provider.d.ts +9 -7
- package/dist/src/flux/Provider.d.ts.map +1 -1
- package/dist/src/flux/aether/external.d.ts +4 -3
- package/dist/src/flux/aether/external.d.ts.map +1 -1
- package/dist/src/flux/aether/provider.d.ts +31 -25
- package/dist/src/flux/aether/provider.d.ts.map +1 -1
- package/dist/src/flux/core/client.d.ts +21 -0
- package/dist/src/flux/core/client.d.ts.map +1 -0
- package/dist/src/flux/core/external.d.ts +4 -0
- package/dist/src/flux/core/external.d.ts.map +1 -0
- package/dist/src/flux/core/index.d.ts +2 -0
- package/dist/src/flux/core/index.d.ts.map +1 -0
- package/dist/src/flux/core/params.d.ts.map +1 -0
- package/dist/src/flux/core/store.d.ts +128 -0
- package/dist/src/flux/core/store.d.ts.map +1 -0
- package/dist/src/flux/core/store.spec.d.ts +2 -0
- package/dist/src/flux/core/store.spec.d.ts.map +1 -0
- package/dist/src/flux/core/streamer.d.ts +31 -0
- package/dist/src/flux/core/streamer.d.ts.map +1 -0
- package/dist/src/flux/core/streamer.spec.d.ts.map +1 -0
- package/dist/src/flux/external.d.ts +3 -5
- package/dist/src/flux/external.d.ts.map +1 -1
- package/dist/src/flux/form.d.ts +6 -3
- package/dist/src/flux/form.d.ts.map +1 -1
- package/dist/src/flux/list.d.ts +13 -13
- package/dist/src/flux/list.d.ts.map +1 -1
- package/dist/src/flux/result.d.ts +10 -9
- package/dist/src/flux/result.d.ts.map +1 -1
- package/dist/src/flux/retrieve.d.ts +18 -39
- package/dist/src/flux/retrieve.d.ts.map +1 -1
- package/dist/src/flux/update.d.ts +12 -7
- package/dist/src/flux/update.d.ts.map +1 -1
- package/dist/src/form/state.d.ts +3 -1
- package/dist/src/form/state.d.ts.map +1 -1
- package/dist/src/form/use.d.ts +1 -0
- package/dist/src/form/use.d.ts.map +1 -1
- package/dist/src/hardware/device/queries.d.ts +12 -4
- package/dist/src/hardware/device/queries.d.ts.map +1 -1
- package/dist/src/hardware/rack/external.d.ts +0 -3
- package/dist/src/hardware/rack/external.d.ts.map +1 -1
- package/dist/src/hardware/rack/queries.d.ts +13 -0
- package/dist/src/hardware/rack/queries.d.ts.map +1 -1
- package/dist/src/hardware/task/queries.d.ts +12 -5
- package/dist/src/hardware/task/queries.d.ts.map +1 -1
- package/dist/src/hooks/index.d.ts +1 -0
- package/dist/src/hooks/index.d.ts.map +1 -1
- package/dist/src/hooks/useDestructors.d.ts +7 -0
- package/dist/src/hooks/useDestructors.d.ts.map +1 -0
- package/dist/src/label/queries.d.ts +21 -19
- package/dist/src/label/queries.d.ts.map +1 -1
- package/dist/src/menu/ContextMenu.d.ts +1 -0
- package/dist/src/menu/ContextMenu.d.ts.map +1 -1
- package/dist/src/mosaic/tree.d.ts.map +1 -1
- package/dist/src/ontology/queries.d.ts +19 -4
- package/dist/src/ontology/queries.d.ts.map +1 -1
- package/dist/src/pluto/Pluto.d.ts +23 -2
- package/dist/src/pluto/Pluto.d.ts.map +1 -1
- package/dist/src/pluto/aether/pluto.d.ts.map +1 -1
- package/dist/src/ranger/aether/index.d.ts +2 -0
- package/dist/src/ranger/aether/index.d.ts.map +1 -0
- package/dist/src/ranger/aether/queries.d.ts +11 -0
- package/dist/src/ranger/aether/queries.d.ts.map +1 -0
- package/dist/src/ranger/queries.d.ts +28 -22
- package/dist/src/ranger/queries.d.ts.map +1 -1
- package/dist/src/state/state.d.ts +1 -1
- package/dist/src/state/state.d.ts.map +1 -1
- package/dist/src/status/Aggregator.d.ts +3 -0
- package/dist/src/status/Aggregator.d.ts.map +1 -1
- package/dist/src/status/Summary.d.ts.map +1 -1
- package/dist/src/status/aether/aggregator.d.ts +2 -12
- package/dist/src/status/aether/aggregator.d.ts.map +1 -1
- package/dist/src/status/aether/errorHandler.d.ts +15 -0
- package/dist/src/status/aether/errorHandler.d.ts.map +1 -0
- package/dist/src/status/aether/errorHandler.spec.d.ts +2 -0
- package/dist/src/status/aether/errorHandler.spec.d.ts.map +1 -0
- package/dist/src/status/aether/external.d.ts +3 -0
- package/dist/src/status/aether/external.d.ts.map +1 -0
- package/dist/src/status/aether/index.d.ts +1 -1
- package/dist/src/status/aether/index.d.ts.map +1 -1
- package/dist/src/testutil/Synnax.d.ts +6 -1
- package/dist/src/testutil/Synnax.d.ts.map +1 -1
- package/dist/src/text/Editable.d.ts.map +1 -1
- package/dist/src/vis/lineplot/range/aether/provider.d.ts +6 -18
- package/dist/src/vis/lineplot/range/aether/provider.d.ts.map +1 -1
- package/dist/src/vis/schematic/Forms.d.ts.map +1 -1
- package/dist/src/vis/value/TelemForm.d.ts.map +1 -1
- package/dist/src/workspace/queries.d.ts +8 -0
- package/dist/src/workspace/queries.d.ts.map +1 -1
- package/dist/{symbols-B15FeAg9.cjs → symbols-DWZqHjhU.cjs} +45 -45
- package/dist/{symbols-Lz5vQQDw.js → symbols-aLnytgtc.js} +6093 -6048
- package/dist/tabs.cjs +1 -1
- package/dist/tabs.js +1 -1
- package/dist/text.cjs +1 -1
- package/dist/text.js +2 -2
- package/dist/theming.cjs +1 -1
- package/dist/theming.js +2 -2
- package/dist/tree.cjs +1 -1
- package/dist/tree.js +1 -1
- package/dist/triggers.cjs +1 -1
- package/dist/triggers.js +1 -1
- package/dist/{units-BGkvnLO-.cjs → units-XE06scfL.cjs} +1 -1
- package/dist/{units-HcS_zslH.js → units-ny6lkoIv.js} +1 -1
- package/dist/video.cjs +1 -1
- package/dist/video.js +1 -1
- package/package.json +5 -5
- package/dist/Menu-C-MABQ1r.js +0 -61
- package/dist/Menu-vR5-lqo4.cjs +0 -1
- package/dist/css-9yccD6t_.cjs +0 -8
- package/dist/eraser-CLWNvWDn.cjs +0 -63
- package/dist/external-CS6l_QN4.cjs +0 -1
- package/dist/external-CVNscTLA.js +0 -42
- package/dist/external-CtooTI5M.cjs +0 -1
- package/dist/external-DNHOS3w0.cjs +0 -1
- package/dist/provider-DBSsDoFS.cjs +0 -53
- package/dist/src/channel/AliasContext.d.ts +0 -19
- package/dist/src/channel/AliasContext.d.ts.map +0 -1
- package/dist/src/channel/AliasProvider.d.ts +0 -6
- package/dist/src/channel/AliasProvider.d.ts.map +0 -1
- package/dist/src/flux/Context.d.ts +0 -4
- package/dist/src/flux/Context.d.ts.map +0 -1
- package/dist/src/flux/aether/listeners.d.ts +0 -16
- package/dist/src/flux/aether/listeners.d.ts.map +0 -1
- package/dist/src/flux/aether/params.d.ts.map +0 -1
- package/dist/src/flux/aether/streamer.d.ts +0 -22
- package/dist/src/flux/aether/streamer.d.ts.map +0 -1
- package/dist/src/flux/aether/streamer.spec.d.ts.map +0 -1
- package/dist/src/flux/aether/types.d.ts +0 -13
- package/dist/src/flux/aether/types.d.ts.map +0 -1
- package/dist/src/flux/listeners.d.ts +0 -4
- package/dist/src/flux/listeners.d.ts.map +0 -1
- package/dist/src/flux/listeners.spec.d.ts +0 -2
- package/dist/src/flux/listeners.spec.d.ts.map +0 -1
- package/dist/src/flux/useMountListeners.d.ts +0 -7
- package/dist/src/flux/useMountListeners.d.ts.map +0 -1
- package/dist/src/hardware/rack/synchronizers.d.ts +0 -3
- package/dist/src/hardware/rack/synchronizers.d.ts.map +0 -1
- package/dist/src/hardware/rack/use.d.ts +0 -3
- package/dist/src/hardware/rack/use.d.ts.map +0 -1
- package/dist/src/hardware/rack/useStatus.d.ts +0 -3
- package/dist/src/hardware/rack/useStatus.d.ts.map +0 -1
- /package/dist/src/flux/{aether → core}/params.d.ts +0 -0
- /package/dist/src/flux/{aether → core}/streamer.spec.d.ts +0 -0
package/dist/eraser-CLWNvWDn.cjs
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
"use strict";const s=require("zod"),f=require("./css-9yccD6t_.cjs"),Fn=require("react"),ml=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Sa=r=>{const e=(t,n=an)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Dr(t))return t;n=Tl(n);const a={},i=t;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),n):(Object.keys(i).forEach(o=>{let l=i[o];const c=r(o);n.recursive&&(Dr(l)?Ns(l)||(l=e(l,n)):n.recursiveInArray&&Es(l)&&(l=[...l].map(u=>{let d=u;return Dr(u)?Ns(d)||(d=e(u,n)):Es(u)&&(d=e({key:u},n).key),d}))),a[c]=l}),a)};return e},za=Sa(ml),wl=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),bl=Sa(wl),vl=[Number,String,Uint8Array],an={recursive:!0,recursiveInArray:!0},Tl=(r=an)=>(r.recursive==null?r=an:r.recursiveInArray??=!1,r),Es=r=>r!=null&&Array.isArray(r),Dr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Ns=r=>vl.some(e=>r instanceof e);let Ol=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r))}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),n=za(t);return e!=null?e.parse(n):n}encodeString(r){const e=bl(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):typeof n=="bigint"?n.toString():n)}};const on=new Ol;let ct=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const Sl=r=>r!=null&&typeof r=="object"&&"toString"in r,zl=(r,e=!1)=>{const t=Sl(r)?"stringer":typeof r;let n;switch(t){case"string":n=(a,i)=>a.localeCompare(i);break;case"stringer":n=(a,i)=>a.toString().localeCompare(i.toString());break;case"number":n=(a,i)=>Number(a)-Number(i);break;case"bigint":n=(a,i)=>BigInt(a)-BigInt(i)>0n?1:-1;break;case"boolean":n=(a,i)=>Number(a)-Number(i);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?El(n):n},El=r=>(e,t)=>r(t,e),Sr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Ea=s.z.object({width:s.z.number(),height:s.z.number()}),Nl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Al=["width","height"];s.z.enum(Al);const kl=["start","center","end"],xl=["signedWidth","signedHeight"];s.z.enum(xl);const pr=s.z.object({x:s.z.number(),y:s.z.number()}),Il=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Cl=["x","y"],Na=s.z.enum(Cl),Aa=["top","right","bottom","left"];s.z.enum(Aa);const jl=["left","right"],ka=s.z.enum(jl),Rl=["top","bottom"],xa=s.z.enum(Rl),Ia=["center"],As=s.z.enum(Ia),Ul=[...Aa,...Ia],Ca=s.z.enum(Ul);s.z.enum(kl);const Ll=["first","last"];s.z.enum(Ll);const Ml=s.z.object({lower:s.z.number(),upper:s.z.number()}),Pl=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Ml,Sr]);s.z.union([Pl,Sr]);s.z.enum([...Na.options,...Ca.options]);s.z.union([Na,Ca,s.z.instanceof(String)]);const qe=(r,e)=>typeof r=="bigint"?r*BigInt(e):r*Number(e),De=(r,e,t)=>{const n={};if(typeof e=="object"&&(t=e,e=void 0),t={makeValid:!0,...t},typeof r=="number"||typeof r=="bigint")e!=null?(n.lower=r,n.upper=e):(n.lower=typeof r=="bigint"?0n:0,n.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=r}else n.lower=r.lower,n.upper=r.upper;return t?.makeValid?Dl(n):n},Dl=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,ks=(r,e)=>{const t=De(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};s.z.object({x:ka.or(As),y:xa.or(As)});const Bl=s.z.object({x:ka,y:xa}),$l=Object.freeze({x:"left",y:"top"}),Fl=(r,e)=>r.x===e.x&&r.y===e.y,xs=s.z.union([s.z.number(),pr,Sr,Ea,Nl,Il]),Zl=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},Is=Object.freeze({x:0,y:0}),Qt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Qt,left:Qt,width:Qt,height:Qt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:pr,two:pr,root:Bl});const Zn=(r,e,t=0,n=0,a)=>{const i={one:{...Is},two:{...Is},root:a??$l};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:r,y:e},i.two={x:i.one.x+t,y:i.one.y+n},i}return"one"in r&&"two"in r&&"root"in r?{...r,root:a??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(i.one={x:r.left,y:r.top},i.two={x:r.right,y:r.bottom},i):(i.one=r,e==null?i.two={x:i.one.x+t,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+t}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},Br=r=>{const e=Zn(r);return{lower:e.one.x,upper:e.two.x}},$r=r=>{const e=Zn(r);return{lower:e.one.y,upper:e.two.y}},ql=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,Yl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Ea,Yl,pr,Sr]);const _l=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:xs,scale:xs});s.z.object({offset:s.z.number(),scale:s.z.number()});const Vl=r=>(e,t,n,a)=>t==="dimension"?[e,n]:[e,a?n-r:n+r],Hl=r=>(e,t,n,a)=>[e,a?n/r:n*r],Wl=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:a,upper:i}=e,{lower:o,upper:l}=r,c=i-a,u=l-o;if(t==="dimension")return[r,n*(u/c)];const d=(n-a)*(u/c)+o;return[r,d]},Gl=r=>(e,t,n)=>[r,n],Kl=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:a}=r;return[r,a-(t-n)]},Jl=r=>(e,t,n)=>{const{lower:a,upper:i}=r;return n=_l(n,a,i),[e,n]};let Cs=class _e{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new _e().translate(e)}static magnify(e){return new _e().magnify(e)}static scale(e,t){return new _e().scale(e,t)}translate(e){const t=this.new(),n=Vl(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Hl(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=De(e,t),a=this.new(),i=Wl(n);return i.type="scale",a.ops.push(i),a}clamp(e,t){const n=De(e,t),a=this.new(),i=Jl(n);return i.type="clamp",a.ops.push(i),a}reBound(e,t){const n=De(e,t),a=this.new(),i=Gl(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=Kl();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new _e;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||t.some(([o,l])=>a>=o&&a<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>a);i!==-1&&t.push([a,i])}),t.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new _e};(class se{x;y;currRoot;constructor(e=new Cs,t=new Cs,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new se().translate(e,t)}static translateX(e){return new se().translateX(e)}static translateY(e){return new se().translateY(e)}static clamp(e){return new se().clamp(e)}static magnify(e){return new se().magnify(e)}static scale(e){return new se().scale(e)}static reBound(e){return new se().reBound(e)}translate(e,t){const n=Zl(e,t),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(ql(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Fl(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Br(e)),t.y=t.y.scale($r(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(Br(e)),t.y=this.y.reBound($r(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Br(e)),t.y=this.y.clamp($r(e)),t}copy(){const e=new se;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Zn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new se});let Xl=(r,e=21)=>(t=e)=>{let n="",a=t|0;for(;a--;)n+=r[Math.random()*r.length|0];return n};const Ql="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ec=11,tc=Xl(Ql,ec),rc=()=>tc(),nc=(r,e)=>t=>t instanceof e||typeof t=="object"&&t!==null&&"discriminator"in t&&t.discriminator===r,sc=s.z.enum(["static","dynamic"]),ac=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),ja=(r,e)=>{const t=new I(e);if(![k.DAY,k.HOUR,k.MINUTE,k.SECOND,k.MILLISECOND,k.MICROSECOND,k.NANOSECOND].some(a=>a.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof I?new I(n):new k(n)};let I=class m extends ct{constructor(e,t="UTC"){if(e==null)super(m.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*m.MILLISECOND.valueOf());else if(typeof e=="string")super(m.parseDateTimeString(e,t).valueOf());else if(Array.isArray(e))super(m.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=m.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=m.MAX:e=m.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,t=1,n=1]){const a=new Date(e,t-1,n,0,0,0,0);return new m(BigInt(a.getTime())*m.MILLISECOND.valueOf()).truncate(m.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,a,i]=e.split(":");let o="00",l="00";i!=null&&([o,l]=i.split("."));let c=m.hours(parseInt(n??"00")).add(m.minutes(parseInt(a??"00"))).add(m.seconds(parseInt(o??"00"))).add(m.milliseconds(parseInt(l??"00")));return t==="local"&&(c=c.add(m.utcOffset)),c.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return m.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new m(BigInt(n.getTime())*m.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(m.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new k(BigInt(new Date().getTimezoneOffset())*m.MINUTE.valueOf())}static since(e){return new m().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new m(e).valueOf()}span(e){return this.range(e).span}range(e){return new St(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new m(e).valueOf()}afterEq(e){return this.valueOf()>=new m(e).valueOf()}before(e){return this.valueOf()<new m(e).valueOf()}beforeEq(e){return this.valueOf()<=new m(e).valueOf()}add(e){return new m(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new m(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(k.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(k.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(k.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(k.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(m.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(m.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const t=this.date();return t.setUTCFullYear(e),new m(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new m(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new m(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new m(t,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new m(t)}get second(){return this.date().getUTCSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new m(t)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const t=this.date();return t.setUTCMilliseconds(e),new m(t)}toString(){return this.date().toISOString()}remainder(e){return ja(this,e)}get isToday(){return this.truncate(k.DAY).equals(m.now().truncate(k.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new m(new Date)}static max(...e){let t=m.MIN;for(const n of e){const a=new m(n);a.after(t)&&(t=a)}return t}static min(...e){let t=m.MAX;for(const n of e){const a=new m(n);a.before(t)&&(t=a)}return t}static nanoseconds(e,t="UTC"){return new m(e,t)}static NANOSECOND=m.nanoseconds(1);static microseconds(e,t="UTC"){return m.nanoseconds(e*1e3,t)}static MICROSECOND=m.microseconds(1);static milliseconds(e,t="UTC"){return m.microseconds(e*1e3,t)}static MILLISECOND=m.milliseconds(1);static seconds(e,t="UTC"){return m.milliseconds(e*1e3,t)}static SECOND=m.seconds(1);static minutes(e,t="UTC"){return m.seconds(e*60,t)}static MINUTE=m.minutes(1);static hours(e,t="UTC"){return m.minutes(e*60,t)}static HOUR=m.hours(1);static days(e,t="UTC"){return m.hours(e*24,t)}static DAY=m.days(1);static MAX=new m((1n<<63n)-1n);static MIN=new m(0);static ZERO=new m(0);static z=s.z.union([s.z.instanceof(m),s.z.object({value:s.z.bigint()}).transform(e=>new m(e.value)),s.z.string().transform(e=>new m(BigInt(e))),s.z.number().transform(e=>new m(e)),s.z.bigint().transform(e=>new m(e)),s.z.date().transform(e=>new m(e)),s.z.custom(e=>e instanceof k).transform(e=>new m(e)),ac.transform(e=>new m(e))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},k=class v extends ct{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof v?e:e instanceof js?e.period:e instanceof I?new v(e):["number","bigint"].includes(typeof e)?v.seconds(e):new v(e)}static fromMilliseconds(e){return e instanceof v?e:e instanceof js?e.period:e instanceof I?new v(e):["number","bigint"].includes(typeof e)?v.milliseconds(e):new v(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new v(e).valueOf()}greaterThan(e){return this.valueOf()>new v(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new v(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new v(e).valueOf()}remainder(e){return ja(this,e)}truncate(e){return new v(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(v.DAY),t=this.truncate(v.HOUR),n=this.truncate(v.MINUTE),a=this.truncate(v.SECOND),i=this.truncate(v.MILLISECOND),o=this.truncate(v.MICROSECOND),l=this.truncate(v.NANOSECOND),c=e,u=t.sub(e),d=n.sub(t),h=a.sub(n),b=i.sub(a),S=o.sub(i),R=l.sub(o);let A="";return c.isZero||(A+=`${c.days}d `),u.isZero||(A+=`${u.hours}h `),d.isZero||(A+=`${d.minutes}m `),h.isZero||(A+=`${h.seconds}s `),b.isZero||(A+=`${b.milliseconds}ms `),S.isZero||(A+=`${S.microseconds}µs `),R.isZero||(A+=`${R.nanoseconds}ns`),A.trim()}mult(e){return new v(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(v.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(v.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(v.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(v.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(v.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new v(e).valueOf()}add(e){return new v(this.valueOf()+new v(e).valueOf())}sub(e){return new v(this.valueOf()-new v(e).valueOf())}static nanoseconds(e=1){return new v(e)}static NANOSECOND=v.nanoseconds(1);static microseconds(e=1){return v.nanoseconds(qe(e,1e3))}static MICROSECOND=v.microseconds(1);static milliseconds(e=1){return v.microseconds(qe(e,1e3))}static MILLISECOND=v.milliseconds(1);static seconds(e=1){return v.milliseconds(qe(e,1e3))}static SECOND=v.seconds(1);static minutes(e=1){return v.seconds(qe(e,60))}static MINUTE=v.minutes(1);static hours(e){return v.minutes(qe(e,60))}static HOUR=v.hours(1);static days(e){return v.hours(qe(e,24))}static DAY=v.days(1);static MAX=new v((1n<<63n)-1n);static MIN=new v(0);static ZERO=new v(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new v(e.value)),s.z.string().transform(e=>new v(BigInt(e))),s.z.number().transform(e=>new v(e)),s.z.instanceof(v)])},js=class Ve extends ct{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Ve(e).valueOf()}get period(){return k.seconds(1/this.valueOf())}sampleCount(e){return new k(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new V(t).valueOf()}span(e){return k.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Ve(e)}static khz(e){return Ve.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new Ve(e)),s.z.instanceof(Ve)])},V=class de extends ct{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new ln(e*this.valueOf())}static UNKNOWN=new de(0);static BIT128=new de(16);static BIT64=new de(8);static BIT32=new de(4);static BIT16=new de(2);static BIT8=new de(1);static z=s.z.union([s.z.number().transform(e=>new de(e)),s.z.instanceof(de)])},St=class ae{start;end;constructor(e,t){typeof e=="object"&&"start"in e?(this.start=new I(e.start),this.end=new I(e.end)):(this.start=new I(e),this.end=new I(t))}get span(){return new k(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new ae(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=k.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),a=this.end.sub(e.end).valueOf();return n<0&&(n=-n),a<0&&(a=-a),n<=t.valueOf()&&a<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=k.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const a=I.max(n.start,e.start),i=I.min(n.end,e.end);return i.before(a)?!1:new k(i.sub(a)).greaterThanOrEqual(t)}contains(e){return e instanceof ae?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new ae(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}static max(...e){return new ae(I.min(...e.map(t=>t.start)),I.max(...e.map(t=>t.end)))}static MAX=new ae(I.MIN,I.MAX);static MIN=new ae(I.MAX,I.MIN);static ZERO=new ae(I.ZERO,I.ZERO);static z=s.z.union([s.z.object({start:I.z,end:I.z}).transform(e=>new ae(e.start,e.end)),s.z.instanceof(ae)]);static sort(e,t){return I.sort(e.start,t.start)||I.sort(e.end,t.end)}},P=class p extends ct{constructor(e){if(e instanceof p||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const t=p.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t==null)throw new Error(`unable to find data type for ${e.toString()}`);super(t.valueOf())}}get Array(){const e=p.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(p.JSON)||this.equals(p.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(p.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=p.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(p.UINT8)||this.equals(p.UINT16)||this.equals(p.UINT32)||this.equals(p.UINT64)}get isSignedInteger(){return this.equals(p.INT8)||this.equals(p.INT16)||this.equals(p.INT32)||this.equals(p.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(p.INT32)&&e.equals(p.FLOAT64)||this.equals(p.INT8)&&e.equals(p.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return p.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new p("unknown");static FLOAT64=new p("float64");static FLOAT32=new p("float32");static INT64=new p("int64");static INT32=new p("int32");static INT16=new p("int16");static INT8=new p("int8");static UINT64=new p("uint64");static UINT32=new p("uint32");static UINT16=new p("uint16");static UINT8=new p("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new p("timestamp");static UUID=new p("uuid");static STRING=new p("string");static JSON=new p("json");static ARRAY_CONSTRUCTORS=new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]]);static DENSITIES=new Map([[p.UINT8.toString(),V.BIT8],[p.UINT16.toString(),V.BIT16],[p.UINT32.toString(),V.BIT32],[p.UINT64.toString(),V.BIT64],[p.FLOAT32.toString(),V.BIT32],[p.FLOAT64.toString(),V.BIT64],[p.INT8.toString(),V.BIT8],[p.INT16.toString(),V.BIT16],[p.INT32.toString(),V.BIT32],[p.INT64.toString(),V.BIT64],[p.TIMESTAMP.toString(),V.BIT64],[p.STRING.toString(),V.UNKNOWN],[p.JSON.toString(),V.UNKNOWN],[p.UUID.toString(),V.BIT128]]);static ALL=[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON];static BIG_INT_TYPES=[p.INT64,p.UINT64,p.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new p(e)),s.z.instanceof(p)])},ln=class C extends ct{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return C.bytes(this.valueOf()+e.valueOf())}sub(e){return C.bytes(this.valueOf()-e.valueOf())}truncate(e){return new C(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return C.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/C.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/C.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/C.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/C.TERABYTE.valueOf()}toString(){const e=this.truncate(C.TERABYTE),t=this.truncate(C.GIGABYTE),n=this.truncate(C.MEGABYTE),a=this.truncate(C.KILOBYTE),i=this.truncate(C.BYTE),o=e,l=t.sub(e),c=n.sub(t),u=a.sub(n),d=i.sub(a);let h="";return o.isZero||(h+=`${o.terabytes}TB `),l.isZero||(h+=`${l.gigabytes}GB `),c.isZero||(h+=`${c.megabytes}MB `),u.isZero||(h+=`${u.kilobytes}KB `),(!d.isZero||h==="")&&(h+=`${d.valueOf()}B`),h.trim()}static bytes(e=1){return new C(e)}static BYTE=new C(1);static kilobytes(e=1){return C.bytes(e.valueOf()*1e3)}static KILOBYTE=C.kilobytes(1);static megabytes(e=1){return C.kilobytes(e.valueOf()*1e3)}static MEGABYTE=C.megabytes(1);static gigabytes(e=1){return C.megabytes(e.valueOf()*1e3)}static GIGABYTE=C.gigabytes(1);static terabytes(e){return C.gigabytes(e.valueOf()*1e3)}static TERABYTE=C.terabytes(1);static ZERO=new C(0);static z=s.z.union([s.z.number().transform(e=>new C(e)),s.z.instanceof(C)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const Ra=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof I||r instanceof k||r instanceof Date},ic=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):or(t,-n),or=(r,e)=>e==0?r:r==0?e:typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:Number(r)+Number(e),oc=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function lc(r){return typeof r=="string"&&oc.test(r)}const Z=[];for(let r=0;r<256;++r)Z.push((r+256).toString(16).slice(1));function cc(r,e=0){return(Z[r[e+0]]+Z[r[e+1]]+Z[r[e+2]]+Z[r[e+3]]+"-"+Z[r[e+4]]+Z[r[e+5]]+"-"+Z[r[e+6]]+Z[r[e+7]]+"-"+Z[r[e+8]]+Z[r[e+9]]+"-"+Z[r[e+10]]+Z[r[e+11]]+Z[r[e+12]]+Z[r[e+13]]+Z[r[e+14]]+Z[r[e+15]]).toLowerCase()}function uc(r,e=0){const t=cc(r,e);if(!lc(t))throw TypeError("Stringified UUID is invalid");return t}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ua=(r,e)=>uc(r,e),be=-1,hc=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),dc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),cn=10,fc=(r,e)=>{if(r==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(r==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},La="sy_x_telem_series";let Ma=class Se{key;discriminator=La;dataType;sampleOffset;gl;_data;timeRange=St.ZERO;alignment=0n;cachedMin;cachedMax;writePos=be;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:St.z.optional(),dataType:P.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([hc,dc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:sc.optional().default("static").optional()});static z=Se.crudeZ.transform(e=>new Se(e));constructor(e){pc(e)&&(e={data:e}),e.data??=[];const{dataType:t,timeRange:n,sampleOffset:a=0,glBufferUsage:i="static",alignment:o=0n,key:l=rc(),data:c}=e;if(yc(c)){const h=c;this.key=h.key,this.dataType=h.dataType,this.sampleOffset=h.sampleOffset,this.gl=h.gl,this._data=h._data,this.timeRange=h.timeRange,this.alignment=h.alignment,this.cachedMin=h.cachedMin,this.cachedMax=h.cachedMax,this.writePos=h.writePos,this._refCount=h._refCount,this.cachedLength=h.cachedLength;return}const u=Ra(c),d=Array.isArray(c);if(t!=null)this.dataType=new P(t);else{if(c instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||u){let h=c;if(!u){if(c.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");h=c[0]}if(typeof h=="string")this.dataType=P.STRING;else if(typeof h=="number")this.dataType=P.FLOAT64;else if(typeof h=="bigint")this.dataType=P.INT64;else if(typeof h=="boolean")this.dataType=P.BOOLEAN;else if(h instanceof I||h instanceof Date||h instanceof I)this.dataType=P.TIMESTAMP;else if(typeof h=="object")this.dataType=P.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new P(c)}if(!d&&!u)this._data=c;else if(d&&c.length===0)this._data=new this.dataType.Array([]).buffer;else{let h=u?[c]:c;const b=h[0];(b instanceof I||b instanceof Date||b instanceof k)&&(h=h.map(S=>new I(S).valueOf())),this.dataType.equals(P.STRING)?(this.cachedLength=h.length,this._data=new TextEncoder().encode(`${h.join(`
|
|
2
|
-
`)}
|
|
3
|
-
`).buffer):this.dataType.equals(P.JSON)?(this.cachedLength=h.length,this._data=new TextEncoder().encode(`${h.map(S=>on.encodeString(S)).join(`
|
|
4
|
-
`)}
|
|
5
|
-
`).buffer):this.dataType.usesBigInt&&typeof b=="number"?this._data=new this.dataType.Array(h.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof b=="bigint"?this._data=new this.dataType.Array(h.map(Number)).buffer:this._data=new this.dataType.Array(h).buffer}this.key=l,this.alignment=o,this.sampleOffset=a??0,this.timeRange=n??St.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const a=new new P(t).Array(e),i=new Se({data:a.buffer,dataType:t,...n});return i.writePos=0,i}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===be)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===be)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===be?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
|
|
6
|
-
`).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(P.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(t=>e.parse(on.decodeString(t)))}get byteCapacity(){return new ln(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===be?this.byteCapacity:this.dataType.isVariable?new ln(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===be?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,a)=>{n===cn&&(e++,t.push(a+1))}),this._cachedIndexes=t,this.cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let a=0;a<this.length;a++)n[a]=ic(this.dataType,e,this.data[a],t);return new Se({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(P.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this.cachedMax=e.reduce((t,n)=>t>n?t:n)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),or(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(P.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this.cachedMin=e.reduce((t,n)=>t<n?t:n)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),or(this.cachedMin,this.sampleOffset))}get bounds(){return De(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const t=e.cachedMin??e.calcRawMin();t<this.cachedMin&&(this.cachedMin=t)}if(this.cachedMax!=null){const t=e.cachedMax??e.calcRawMax();t>this.cachedMax&&(this.cachedMax=t)}}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(P.UUID))return this.atUUID(e,t);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return or(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);const n=Ua(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,a=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],a=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===cn){if(e===0){a=o;break}n=o+1,e--}if(a===0&&(a=this.data.length),n>=a||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(n,a);return this.dataType.equals(P.STRING)?new TextDecoder().decode(i):za(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let t=0,n=this.length-1;const a=zl(e);for(;t<=n;){const i=Math.floor((t+n)/2),o=a(this.at(i,!0),e);if(o===0)return i;o<0?t=i+1:n=i-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(P.FLOAT32)&&!this.dataType.equals(P.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:a}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==a)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==be){a===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const i=this.dataType.density.size(a).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,i,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=be}as(e){return fc(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Us(this.alignmentBounds.lower),upper:Us(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return De(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new gc(this);return this.dataType.equals(P.JSON)?new mc(e):e}return this.dataType.equals(P.UUID)?new wc(this):new bc(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Rs(this,e,t??this.length)}subAlignmentIterator(e,t){return new Rs(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new Se({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let a;return e?a=this.data.subarray(t,n):a=this.data.slice(t,n),new Se({data:a,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new Se({data:this.buffer,dataType:this.dataType,timeRange:St.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(t=>t.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=",";e+="...,";for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=",")}return e+="])",e}};const pc=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Ma?!0:Ra(r),yc=nc(La,Ma);let Rs=class{series;end;index;constructor(r,e,t){this.series=r;const n=De(0,r.length);this.end=ks(n,t),this.index=ks(n,e)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},gc=class{series;index;decoder;constructor(r){if(!r.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=r,this.index=0,this.decoder=new TextDecoder}next(){const r=this.index,e=this.series.data;for(;this.index<e.length&&e[this.index]!==cn;)this.index++;const t=this.index;return r===t?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(r,t))})}},mc=class Pa{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:on.decodeString(e.value,Pa.schema)}}};class wc{series;index;data;density;constructor(e){if(!e.dataType.equals(P.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=P.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Ua(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let bc=class{series;index;constructor(r){this.series=r,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}};const Us=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const vc=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";vc();const Tc=["macOS","Windows","Linux"],Oc=["macos","windows","linux"],Sc={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(Tc).or(s.z.enum(Oc).transform(r=>Sc[r]));const zc=(...r)=>r.map(Da).join(""),Da=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Ec=r=>r.endsWith("/")?r.slice(0,-1):r,Nc=(r,e="")=>r===null?"":`?${Object.entries(r).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,n])=>`${e}${t}=${n}`).join("&")}`;let Ac=class lr{protocol;host;port;path;constructor({host:e,port:t,protocol:n="",pathPrefix:a=""}){this.protocol=n,this.host=e,this.port=t,this.path=Da(a)}replace(e){return new lr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new lr({...this,pathPrefix:zc(this.path,e)})}toString(){return Ec(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new lr({host:"unknown",port:0})};const kc=async r=>await new Promise(e=>setTimeout(e,k.fromMilliseconds(r).milliseconds));class xc{config;retries;interval;constructor(e){this.config={baseInterval:new k(e?.baseInterval??k.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??kc},this.retries=0,this.interval=new k(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),this.retries++,!0)}reset(){this.retries=0,this.interval=this.config.baseInterval}}const Ic=s.z.object({baseInterval:k.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Cc=Object.freeze(Object.defineProperty({__proto__:null,Breaker:xc,breakerConfigZ:Ic},Symbol.toStringTag,{value:"Module"})),jc=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Ba=s.z.string().regex(jc),et=s.z.number().min(0).max(255),$a=s.z.number().min(0).max(1),Fa=s.z.tuple([et,et,et,$a]),Rc=s.z.tuple([et,et,et]),Uc=s.z.object({rgba255:Fa}),Lc=s.z.number().min(0).max(360),Mc=s.z.number().min(0).max(100),Pc=s.z.number().min(0).max(100),Dc=s.z.tuple([Lc,Mc,Pc,$a]),qn=s.z.union([Ba,Rc,Fa,Dc,Uc]),Bc=qn.transform(r=>Yn(r)),Yn=(r,e=1)=>{if(r=qn.parse(r),typeof r=="string")return $c(r,e);if(Array.isArray(r)){if(r.length<3||r.length>4)throw new Error(`Invalid color: [${r.join(", ")}]`);return r.length===3?[...r,e]:r}return r.rgba255},$c=(r,e=1)=>(r=Ba.parse(r),r=Fc(r),[er(r,0),er(r,2),er(r,4),r.length===8?er(r,6)/255:e]),er=(r,e)=>parseInt(r.slice(e,e+2),16),Fc=r=>r.startsWith("#")?r.slice(1):r;Yn("#000000");Yn("#ffffff");const Zc=s.z.object({key:s.z.string(),color:qn,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(Zc);const qc=s.z.object({key:s.z.string(),name:s.z.string(),color:Bc});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(qc)});s.z.int().min(0).max(255);s.z.object({name:s.z.string(),key:s.z.string()});const Yc=r=>Object.getOwnPropertySymbols(globalThis).includes(r),_c=(r,e)=>{const t=Symbol.for(r);if(!Yc(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},Za="sy_x_error",Vc=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(r):e instanceof Error?e.message.startsWith(r):typeof e!="string"?!1:e.startsWith(r),Bt=r=>class zt extends Error{static discriminator=Za;discriminator=zt.discriminator;static TYPE=r;type=zt.TYPE;static matches=Vc(r);matches=zt.matches;constructor(t,n){super(t,n),this.name=zt.TYPE}static sub(t){return Bt(`${r}.${t}`)}},qa=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!==Za)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},He="unknown",un="nil";class Hc{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:un,data:""};if(qa(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:He,data:e.message};if(typeof e=="string")return{type:He,data:e};try{return{type:He,data:JSON.stringify(e)}}catch{return{type:He,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===un)return null;if(e.type===He)return new hn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new hn(e.data)}}const _n=_c("synnax-error-registry",()=>new Hc),Wc=({encode:r,decode:e})=>_n().register({encode:r,decode:e}),Gc=r=>_n().encode(r),Kc=r=>r==null?null:_n().decode(r);let hn=class extends Bt("unknown"){};const Jc=s.z.object({type:s.z.string(),data:s.z.string()});class Xc extends Bt("canceled"){}class Qc extends Bt("not_implemented"){}const Ie=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Xc,NONE:un,NotImplemented:Qc,UNKNOWN:He,Unknown:hn,createTyped:Bt,decode:Kc,encode:Gc,isTyped:qa,payloadZ:Jc,register:Wc},Symbol.toStringTag,{value:"Module"})),eu=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),Ya=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),tu=Ya.extend({result:s.json()}),ru=Ya.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),nu=s.union([tu,ru]);s.union([eu,nu]);s.z.string().regex(/^\d+\.\d+\.\d+$/);const su=["standard","scientific","engineering"];s.z.enum(su);s.z.enum(["success","info","warning","error","loading","disabled"]);let $t=class extends Ie.createTyped("freighter"){},te=class extends $t.sub("eof"){constructor(){super("EOF")}},rt=class extends $t.sub("stream_closed"){constructor(){super("StreamClosed")}},Ce=class extends $t.sub("unreachable"){url;constructor(e={}){const{message:t="Unreachable",url:n=Ac.UNKNOWN}=e;super(t),this.url=n}};const au=r=>{if(!r.type.startsWith($t.TYPE))return null;if(te.matches(r))return{type:te.TYPE,data:"EOF"};if(rt.matches(r))return{type:rt.TYPE,data:"StreamClosed"};if(Ce.matches(r))return{type:Ce.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},iu=r=>{if(!r.type.startsWith($t.TYPE))return null;switch(r.type){case te.TYPE:return new te;case rt.TYPE:return new rt;case Ce.TYPE:return new Ce;default:throw new Ie.Unknown(`Unknown error type: ${r.data}`)}};Ie.register({encode:au,decode:iu});class _a{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const a=async i=>{if(n===this.middleware.length)return await t(i);const o=this.middleware[n];return n++,await o(i,a)};return await a(e)}}const Va="Content-Type",ou=r=>typeof r.cause=="object"&&r.cause!==null&&"code"in r.cause&&r.cause.code==="ECONNREFUSED",lu=400;class cu extends _a{endpoint;encoder;constructor(e,t,n=!1){return super(),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,new Proxy(this,{get:(a,i,o)=>i==="endpoint"?this.endpoint:Reflect.get(a,i,o)})}get headers(){return{[Va]:this.encoder.contentType}}async send(e,t,n,a){t=n?.parse(t);let i=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,c]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async u=>{const d={...u,params:{}};l.headers={...this.headers,...u.params};let h;try{h=await fetch(u.target,l)}catch(S){if(!(S instanceof Error))throw S;return[d,ou(S)?new Ce({url:o}):S]}const b=await h.arrayBuffer();if(h?.ok)return a!=null&&(i=this.encoder.decode(b,a)),[d,null];try{if(h.status!==lu)return[d,new Error(h.statusText)];const S=this.encoder.decode(b,Ie.payloadZ),R=Ie.decode(S);return[d,R]}catch(S){return[d,new Error(`[freighter] - failed to decode error: ${h.statusText}: ${S.message}`)]}});if(c!=null)return[null,c];if(i==null)throw new Error("Response must be defined");return[i,null]}}const uu=(r,e)=>{class t{wrapped;constructor(a){this.wrapped=a}use(...a){this.wrapped.use(...a)}async send(a,i,o,l){const c=new Cc.Breaker(e);do{const[u,d]=await this.wrapped.send(a,i,o,l);if(d==null)return[u,null];if(!Ce.matches(d))return[null,d];if(!await c.wait())return[u,d]}while(!0)}}return new t(r)},g=async(r,e,t,n,a)=>{const[i,o]=await r.send(e,t,n,a);if(o!=null)throw o;return i},hu=s.z.object({type:s.z.enum(["data","close","open"]),payload:s.z.unknown(),error:s.z.optional(Ie.payloadZ)});class du{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,t,n,a){this.codec=t,this.reqSchema=n,this.resSchema=a,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return Ie.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new te;if(this.sendClosed)throw new rt;return this.ws.send(this.codec.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");if(this.serverClosed=Ie.decode(e.error),this.serverClosed==null)throw new Error("Message error must be defined");return[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((e,t)=>this.receiveCallbacksQueue.push({resolve:e,reject:t}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this)}onMessage(e){this.addMessage(this.codec.decode(e.data,hu))}onClose(e){this.addMessage({type:"close",error:{type:e.code===pu?te.TYPE:rt.TYPE,data:""}})}}const fu="freighterctx",pu=1e3;let yu=class dn extends _a{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,t,n=!1){super(),this.secure=n,this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}withCodec(e){const t=new dn(this.baseUrl,e,this.secure);return t.use(...this.middleware),t}async stream(e,t,n){let a;const[,i]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const l=new WebSocket(this.buildURL(e,o)),c={...o,params:{}};l.binaryType=dn.MESSAGE_TYPE;const u=await this.wrapSocket(l,t,n);return u instanceof Error?[c,u]:(a=u,[c,null])});if(i!=null)throw i;return a}buildURL(e,t){const n=Nc({[Va]:this.encoder.contentType,...t.params},fu);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(a=>{e.onopen=()=>{const i=new du(e,this.encoder,t,n);i.receiveOpenAck().then(o=>{o!=null?a(o):a(i)}).catch(o=>a(o))},e.onerror=i=>{const o=i;a(new Error(o.message))}})}};const gu=r=>Array.isArray(r)?r:r==null?[]:[r],O=Object.freeze(Object.defineProperty({__proto__:null,toArray:gu},Symbol.toStringTag,{value:"Module"})),mu=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Vn=r=>{const e=(t,n=fn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Fr(t))return t;n=Tu(n);const a={},i=t;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),n):(Object.keys(i).forEach(o=>{let l=i[o];const c=r(o);n.recursive&&(Fr(l)?Ms(l)||(l=e(l,n)):n.recursiveInArray&&Ls(l)&&(l=[...l].map(u=>{let d=u;return Fr(u)?Ms(d)||(d=e(u,n)):Ls(u)&&(d=e({key:u},n).key),d}))),a[c]=l}),a)};return e},Hn=Vn(mu),wu=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Ha=Vn(wu),bu=r=>r.length===0?r:r[0].toUpperCase()+r.slice(1),vu=[Number,String,Uint8Array],fn={recursive:!0,recursiveInArray:!0},Tu=(r=fn)=>(r.recursive==null?r=fn:r.recursiveInArray??=!1,r),Ls=r=>r!=null&&Array.isArray(r),Fr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Ms=r=>vu.some(e=>r instanceof e),Ou=r=>r.replace(/\s+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}-${n.toLowerCase()}`).toLowerCase(),Su=Vn(Ou),zu=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:Ha,capitalize:bu,snakeToCamel:Hn,toKebab:Su},Symbol.toStringTag,{value:"Module"})),Wa=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);let Ga=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r))}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),n=Hn(t);return e!=null?e.parse(n):n}encodeString(r){const e=Ha(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):typeof n=="bigint"?n.toString():n)}},Ka=class{contentType="text/csv";encode(r){const e=this.encodeString(r);return new TextEncoder().encode(e)}decode(r,e){const t=new TextDecoder().decode(r);return this.decodeString(t,e)}encodeString(r){if(!Array.isArray(r)||r.length===0||!Wa(r[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(r[0]),t=[e.join(",")];return r.forEach(n=>{const a=e.map(i=>JSON.stringify(n[i]??""));t.push(a.join(","))}),t.join(`
|
|
7
|
-
`)}decodeString(r,e){const[t,...n]=r.trim().split(`
|
|
8
|
-
`).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const a=t.split(",").map(o=>o.trim()),i={};return a.forEach(o=>{i[o]=[]}),n.forEach(o=>{const l=o.split(",").map(c=>c.trim());a.forEach((c,u)=>{const d=this.parseValue(l[u]);d!=null&&i[c].push(d)})}),e!=null?e.parse(i):i}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}},Ja=class{contentType="text/plain";encode(r){if(typeof r!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(r)}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const xt=new Ga,Eu=new Ka,Nu=new Ja,Au=[xt],$e=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Ka,CSV_CODEC:Eu,ENCODERS:Au,JSONCodec:Ga,JSON_CODEC:xt,TEXT_CODEC:Nu,TextCodec:Ja},Symbol.toStringTag,{value:"Module"})),pn=r=>[...new Set(r)],ku=(r,e,t=!0)=>{const n=new Map;return r.forEach(a=>{const i=e(a);if(n.has(i)){if(t)return;n.delete(i)}n.set(i,a)}),Array.from(n.values())},Ps=Object.freeze(Object.defineProperty({__proto__:null,by:ku,unique:pn},Symbol.toStringTag,{value:"Module"}));let ut=class{value;constructor(r){this.value=r}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const xu=r=>r!=null&&typeof r=="object"&&"toString"in r,zr=(r,e=!1)=>{const t=xu(r)?"stringer":typeof r;let n;switch(t){case"string":n=(a,i)=>a.localeCompare(i);break;case"stringer":n=(a,i)=>a.toString().localeCompare(i.toString());break;case"number":n=(a,i)=>Number(a)-Number(i);break;case"bigint":n=(a,i)=>BigInt(a)-BigInt(i)>0n?1:-1;break;case"boolean":n=(a,i)=>Number(a)-Number(i);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Qa(n):n},Iu=(r,e,t)=>{const n=zr(e[r],t);return(a,i)=>n(a[r],i[r])},Cu=(r,e)=>r.length!==e.length?r.length-e.length:r.every((t,n)=>t===e[n])?0:-1,Xa=(r,e)=>{if(r.length!==e.length)return r.length-e.length;if(r.length===0)return 0;const t=zr(r[0]),n=[...r].sort(t),a=[...e].sort(t);return n.every((i,o)=>i===a[o])?0:-1},ju=(r,e)=>{const t=pn(r),n=pn(e);return Xa(t,n)},Ru=(r,e)=>r===e?0:r==="first"&&e==="last"?1:-1,Qa=r=>(e,t)=>r(t,e),ht=0,cr=-1,ur=1,ei=r=>r<ht,ti=r=>r>ht,Uu=r=>r>=ht,ri=r=>r===ht,Lu=(r,e)=>{const t=/([a-zA-Z]+)|(\d+)/g,n=r.replace(/[\s_.-]+/g,"").match(t),a=e.replace(/[\s_.-]+/g,"").match(t);if(!n||!a)return 0;for(let i=0;i<Math.min(n.length,a.length);i++){const o=n[i],l=a[i];if(isNaN(Number(o))&&isNaN(Number(l))){const c=o.localeCompare(l);if(c!==0)return c}else if(!isNaN(Number(o))&&!isNaN(Number(l))){const c=Number(o)-Number(l);if(c!==0)return c}else return isNaN(Number(o))?-1:1}return n.length-a.length},Ds=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:ht,GREATER_THAN:ur,LESS_THAN:cr,isEqualTo:ri,isGreaterThan:ti,isGreaterThanEqual:Uu,isLessThan:ei,newF:zr,newFieldF:Iu,order:Ru,primitiveArrays:Cu,reverseF:Qa,stringsWithNumbers:Lu,uniqueUnorderedPrimitiveArrays:ju,unorderedPrimitiveArrays:Xa},Symbol.toStringTag,{value:"Module"})),Er=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ni=s.z.object({width:s.z.number(),height:s.z.number()}),Mu=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Pu=["width","height"];s.z.enum(Pu);const Du=["start","center","end"],Bu=["signedWidth","signedHeight"];s.z.enum(Bu);const yr=s.z.object({x:s.z.number(),y:s.z.number()}),$u=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Fu=["x","y"],si=s.z.enum(Fu),ai=["top","right","bottom","left"];s.z.enum(ai);const Zu=["left","right"],ii=s.z.enum(Zu),qu=["top","bottom"],oi=s.z.enum(qu),li=["center"],Bs=s.z.enum(li),Yu=[...ai,...li],ci=s.z.enum(Yu);s.z.enum(Du);const _u=["first","last"];s.z.enum(_u);const Vu=s.z.object({lower:s.z.number(),upper:s.z.number()}),Hu=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Vu,Er]);s.z.union([Hu,Er]);s.z.enum([...si.options,...ci.options]);s.z.union([si,ci,s.z.instanceof(String)]);const Zr=(r,e)=>typeof r=="bigint"?r-BigInt(e):r-Number(e),Wu=(r,e)=>typeof r=="bigint"?r+BigInt(e):r+Number(e),$s=(r,e)=>typeof r=="bigint"?r===BigInt(e):r===Number(e),Gu=(r,e)=>r<=e?r:typeof r=="bigint"?r<=e?r:BigInt(e):r<=e?r:Number(e),Ku=r=>r<0?-r:r,Ye=(r,e)=>typeof r=="bigint"?r*BigInt(e):r*Number(e),Y=(r,e,t)=>{const n={};if(typeof e=="object"&&(t=e,e=void 0),t={makeValid:!0,...t},typeof r=="number"||typeof r=="bigint")e!=null?(n.lower=r,n.upper=e):(n.lower=typeof r=="bigint"?0n:0,n.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=r}else n.lower=r.lower,n.upper=r.upper;return t?.makeValid?Ju(n):n},Ju=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Fs=(r,e)=>{const t=Y(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},tr=(r,e)=>{const t=Y(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=Y(e);return n.lower>=t.lower&&n.upper<=t.upper},Xu=r=>({lower:Math.min(...r.map(e=>Y(e).lower)),upper:Math.max(...r.map(e=>Y(e).upper))}),Qu=(r,e,t)=>{const n=r.map(l=>Y(l)),a=t>0?1:t<0?-1:0;if(a===0)return e;let i=t,o=e;for(;$s(i,0)===!1;){const l=n.findIndex(c=>a>0?o>=c.lower&&o<c.upper:o>c.lower&&o<=c.upper);if(l!==-1){const c=n[l];let u;if(a>0?u=Zr(c.upper,o):u=Zr(o,c.lower),u>0){const d=Gu(Ku(i),u);if(o=Wu(o,a>0?d:-d),i=Zr(i,a>0?d:-d),$s(i,0))return o;continue}}if(a>0){const c=n.filter(u=>u.lower>o);if(c.length>0)o=c[0].lower;else return o}else{const c=n.filter(u=>u.upper<o);if(c.length>0)o=c[c.length-1].upper;else return o}}return o},eh=(r,e,t)=>{const n=r.map(o=>Y(o));if(e===t)return typeof e=="bigint"?0n:0;const a=e<t?Y([e,t]):Y([t,e]);let i=typeof e=="bigint"?0n:0;for(const o of n){const l=o.lower>a.lower?o.lower:a.lower,c=o.upper<a.upper?o.upper:a.upper;if(l<c){const u=c-l;i=i+u}}return i};s.z.object({x:ii.or(Bs),y:oi.or(Bs)});const th=s.z.object({x:ii,y:oi}),rh=Object.freeze({x:"left",y:"top"}),nh=(r,e)=>r.x===e.x&&r.y===e.y,Zs=s.z.union([s.z.number(),yr,Er,ni,Mu,$u]),sh=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},qs=Object.freeze({x:0,y:0}),rr=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:rr,left:rr,width:rr,height:rr});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:yr,two:yr,root:th});const Wn=(r,e,t=0,n=0,a)=>{const i={one:{...qs},two:{...qs},root:a??rh};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:r,y:e},i.two={x:i.one.x+t,y:i.one.y+n},i}return"one"in r&&"two"in r&&"root"in r?{...r,root:a??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(i.one={x:r.left,y:r.top},i.two={x:r.right,y:r.bottom},i):(i.one=r,e==null?i.two={x:i.one.x+t,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+t}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},qr=r=>{const e=Wn(r);return{lower:e.one.x,upper:e.two.x}},Yr=r=>{const e=Wn(r);return{lower:e.one.y,upper:e.two.y}},ah=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,ih=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ni,ih,yr,Er]);const oh=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Zs,scale:Zs});s.z.object({offset:s.z.number(),scale:s.z.number()});const lh=r=>(e,t,n,a)=>t==="dimension"?[e,n]:[e,a?n-r:n+r],ch=r=>(e,t,n,a)=>[e,a?n/r:n*r],uh=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:a,upper:i}=e,{lower:o,upper:l}=r,c=i-a,u=l-o;if(t==="dimension")return[r,n*(u/c)];const d=(n-a)*(u/c)+o;return[r,d]},hh=r=>(e,t,n)=>[r,n],dh=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:a}=r;return[r,a-(t-n)]},fh=r=>(e,t,n)=>{const{lower:a,upper:i}=r;return n=oh(n,a,i),[e,n]};let Ys=class We{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new We().translate(e)}static magnify(e){return new We().magnify(e)}static scale(e,t){return new We().scale(e,t)}translate(e){const t=this.new(),n=lh(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=ch(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=Y(e,t),a=this.new(),i=uh(n);return i.type="scale",a.ops.push(i),a}clamp(e,t){const n=Y(e,t),a=this.new(),i=fh(n);return i.type="clamp",a.ops.push(i),a}reBound(e,t){const n=Y(e,t),a=this.new(),i=hh(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=dh();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new We;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||t.some(([o,l])=>a>=o&&a<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>a);i!==-1&&t.push([a,i])}),t.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new We};(class ie{x;y;currRoot;constructor(e=new Ys,t=new Ys,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ie().translate(e,t)}static translateX(e){return new ie().translateX(e)}static translateY(e){return new ie().translateY(e)}static clamp(e){return new ie().clamp(e)}static magnify(e){return new ie().magnify(e)}static scale(e){return new ie().scale(e)}static reBound(e){return new ie().reBound(e)}translate(e,t){const n=sh(e,t),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(ah(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!nh(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(qr(e)),t.y=t.y.scale(Yr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(qr(e)),t.y=this.y.reBound(Yr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(qr(e)),t.y=this.y.clamp(Yr(e)),t}copy(){const e=new ie;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Wn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new ie});let ph=(r,e=21)=>(t=e)=>{let n="",a=t|0;for(;a--;)n+=r[Math.random()*r.length|0];return n};const yh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ui=11,gh=ph(yh,ui),Gn=()=>gh(),mh=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:ui,create:Gn},Symbol.toStringTag,{value:"Module"})),wh=(r,e)=>t=>t instanceof e||typeof t=="object"&&t!==null&&"discriminator"in t&&t.discriminator===r,bh=s.z.enum(["static","dynamic"]),vh=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),hi=(r,e)=>{const t=new E(e);if(![z.DAY,z.HOUR,z.MINUTE,z.SECOND,z.MILLISECOND,z.MICROSECOND,z.NANOSECOND].some(a=>a.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof E?new E(n):new z(n)};let E=class w extends ut{constructor(e,t="UTC"){if(e==null)super(w.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*w.MILLISECOND.valueOf());else if(typeof e=="string")super(w.parseDateTimeString(e,t).valueOf());else if(Array.isArray(e))super(w.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=w.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=w.MAX:e=w.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,t=1,n=1]){const a=new Date(e,t-1,n,0,0,0,0);return new w(BigInt(a.getTime())*w.MILLISECOND.valueOf()).truncate(w.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,a,i]=e.split(":");let o="00",l="00";i!=null&&([o,l]=i.split("."));let c=w.hours(parseInt(n??"00")).add(w.minutes(parseInt(a??"00"))).add(w.seconds(parseInt(o??"00"))).add(w.milliseconds(parseInt(l??"00")));return t==="local"&&(c=c.add(w.utcOffset)),c.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return w.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new w(BigInt(n.getTime())*w.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(w.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new z(BigInt(new Date().getTimezoneOffset())*w.MINUTE.valueOf())}static since(e){return new w().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new w(e).valueOf()}span(e){return this.range(e).span}range(e){return new L(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new w(e).valueOf()}afterEq(e){return this.valueOf()>=new w(e).valueOf()}before(e){return this.valueOf()<new w(e).valueOf()}beforeEq(e){return this.valueOf()<=new w(e).valueOf()}add(e){return new w(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new w(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(w.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(w.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const t=this.date();return t.setUTCFullYear(e),new w(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new w(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new w(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new w(t,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new w(t)}get second(){return this.date().getUTCSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new w(t)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const t=this.date();return t.setUTCMilliseconds(e),new w(t)}toString(){return this.date().toISOString()}remainder(e){return hi(this,e)}get isToday(){return this.truncate(z.DAY).equals(w.now().truncate(z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new w(new Date)}static max(...e){let t=w.MIN;for(const n of e){const a=new w(n);a.after(t)&&(t=a)}return t}static min(...e){let t=w.MAX;for(const n of e){const a=new w(n);a.before(t)&&(t=a)}return t}static nanoseconds(e,t="UTC"){return new w(e,t)}static NANOSECOND=w.nanoseconds(1);static microseconds(e,t="UTC"){return w.nanoseconds(e*1e3,t)}static MICROSECOND=w.microseconds(1);static milliseconds(e,t="UTC"){return w.microseconds(e*1e3,t)}static MILLISECOND=w.milliseconds(1);static seconds(e,t="UTC"){return w.milliseconds(e*1e3,t)}static SECOND=w.seconds(1);static minutes(e,t="UTC"){return w.seconds(e*60,t)}static MINUTE=w.minutes(1);static hours(e,t="UTC"){return w.minutes(e*60,t)}static HOUR=w.hours(1);static days(e,t="UTC"){return w.hours(e*24,t)}static DAY=w.days(1);static MAX=new w((1n<<63n)-1n);static MIN=new w(0);static ZERO=new w(0);static z=s.z.union([s.z.instanceof(w),s.z.object({value:s.z.bigint()}).transform(e=>new w(e.value)),s.z.string().transform(e=>new w(BigInt(e))),s.z.number().transform(e=>new w(e)),s.z.bigint().transform(e=>new w(e)),s.z.date().transform(e=>new w(e)),s.z.custom(e=>e instanceof z).transform(e=>new w(e)),vh.transform(e=>new w(e))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},z=class T extends ut{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof T?e:e instanceof _s?e.period:e instanceof E?new T(e):["number","bigint"].includes(typeof e)?T.seconds(e):new T(e)}static fromMilliseconds(e){return e instanceof T?e:e instanceof _s?e.period:e instanceof E?new T(e):["number","bigint"].includes(typeof e)?T.milliseconds(e):new T(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new T(e).valueOf()}greaterThan(e){return this.valueOf()>new T(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new T(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new T(e).valueOf()}remainder(e){return hi(this,e)}truncate(e){return new T(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(T.DAY),t=this.truncate(T.HOUR),n=this.truncate(T.MINUTE),a=this.truncate(T.SECOND),i=this.truncate(T.MILLISECOND),o=this.truncate(T.MICROSECOND),l=this.truncate(T.NANOSECOND),c=e,u=t.sub(e),d=n.sub(t),h=a.sub(n),b=i.sub(a),S=o.sub(i),R=l.sub(o);let A="";return c.isZero||(A+=`${c.days}d `),u.isZero||(A+=`${u.hours}h `),d.isZero||(A+=`${d.minutes}m `),h.isZero||(A+=`${h.seconds}s `),b.isZero||(A+=`${b.milliseconds}ms `),S.isZero||(A+=`${S.microseconds}µs `),R.isZero||(A+=`${R.nanoseconds}ns`),A.trim()}mult(e){return new T(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(T.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(T.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(T.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(T.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(T.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new T(e).valueOf()}add(e){return new T(this.valueOf()+new T(e).valueOf())}sub(e){return new T(this.valueOf()-new T(e).valueOf())}static nanoseconds(e=1){return new T(e)}static NANOSECOND=T.nanoseconds(1);static microseconds(e=1){return T.nanoseconds(Ye(e,1e3))}static MICROSECOND=T.microseconds(1);static milliseconds(e=1){return T.microseconds(Ye(e,1e3))}static MILLISECOND=T.milliseconds(1);static seconds(e=1){return T.milliseconds(Ye(e,1e3))}static SECOND=T.seconds(1);static minutes(e=1){return T.seconds(Ye(e,60))}static MINUTE=T.minutes(1);static hours(e){return T.minutes(Ye(e,60))}static HOUR=T.hours(1);static days(e){return T.hours(Ye(e,24))}static DAY=T.days(1);static MAX=new T((1n<<63n)-1n);static MIN=new T(0);static ZERO=new T(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new T(e.value)),s.z.string().transform(e=>new T(BigInt(e))),s.z.number().transform(e=>new T(e)),s.z.instanceof(T)])},_s=class Ge extends ut{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Ge(e).valueOf()}get period(){return z.seconds(1/this.valueOf())}sampleCount(e){return new z(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new H(t).valueOf()}span(e){return z.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Ge(e)}static khz(e){return Ge.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new Ge(e)),s.z.instanceof(Ge)])},H=class fe extends ut{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new nt(e*this.valueOf())}static UNKNOWN=new fe(0);static BIT128=new fe(16);static BIT64=new fe(8);static BIT32=new fe(4);static BIT16=new fe(2);static BIT8=new fe(1);static z=s.z.union([s.z.number().transform(e=>new fe(e)),s.z.instanceof(fe)])},L=class oe{start;end;constructor(e,t){typeof e=="object"&&"start"in e?(this.start=new E(e.start),this.end=new E(e.end)):(this.start=new E(e),this.end=new E(t))}get span(){return new z(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new oe(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=z.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),a=this.end.sub(e.end).valueOf();return n<0&&(n=-n),a<0&&(a=-a),n<=t.valueOf()&&a<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=z.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const a=E.max(n.start,e.start),i=E.min(n.end,e.end);return i.before(a)?!1:new z(i.sub(a)).greaterThanOrEqual(t)}contains(e){return e instanceof oe?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new oe(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}static max(...e){return new oe(E.min(...e.map(t=>t.start)),E.max(...e.map(t=>t.end)))}static MAX=new oe(E.MIN,E.MAX);static MIN=new oe(E.MAX,E.MIN);static ZERO=new oe(E.ZERO,E.ZERO);static z=s.z.union([s.z.object({start:E.z,end:E.z}).transform(e=>new oe(e.start,e.end)),s.z.instanceof(oe)]);static sort(e,t){return E.sort(e.start,t.start)||E.sort(e.end,t.end)}},N=class y extends ut{constructor(e){if(e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const t=y.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t==null)throw new Error(`unable to find data type for ${e.toString()}`);super(t.valueOf())}}get Array(){const e=y.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(y.JSON)||this.equals(y.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(y.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=y.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(y.UINT8)||this.equals(y.UINT16)||this.equals(y.UINT32)||this.equals(y.UINT64)}get isSignedInteger(){return this.equals(y.INT8)||this.equals(y.INT16)||this.equals(y.INT32)||this.equals(y.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(y.INT32)&&e.equals(y.FLOAT64)||this.equals(y.INT8)&&e.equals(y.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return y.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new y("unknown");static FLOAT64=new y("float64");static FLOAT32=new y("float32");static INT64=new y("int64");static INT32=new y("int32");static INT16=new y("int16");static INT8=new y("int8");static UINT64=new y("uint64");static UINT32=new y("uint32");static UINT16=new y("uint16");static UINT8=new y("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new y("timestamp");static UUID=new y("uuid");static STRING=new y("string");static JSON=new y("json");static ARRAY_CONSTRUCTORS=new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]]);static DENSITIES=new Map([[y.UINT8.toString(),H.BIT8],[y.UINT16.toString(),H.BIT16],[y.UINT32.toString(),H.BIT32],[y.UINT64.toString(),H.BIT64],[y.FLOAT32.toString(),H.BIT32],[y.FLOAT64.toString(),H.BIT64],[y.INT8.toString(),H.BIT8],[y.INT16.toString(),H.BIT16],[y.INT32.toString(),H.BIT32],[y.INT64.toString(),H.BIT64],[y.TIMESTAMP.toString(),H.BIT64],[y.STRING.toString(),H.UNKNOWN],[y.JSON.toString(),H.UNKNOWN],[y.UUID.toString(),H.BIT128]]);static ALL=[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON];static BIG_INT_TYPES=[y.INT64,y.UINT64,y.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new y(e)),s.z.instanceof(y)])},nt=class j extends ut{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return j.bytes(this.valueOf()+e.valueOf())}sub(e){return j.bytes(this.valueOf()-e.valueOf())}truncate(e){return new j(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return j.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/j.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/j.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/j.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/j.TERABYTE.valueOf()}toString(){const e=this.truncate(j.TERABYTE),t=this.truncate(j.GIGABYTE),n=this.truncate(j.MEGABYTE),a=this.truncate(j.KILOBYTE),i=this.truncate(j.BYTE),o=e,l=t.sub(e),c=n.sub(t),u=a.sub(n),d=i.sub(a);let h="";return o.isZero||(h+=`${o.terabytes}TB `),l.isZero||(h+=`${l.gigabytes}GB `),c.isZero||(h+=`${c.megabytes}MB `),u.isZero||(h+=`${u.kilobytes}KB `),(!d.isZero||h==="")&&(h+=`${d.valueOf()}B`),h.trim()}static bytes(e=1){return new j(e)}static BYTE=new j(1);static kilobytes(e=1){return j.bytes(e.valueOf()*1e3)}static KILOBYTE=j.kilobytes(1);static megabytes(e=1){return j.kilobytes(e.valueOf()*1e3)}static MEGABYTE=j.megabytes(1);static gigabytes(e=1){return j.megabytes(e.valueOf()*1e3)}static GIGABYTE=j.gigabytes(1);static terabytes(e){return j.gigabytes(e.valueOf()*1e3)}static TERABYTE=j.terabytes(1);static ZERO=new j(0);static z=s.z.union([s.z.number().transform(e=>new j(e)),s.z.instanceof(j)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const di=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof E||r instanceof z||r instanceof Date},Th=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):hr(t,-n),hr=(r,e)=>e==0?r:r==0?e:typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:Number(r)+Number(e),Oh=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Sh(r){return typeof r=="string"&&Oh.test(r)}const q=[];for(let r=0;r<256;++r)q.push((r+256).toString(16).slice(1));function zh(r,e=0){return(q[r[e+0]]+q[r[e+1]]+q[r[e+2]]+q[r[e+3]]+"-"+q[r[e+4]]+q[r[e+5]]+"-"+q[r[e+6]]+q[r[e+7]]+"-"+q[r[e+8]]+q[r[e+9]]+"-"+q[r[e+10]]+q[r[e+11]]+q[r[e+12]]+q[r[e+13]]+q[r[e+14]]+q[r[e+15]]).toLowerCase()}function Eh(r,e=0){const t=zh(r,e);if(!Sh(t))throw TypeError("Stringified UUID is invalid");return t}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const fi=(r,e)=>Eh(r,e),ve=-1,yn={[Symbol.iterator]:()=>yn,next:()=>({done:!0,value:void 0})},Nh=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Ah=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),gn=10,pi=(r,e)=>{if(r==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(r==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},yi="sy_x_telem_series";let Ae=class ze{key;discriminator=yi;dataType;sampleOffset;gl;_data;timeRange=L.ZERO;alignment=0n;cachedMin;cachedMax;writePos=ve;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:L.z.optional(),dataType:N.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([Nh,Ah,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:bh.optional().default("static").optional()});static z=ze.crudeZ.transform(e=>new ze(e));constructor(e){kh(e)&&(e={data:e}),e.data??=[];const{dataType:t,timeRange:n,sampleOffset:a=0,glBufferUsage:i="static",alignment:o=0n,key:l=Gn(),data:c}=e;if(gi(c)){const h=c;this.key=h.key,this.dataType=h.dataType,this.sampleOffset=h.sampleOffset,this.gl=h.gl,this._data=h._data,this.timeRange=h.timeRange,this.alignment=h.alignment,this.cachedMin=h.cachedMin,this.cachedMax=h.cachedMax,this.writePos=h.writePos,this._refCount=h._refCount,this.cachedLength=h.cachedLength;return}const u=di(c),d=Array.isArray(c);if(t!=null)this.dataType=new N(t);else{if(c instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||u){let h=c;if(!u){if(c.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");h=c[0]}if(typeof h=="string")this.dataType=N.STRING;else if(typeof h=="number")this.dataType=N.FLOAT64;else if(typeof h=="bigint")this.dataType=N.INT64;else if(typeof h=="boolean")this.dataType=N.BOOLEAN;else if(h instanceof E||h instanceof Date||h instanceof E)this.dataType=N.TIMESTAMP;else if(typeof h=="object")this.dataType=N.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new N(c)}if(!d&&!u)this._data=c;else if(d&&c.length===0)this._data=new this.dataType.Array([]).buffer;else{let h=u?[c]:c;const b=h[0];(b instanceof E||b instanceof Date||b instanceof z)&&(h=h.map(S=>new E(S).valueOf())),this.dataType.equals(N.STRING)?(this.cachedLength=h.length,this._data=new TextEncoder().encode(`${h.join(`
|
|
9
|
-
`)}
|
|
10
|
-
`).buffer):this.dataType.equals(N.JSON)?(this.cachedLength=h.length,this._data=new TextEncoder().encode(`${h.map(S=>xt.encodeString(S)).join(`
|
|
11
|
-
`)}
|
|
12
|
-
`).buffer):this.dataType.usesBigInt&&typeof b=="number"?this._data=new this.dataType.Array(h.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof b=="bigint"?this._data=new this.dataType.Array(h.map(Number)).buffer:this._data=new this.dataType.Array(h).buffer}this.key=l,this.alignment=o,this.sampleOffset=a??0,this.timeRange=n??L.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const a=new new N(t).Array(e),i=new ze({data:a.buffer,dataType:t,...n});return i.writePos=0,i}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===ve)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===ve)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===ve?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
|
|
13
|
-
`).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(N.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(t=>e.parse(xt.decodeString(t)))}get byteCapacity(){return new nt(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ve?this.byteCapacity:this.dataType.isVariable?new nt(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===ve?this.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,a)=>{n===gn&&(e++,t.push(a+1))}),this._cachedIndexes=t,this.cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let a=0;a<this.length;a++)n[a]=Th(this.dataType,e,this.data[a],t);return new ze({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(N.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this.cachedMax=e.reduce((t,n)=>t>n?t:n)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),hr(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(N.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this.cachedMin=e.reduce((t,n)=>t<n?t:n)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),hr(this.cachedMin,this.sampleOffset))}get bounds(){return Y(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const t=e.cachedMin??e.calcRawMin();t<this.cachedMin&&(this.cachedMin=t)}if(this.cachedMax!=null){const t=e.cachedMax??e.calcRawMax();t>this.cachedMax&&(this.cachedMax=t)}}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(N.UUID))return this.atUUID(e,t);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return hr(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);const n=fi(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,a=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],a=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===gn){if(e===0){a=o;break}n=o+1,e--}if(a===0&&(a=this.data.length),n>=a||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(n,a);return this.dataType.equals(N.STRING)?new TextDecoder().decode(i):Hn(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let t=0,n=this.length-1;const a=zr(e);for(;t<=n;){const i=Math.floor((t+n)/2),o=a(this.at(i,!0),e);if(o===0)return i;o<0?t=i+1:n=i-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(N.FLOAT32)&&!this.dataType.equals(N.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:a}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==a)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==ve){a===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const i=this.dataType.density.size(a).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,i,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=ve}as(e){return pi(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Hs(this.alignmentBounds.lower),upper:Hs(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return Y(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new xh(this);return this.dataType.equals(N.JSON)?new Kn(e):e}return this.dataType.equals(N.UUID)?new Ih(this):new Ch(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Vs(this,e,t??this.length)}subAlignmentIterator(e,t){return new Vs(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new ze({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let a;return e?a=this.data.subarray(t,n):a=this.data.slice(t,n),new ze({data:a,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ze({data:this.buffer,dataType:this.dataType,timeRange:L.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(t=>t.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=",";e+="...,";for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=",")}return e+="])",e}};const kh=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Ae?!0:di(r),gi=wh(yi,Ae);let Vs=class{series;end;index;constructor(r,e,t){this.series=r;const n=Y(0,r.length);this.end=Fs(n,t),this.index=Fs(n,e)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},xh=class{series;index;decoder;constructor(r){if(!r.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=r,this.index=0,this.decoder=new TextDecoder}next(){const r=this.index,e=this.series.data;for(;this.index<e.length&&e[this.index]!==gn;)this.index++;const t=this.index;return r===t?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(r,t))})}};class Kn{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:xt.decodeString(e.value,Kn.schema)}}}class Ih{series;index;data;density;constructor(e){if(!e.dataType.equals(N.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=N.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=fi(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}class Ch{series;index;constructor(e){this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class jh{series;constructor(e=[]){if(e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){return pi(e,this.dataType),this}get dataType(){return this.series.length===0?N.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?L.ZERO:new L(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?Y(0n,0n):Y(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){const t=()=>new Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),n=e.dataType.equals(this.dataType);if(gi(e)){if(this.series.length!==0&&!n)throw t();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!n)throw t();this.series.push(...e.series)}}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){for(const n of this.series)if(tr(n.alignmentBounds,e))return n.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new _r(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return yn;let n=0;for(let i=0;i<this.series.length;i++){const o=this.series[i];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)n+=o.length;else if(tr(o.alignmentBounds,e)){n+=Number(e-o.alignment);break}}let a=0;for(let i=0;i<this.series.length;i++){const o=this.series[i];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)a+=o.length;else if(tr(o.alignmentBounds,t)){a+=Number(t-o.alignment);break}}return new _r(this,n,a)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return yn;t=Math.min(t,Number(this.distance(e,this.alignmentBounds.upper)));let n=0;for(let a=0;a<this.series.length;a++){const i=this.series[a];if(e<i.alignment)break;if(e>=i.alignmentBounds.upper)n+=i.length;else if(tr(i.alignmentBounds,e)){n+=Number(e-i.alignment);break}}return new _r(this,n,n+t)}updateGLBuffer(e){this.series.forEach(t=>t.updateGLBuffer(e))}get bounds(){return Xu(this.series.map(e=>e.bounds))}get byteLength(){return new nt(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const n=this.series.map(a=>a.alignmentBounds);return Qu(n,e,t)}acquire(e){this.series.forEach(t=>t.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,t){const n=this.series.map(a=>a.alignmentBounds);return eh(n,e,t)}parseJSON(e){if(!this.dataType.equals(N.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(t=>t.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Rh(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}let Rh=class{series;seriesIndex;internal;constructor(r){this.series=r,this.seriesIndex=0,this.internal=r[0][Symbol.iterator]()}next(){const r=this.internal.next();return r.done===!1?r:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[Symbol.iterator](){return this}};class _r{series;index;end;constructor(e,t,n){this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}const Hs=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},Uh=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Lh=(r,e,t=".")=>{const n=r.split(t);return n.map((a,i)=>{const o=e(a,i,n);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(a=>a!=null).join(t)},Mh=(r,e)=>{if(!Array.isArray(r))return r[e];const t=r[e];if(t!=null||r.length==0)return t;const n=r[0];if(typeof n=="object"&&"key"in n)return r.find(a=>a.key===e)},Ph=(r,e,t={optional:!1,separator:"."})=>{t.separator??=".";const{optional:n,getter:a=Mh}=t,i=e.split(t.separator);if(i.length===1&&i[0]==="")return r;let o=r;for(const l of i){const c=a(o,l);if(c==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${l} is null`)}o=c}return o};s.z.object({key:s.z.string(),value:s.z.string()});class Dh{handlers;transform;closer;constructor(e,t){this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,a]=this.transform(e);if(!a)return;t=n}this.handlers.forEach((n,a)=>a(t))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}}let Bh=class{handlers;constructor(r){this.handlers=r??new Map}onChange(r){return this.handlers.set(r,null),()=>this.handlers.delete(r)}notify(r){this.handlers.forEach((e,t)=>t(r))}};const $h=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:Bh,Observer:Dh},Symbol.toStringTag,{value:"Module"})),Fh=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),Jn=r=>Object.entries(r),Zh=(r,e)=>Object.fromEntries(Jn(r).map(([t,n])=>[t,e(n,t)])),qh=r=>Object.fromEntries(Jn(r).filter(([e,t])=>t!==void 0)),ge=Object.freeze(Object.defineProperty({__proto__:null,entries:Jn,map:Zh,purgeUndefined:qh,unknownZ:Fh},Symbol.toStringTag,{value:"Module"})),Yh=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Yh();const _h=["macOS","Windows","Linux"],Vh=["macos","windows","linux"],Hh={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(_h).or(s.z.enum(Vh).transform(r=>Hh[r]));const Wh=(...r)=>r.map(mi).join(""),mi=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Gh=r=>r.endsWith("/")?r.slice(0,-1):r;class Nt{protocol;host;port;path;constructor({host:e,port:t,protocol:n="",pathPrefix:a=""}){this.protocol=n,this.host=e,this.port=t,this.path=mi(a)}replace(e){return new Nt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Nt({...this,pathPrefix:Wh(this.path,e)})}toString(){return Gh(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new Nt({host:"unknown",port:0})}const Kh=r=>r.nullable().transform(e=>e===null?void 0:e).optional(),Jh=r=>s.array(r).or(r.transform(e=>[e])),wi=r=>Lh(r,(e,t,n)=>{const a=t===n.length-1,i=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[t+1]));return i&&(e="element"),a||o?e:[e,"shape"]}),Ws=(r,e)=>{if(r==null)return null;const t=r[e];return t==null&&typeof r=="object"&&"sourceType"in r?r.sourceType()[e]:t},Xh=(r,e,t)=>Ph(Ws(r,"shape"),wi(e),{...t,getter:Ws}),At=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:Xh,getFieldSchemaPath:wi,nullToUndefined:Kh,toArray:Jh},Symbol.toStringTag,{value:"Module"})),Qh=async r=>await new Promise(e=>setTimeout(e,z.fromMilliseconds(r).milliseconds));class ed{config;retries;interval;constructor(e){this.config={baseInterval:new z(e?.baseInterval??z.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Qh},this.retries=0,this.interval=new z(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),this.retries++,!0)}reset(){this.retries=0,this.interval=this.config.baseInterval}}const td=s.z.object({baseInterval:z.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),bi=Object.freeze(Object.defineProperty({__proto__:null,Breaker:ed,breakerConfigZ:td},Symbol.toStringTag,{value:"Module"})),rd=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,vi=s.z.string().regex(rd),tt=s.z.number().min(0).max(255),Ti=s.z.number().min(0).max(1),Oi=s.z.tuple([tt,tt,tt,Ti]),nd=s.z.tuple([tt,tt,tt]),sd=s.z.object({rgba255:Oi}),ad=s.z.number().min(0).max(360),id=s.z.number().min(0).max(100),od=s.z.number().min(0).max(100),ld=s.z.tuple([ad,id,od,Ti]),Xn=s.z.union([vi,nd,Oi,ld,sd]),cd=Xn.transform(r=>Qn(r)),Qn=(r,e=1)=>{if(r=Xn.parse(r),typeof r=="string")return ud(r,e);if(Array.isArray(r)){if(r.length<3||r.length>4)throw new Error(`Invalid color: [${r.join(", ")}]`);return r.length===3?[...r,e]:r}return r.rgba255},ud=(r,e=1)=>(r=vi.parse(r),r=hd(r),[nr(r,0),nr(r,2),nr(r,4),r.length===8?nr(r,6)/255:e]),nr=(r,e)=>parseInt(r.slice(e,e+2),16),hd=r=>r.startsWith("#")?r.slice(1):r;Qn("#000000");Qn("#ffffff");const dd=s.z.object({key:s.z.string(),color:Xn,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(dd);const fd=s.z.object({key:s.z.string(),name:s.z.string(),color:cd});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(fd)});const Si=s.z.int().min(0).max(255),zi=255,Ei=0,pd={lower:Ei,upper:zi+1},Ni=s.z.object({name:s.z.string(),key:s.z.string()}),It=r=>s.z.object({subject:Ni,resource:r,authority:Si}),yd=(...r)=>e=>e.filter(t=>{let n=!1;return t.to!=null&&(n=r.includes(t.to.resource)),t.from!=null&&!n&&(n=r.includes(t.from.resource)),n}),Ai=r=>s.z.object({from:It(r),to:s.z.null()}),ki=r=>s.z.object({from:s.z.null(),to:It(r)}),gd=r=>s.z.union([Ai(r),ki(r),s.z.object({from:It(r),to:It(r)})]),X=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:zi,AUTHORITY_BOUNDS:pd,ZERO_AUTHORITY:Ei,acquireZ:ki,authorityZ:Si,filterTransfersByChannelKey:yd,releaseZ:Ai,stateZ:It,subjectZ:Ni,transferZ:gd},Symbol.toStringTag,{value:"Module"})),md=r=>Object.getOwnPropertySymbols(globalThis).includes(r),wd=(r,e)=>{const t=Symbol.for(r);if(!md(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},xi="sy_x_error",bd=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(r):e instanceof Error?e.message.startsWith(r):typeof e!="string"?!1:e.startsWith(r),Ft=r=>class Et extends Error{static discriminator=xi;discriminator=Et.discriminator;static TYPE=r;type=Et.TYPE;static matches=bd(r);matches=Et.matches;constructor(t,n){super(t,n),this.name=Et.TYPE}static sub(t){return Ft(`${r}.${t}`)}},Ii=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!==xi)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Ke="unknown",mn="nil";class vd{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:mn,data:""};if(Ii(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Ke,data:e.message};if(typeof e=="string")return{type:Ke,data:e};try{return{type:Ke,data:JSON.stringify(e)}}catch{return{type:Ke,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===mn)return null;if(e.type===Ke)return new wn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new wn(e.data)}}const es=wd("synnax-error-registry",()=>new vd),Td=({encode:r,decode:e})=>es().register({encode:r,decode:e}),Od=r=>es().encode(r),Sd=r=>r==null?null:es().decode(r);class wn extends Ft("unknown"){}const zd=s.z.object({type:s.z.string(),data:s.z.string()});class Ed extends Ft("canceled"){}class Nd extends Ft("not_implemented"){}const ye=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Ed,NONE:mn,NotImplemented:Nd,UNKNOWN:Ke,Unknown:wn,createTyped:Ft,decode:Sd,encode:Od,isTyped:Ii,payloadZ:zd,register:Td},Symbol.toStringTag,{value:"Module"})),Ad=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),Ci=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),kd=Ci.extend({result:s.json()}),xd=Ci.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),Id=s.union([kd,xd]);s.union([Ad,Id]);const bn=s.z.string().regex(/^\d+\.\d+\.\d+$/),Zt=(r,e,t={})=>{t.checkMajor??=!0,t.checkMinor??=!0,t.checkPatch??=!0;const n=bn.parse(r),a=bn.parse(e),[i,o,l]=n.split(".").map(Number),[c,u,d]=a.split(".").map(Number);if(t.checkMajor){if(i<c)return cr;if(i>c)return ur}if(t.checkMinor){if(o<u)return cr;if(o>u)return ur}if(t.checkPatch){if(l<d)return cr;if(l>d)return ur}return ht},Cd=(r,e,t={})=>ri(Zt(r,e,t)),ji=(r,e,t={})=>ti(Zt(r,e,t)),jd=(r,e,t={})=>ei(Zt(r,e,t)),Rd=({name:r,migrate:e})=>t=>{try{const n=e(t);return console.log(`${r} migrated: ${t.version} -> ${n.version}`),n}catch(n){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(n),n}},Ud=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:a})=>{const i=Object.keys(e).sort(Zt).pop();if(i==null)return u=>{if(u.version??=n,u.version!==a.version)return console.log(`${r} version ${u.version} is newer than latest version of ${a.version}.
|
|
14
|
-
Returning default instead.
|
|
15
|
-
`),a;try{return t!=null?t.parse(u):u}catch(d){return console.log(`${r} failed to parse default. Exiting with default`),console.error(d),a}};const o=Object.keys(e).length;let l=!1;const c=u=>{try{if(o===0||ji(u.version,i))return console.log(l?`${r} ${u.version} now up to date`:`${r} version ${u.version} is up to date with target version ${a.version}`),u;const d=u.version,h=e[d],b=h(u);return l=!0,c(b)}catch(d){return console.log(`${r} failed to migrate from ${u.version} to ${i}`),console.error(d),a}};return u=>{try{if(u.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),u.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),a;return c(u)}catch(d){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(d),a}}},Gs=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Zt,createMigration:Rd,migrator:Ud,semVerNewer:ji,semVerOlder:jd,semVerZ:bn,versionsEqual:Cd},Symbol.toStringTag,{value:"Module"})),Ld=["standard","scientific","engineering"];s.z.enum(Ld);const Ri=s.z.enum(["success","info","warning","error","loading","disabled"]),Md=r=>s.z.object({key:s.z.string(),variant:Ri,message:s.z.string(),description:s.z.string().optional(),time:E.z,details:r??s.z.unknown().optional()}),Pd=(r,e)=>{if(!(r instanceof Error))throw r;return Ui({variant:"error",message:e??r.message,description:e!=null?r.message:void 0,details:{stack:r.stack??""}})},Ui=r=>({key:Gn(),time:E.now(),...r}),Nr=Object.freeze(Object.defineProperty({__proto__:null,create:Ui,fromException:Pd,statusZ:Md,variantZ:Ri},Symbol.toStringTag,{value:"Module"})),Dd=(r,e="")=>{const t=r.length;return t===0?e:t===1?r[0]:t===2?`${r[0]} and ${r[1]}`:`${r.slice(0,-1).join(", ")}, and ${r[t-1]}`},Bd=r=>{const e=r.split(" "),t=new Set,n=e.map(o=>o.charAt(0).toLowerCase()).join("");t.add(n.replace(/-/g,"_")),t.add(n.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const a=/\d+/g;r.match(a)&&e.forEach((o,l)=>{if(a.test(o)){const c=e.map((u,d)=>d!==l?u.charAt(0).toLowerCase():u).join("");t.add(c.replace(/-/g,"_")),t.add(c.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const i=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return t.add(i.join("").replace(/-/g,"_")),t.add(i.join("_").replace(/-/g,"_")),Array.from(t).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},$d=(r,e)=>r.startsWith(e)?r.slice(e.length):r,Fd=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:Bd,naturalLanguageJoin:Dd,trimPrefix:$d},Symbol.toStringTag,{value:"Module"})),Zd="all",qd="create",Yd="delete",_d="retrieve",Vd="update",vn=s.z.enum([Zd,qd,Yd,_d,Vd]);let le=class extends ye.createTyped("sy"){},$=class extends le.sub("validation"){};class Ct extends $.sub("path"){path;error;static encodedSchema=s.z.object({path:s.z.string().array(),error:ye.payloadZ});constructor(e,t){const n=O.toArray(e);super(`${n.join(".")}: ${t.message}`),this.path=n.flatMap(a=>a.split(".")),this.error=t}static decode(e){const t=Ct.encodedSchema.parse(JSON.parse(e.data));return new Ct(t.path,ye.decode(t.error))}}class gr extends le.sub("auth"){}class Tn extends gr.sub("invalid_token"){}class On extends gr.sub("expired_token"){}class W extends le.sub("unexpected"){constructor(e){super(`
|
|
16
|
-
Unexpected error encountered:
|
|
17
|
-
|
|
18
|
-
${e}
|
|
19
|
-
|
|
20
|
-
Please report this to the Synnax team.
|
|
21
|
-
`)}}class je extends le.sub("query"){}class st extends je.sub("not_found"){}class mr extends je.sub("multiple_results"){}class Ks extends le.sub("route"){path;constructor(e,t){super(e),this.path=t}}class Sn extends le.sub("control"){}class Js extends Sn.sub("unauthorized"){}class Hd extends le.sub("disconnected"){constructor(e="Operation failed because no cluster is connected."){super(e)}}class Rv extends le.sub("contiguity"){}const Wd=r=>r.type.startsWith(le.TYPE)?r.type.startsWith($.TYPE)?r.type===Ct.TYPE?Ct.decode(r):new $(r.data):r.type.startsWith(gr.TYPE)?r.type.startsWith(Tn.TYPE)?new Tn(r.data):r.type.startsWith(On.TYPE)?new On(r.data):new gr(r.data):r.type.startsWith(W.TYPE)?new W(r.data):r.type.startsWith(je.TYPE)?r.type.startsWith(st.TYPE)?new st(r.data):r.type.startsWith(mr.TYPE)?new mr(r.data):new je(r.data):r.type.startsWith(Sn.TYPE)?r.type.startsWith(Js.TYPE)?new Js(r.data):new Sn(r.data):r.type.startsWith(Ks.TYPE)?new Ks(r.data,r.data):new W(r.data):null,Gd=()=>{throw new ye.NotImplemented};ye.register({encode:Gd,decode:Wd});const Kd=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Ce?[t,new Ce({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class Li{key;name;constructor(e,t){this.key=t,this.name=e}get ontologyID(){return Jd(this.key)}}const Jd=r=>({type:"group",key:r}),Ar=s.z.uuid(),ts=s.z.string(),Mi=s.z.object({key:Ar,name:ts}),Pi="builtin",Xd="cluster",Qd="node",kr=s.z.enum(["label","log","allow_all","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","table"]),ef=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:kr.parse(e),key:t??""}}),U=s.z.object({type:kr,key:s.z.string()}).or(ef),tf={type:Pi,key:"root"},rs=r=>`${r.type}:${r.key}`,rf=(r,e)=>r.type===e.type&&r.key===e.key,Di=r=>{const e=O.toArray(r);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:t})=>t):e.map(t=>U.parse(t))},Bi=s.z.object({id:U,name:s.z.string(),data:ge.unknownZ.optional().nullable()}).transform(r=>({key:rs(r.id),...r})),nf=r=>r==="to"?"from":"to",sf=s.z.object({from:U,type:s.z.string(),to:U}).or(s.z.string().transform(r=>{const[e,t,n]=r.split("->");return{from:U.parse(e),type:t,to:U.parse(n)}})),af="parent",of=(r,e)=>!(e.type!=null&&e.type!==r.type||e.from?.type!=null&&e.from.type!==r.from.type||e.to?.type!=null&&e.to.type!==r.to.type||e.from?.key!=null&&e.from.key!==r.from.key||e.to?.key!=null&&e.to.key!==r.to.key),lf=s.z.object({group:Mi}),cf=s.z.object({parent:U,key:Ar.optional(),name:ts}),uf=s.z.object({key:Ar,name:ts}),hf=s.z.object({keys:s.z.array(Ar)});let df=class dr{static CREATE_ENDPOINT="/ontology/create-group";static RENAME_ENDPOINT="/ontology/rename-group";static DELETE_ENDPOINT="/ontology/delete-group";client;constructor(e){this.client=e}async create(e,t,n){return(await g(this.client,dr.CREATE_ENDPOINT,{parent:e,name:t,key:n},cf,lf)).group}async rename(e,t){await g(this.client,dr.RENAME_ENDPOINT,{key:e,name:t},uf,s.z.object({}))}async delete(e){await g(this.client,dr.DELETE_ENDPOINT,{keys:e},hf,s.z.object({}))}},ff=class{creator;constructor(r){this.creator=new df(r)}async create(r,e,t){return this.sugar(await this.creator.create(r,e,t))}async rename(r,e){return await this.creator.rename(r,e)}async delete(...r){return await this.creator.delete(r)}sugar(r){return new Li(r.name,r.key)}};const pf="/ontology/add-children",yf="/ontology/remove-children",gf="/ontology/move-children",Xs=s.z.object({id:U,children:U.array()}),mf=s.z.object({from:U,to:U,children:U.array()}),Vr=s.z.object({});let wf=class{client;constructor(r){this.client=r}async addChildren(r,...e){await g(this.client,pf,{id:r,children:e},Xs,Vr)}async removeChildren(r,...e){await g(this.client,yf,{id:r,children:e},Xs,Vr)}async moveChildren(r,e,...t){await g(this.client,gf,{from:r,to:e,children:t},mf,Vr)}};const bf="/ontology/retrieve",vf=s.z.object({ids:U.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:kr.array().optional()}),Tf=s.z.object({resources:Bi.array()});let $i=class{type="ontology";groups;client;writer;framer;constructor(r,e){this.client=r,this.writer=new wf(r),this.groups=new ff(r),this.framer=e}async retrieve(r,e){if(!Array.isArray(r)&&typeof r=="object"&&!("key"in r))return this.execRetrieve(r);const t=Di(r),n=await this.execRetrieve({ids:t,...e});if(Array.isArray(r))return n;if(n.length===0)throw new je(`No resource found with ID ${Fd.naturalLanguageJoin(t.map(a=>rs(a)))}`);return n[0]}async retrieveChildren(r,e){return await this.execRetrieve({ids:O.toArray(r),children:!0,...e})}async retrieveParents(r,e){return await this.execRetrieve({ids:O.toArray(r),parents:!0,...e})}async addChildren(r,...e){return await this.writer.addChildren(r,...e)}async removeChildren(r,...e){return await this.writer.removeChildren(r,...e)}async moveChildren(r,e,...t){return await this.writer.moveChildren(r,e,...t)}async execRetrieve(r){const{resources:e}=await g(this.client,bf,r,vf,Tf);return e}};const Of="sy_ontology_resource_set",Sf="sy_ontology_resource_delete",zf="sy_ontology_relationship_set",Ef="sy_ontology_relationship_delete",Nf=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:Pi,CLUSTER_TYPE:Xd,Client:$i,NODE_TYPE:Qd,PARENT_OF_RELATIONSHIP_TYPE:af,RELATIONSHIP_DELETE_CHANNEL_NAME:Ef,RELATIONSHIP_SET_CHANNEL_NAME:zf,RESOURCE_DELETE_CHANNEL_NAME:Sf,RESOURCE_SET_CHANNEL_NAME:Of,ROOT_ID:tf,idToString:rs,idZ:U,idsEqual:rf,matchRelationship:of,oppositeRelationshipDirection:nf,parseIDs:Di,relationshipZ:sf,resourceTypeZ:kr,resourceZ:Bi},Symbol.toStringTag,{value:"Module"})),F=r=>s.z.union([s.z.union([s.z.null(),s.z.undefined()]).transform(()=>[]),r.array()]),qt=s.z.uuid(),ns=s.z.object({key:qt,subjects:F(U),objects:F(U),actions:F(vn)}),Af=s.z.object({key:qt.optional(),subjects:U.array().or(U),objects:U.array().or(U),actions:vn.array().or(vn)}),kf=s.z.object({keys:qt.array().optional(),subjects:U.array().optional()}),xf=s.z.object({key:qt}).transform(({key:r})=>({keys:[r]})),If=s.z.union([s.z.object({for:U}).transform(({for:r})=>({subjects:[r]})),s.z.object({for:U.array()}).transform(({for:r})=>({subjects:r})),kf]),Cf=s.z.union([xf,If]),jf=s.z.object({policies:F(ns)}),Rf=s.z.object({policies:ns.partial({key:!0}).array()}),Uf=s.z.object({policies:ns.array()}),Lf=s.z.object({keys:qt.array()}),Mf=s.z.object({}),Pf="/access/policy/retrieve",Df="/access/policy/create",Bf="/access/policy/delete";let $f=class{client;constructor(r){this.client=r}async create(r){const e=Array.isArray(r),t=Af.array().parse(O.toArray(r)).map(a=>({objects:O.toArray(a.objects),actions:O.toArray(a.actions),subjects:O.toArray(a.subjects)})),n=await g(this.client,Df,{policies:t},Rf,Uf);return e?n.policies:n.policies[0]}async retrieve(r){const e="key"in r,t=await g(this.client,Pf,r,Cf,jf);return e?t.policies[0]:t.policies}async delete(r){await g(this.client,Bf,{keys:O.toArray(r)},Lf,Mf)}},Ff=class{policy;constructor(r){this.policy=new $f(r)}};const D=s.z.number(),pe=s.z.string(),dt=s.z.object({name:pe,key:D,dataType:N.z,leaseholder:s.z.number(),index:D,isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional(),expression:s.z.string().default(""),requires:F(D)}),Fi=dt.extend({key:D.optional(),leaseholder:s.z.number().optional(),index:D.optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1),expression:s.z.string().optional().default(""),requires:F(D).optional().default([])}),Zf=Nr.statusZ(),Fe=s.z.union([At.toArray(D),At.toArray(pe),At.toArray(dt).transform(r=>r.map(e=>e.key))]),qf=new Error("request for lock canceled");var Yf=function(r,e,t,n){function a(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function l(d){try{u(n.next(d))}catch(h){o(h)}}function c(d){try{u(n.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):a(d.value).then(l,c)}u((n=n.apply(r,e||[])).next())})};class _f{constructor(e,t=qf){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,a)=>{const i={resolve:n,reject:a,weight:e,priority:t},o=Zi(this._queue,l=>t<=l.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return Yf(this,arguments,void 0,function*(t,n=1,a=0){const[i,o]=yield this.acquire(n,a);try{return yield t(i)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Vf(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const n=this._weightedWaiters[t-1];if(!n)continue;const a=n.findIndex(i=>i.priority<=e);(a===-1?n:n.splice(0,a)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function Vf(r,e){const t=Zi(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Zi(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var Hf=function(r,e,t,n){function a(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function l(d){try{u(n.next(d))}catch(h){o(h)}}function c(d){try{u(n.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):a(d.value).then(l,c)}u((n=n.apply(r,e||[])).next())})};class Wf{constructor(e){this._semaphore=new _f(1,e)}acquire(){return Hf(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const Gf=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let a=O.toArray(r);const i=a[0],o=typeof i;let l;return o==="string"&&t&&!isNaN(parseInt(i))&&"number"in e?(l=e.number,a=a.map(c=>parseInt(c))):l=e[o],{single:n,variant:l,normalized:a,actual:r}},ft=(r,e,t,n)=>{if(n){if(t.length===0)throw new st(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new mr(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Kf=s.z.object({leaseholder:s.z.number().optional(),keys:D.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),rangeKey:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),dataTypes:N.z.array().optional(),notDataTypes:N.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional(),calculated:s.z.boolean().optional()}),Jf=s.z.object({channels:F(dt)}),ee=r=>(Array.isArray(r)&&r.length>0&&typeof r[0]=="object"?r=r.map(e=>e.key):typeof r=="object"&&"key"in r&&(r=[r.key]),Gf(r,{number:"keys",string:"names"}));class Yt{static ENDPOINT="/channel/retrieve";client;constructor(e){this.client=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const n=ee(e),{variant:a}=n;let{normalized:i}=n;return a==="keys"&&i.indexOf(0)!==-1&&(i=i.filter(o=>o!==0)),i.length===0?[]:await this.execute({[a]:i,...t})}async execute(e){const[t,n]=await this.client.send(Yt.ENDPOINT,e,Kf,Jf);if(n!=null)throw n;return t.channels}}class ss{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n}=ee(e),a=[],i=[];if(n.forEach(l=>{const c=this.get(l);c!=null?a.push(...c):i.push(l)}),i.length===0)return a;const o=await this.wrapped.retrieve(i,t);return this.set(o),a.concat(o)}delete(e){const{variant:t,normalized:n}=ee(e);t==="names"?n.forEach(a=>{const i=this.namesToKeys.get(a);i!=null&&(i.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(a))}):n.forEach(a=>{const i=this.cache.get(a);i!=null&&(this.cache.delete(a),this.namesToKeys.delete(i.name))})}rename(e,t){e.forEach((n,a)=>{const i=t[a],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const l=this.namesToKeys.get(o.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(o.name)),o.name=i,this.cache.set(n,o);const c=this.namesToKeys.get(i);c==null?this.namesToKeys.set(i,new Set([n])):c.add(n)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const n=this.namesToKeys.get(t.name);n==null?this.namesToKeys.set(t.name,new Set([t.key])):n.add(t.key)})}get(e){if(typeof e=="number"){const a=this.cache.get(e);return a==null?void 0:[a]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(a=>{const i=this.cache.get(a);i!=null&&n.push(i)}),n.length!==0)return n}}class qi{mu=new Wf;requests=new Map;wrapped;debouncedRun;constructor(e,t){this.wrapped=e,this.debouncedRun=Uh(()=>{this.run()},t)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:t,variant:n}=ee(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,i)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:i}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(a=>e.add(a)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,a)=>n.resolve(t.filter(i=>a.includes(i.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const Yi=async(r,e)=>{const{normalized:t}=ee(e),n=await r.retrieve(t),a=[];if(t.forEach(i=>{n.find(o=>o.name===i||o.key===i)==null&&a.push(i)}),a.length>0)throw new je(`Could not find channels: ${JSON.stringify(a)}`);return n},Xf="sy_channel_set",Qf="sy_channel_delete";class _i{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;requires;constructor({dataType:e,name:t,leaseholder:n=0,key:a=0,isIndex:i=!1,index:o=0,internal:l=!1,virtual:c=!1,frameClient:u,alias:d,expression:h="",requires:b=[]}){this.key=a,this.name=t,this.dataType=new N(e),this.leaseholder=n,this.index=o,this.isIndex=i,this.internal=l,this.alias=d,this.virtual=c,this.expression=h,this.requires=b??[],this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new $("cannot read from a channel that has not been created");return this._frameClient}get payload(){return dt.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,expression:this.expression,requires:this.requires})}get isCalculated(){return wr(this.payload)}get ontologyID(){return Wi(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const ep="sy_calculation_status",tp="/channel/retrieve-group",rp=s.z.object({}),np=s.z.object({group:Mi});let Vi=class{type="channel";frameClient;client;retriever;writer;constructor(r,e,t,n){this.frameClient=r,this.retriever=e,this.client=t,this.writer=n}async create(r,e={}){const{retrieveIfNameExists:t=!1}=e,n=!Array.isArray(r);let a=O.toArray(r),i=[];if(t){const o=await this.retriever.retrieve(a.map(c=>c.name)),l=new Set(o.map(c=>c.name));a=a.filter(c=>!l.has(c.name)),i=this.sugar(o)}return i=i.concat(this.sugar(await this.writer.create(a))),n?i[0]:i}async retrieve(r,e){if(typeof r=="object"&&!Array.isArray(r))return this.sugar(await this.retriever.retrieve(r));const t=!Array.isArray(r),n=this.sugar(await this.retriever.retrieve(r,e));return ft("channel",r,n,t),t?n[0]:n}async delete(r){const{normalized:e,variant:t}=ee(r);return t==="keys"?await this.writer.delete({keys:e}):await this.writer.delete({names:e})}async rename(r,e){return await this.writer.rename(O.toArray(r),O.toArray(e))}createDebouncedBatchRetriever(r=10){return new ss(new qi(new Yt(this.client),r))}sugar(r){const{frameClient:e}=this;return r.map(t=>new _i({...t,frameClient:e}))}async retrieveGroup(){const r=await g(this.client,tp,{},rp,np);return new Li(r.group.name,r.group.key)}};const wr=({virtual:r,expression:e})=>r&&e!=="",Hi=async(r,e)=>{if(!wr(e))return e.index;for(const t of e.requires){const n=await r(t);if(n==null)return null;if(!n.virtual)return n.index}for(const t of e.requires){const n=await r(t);if(n==null)return null;if(wr(n)){const a=await Hi(r,n);if(a!=null)return a}}return null},Wi=r=>({type:"channel",key:r.toString()}),sp=s.z.object({channels:Fi.array()}),ap=s.z.object({channels:dt.array()}),ip=s.z.object({keys:D.array().optional(),names:pe.array().optional()}),op=s.z.object({}),lp=s.z.object({keys:D.array(),names:pe.array()}),cp=s.z.object({}),up="/channel/create",hp="/channel/delete",dp="/channel/rename";let Gi=class{client;cache;constructor(r,e){this.client=r,this.cache=e}async create(r){const{channels:e}=await g(this.client,up,{channels:r.map(t=>({...t,dataType:t.dataType}))},sp,ap);return this.cache.set(e),e}async delete(r){await g(this.client,hp,r,ip,op),r.keys!=null&&this.cache.delete(r.keys),r.names!=null&&this.cache.delete(r.names)}async rename(r,e){await g(this.client,dp,{keys:r,names:e},lp,cp),this.cache.rename(r,e)}};const fp=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:ep,CacheRetriever:ss,Channel:_i,Client:Vi,ClusterRetriever:Yt,DELETE_CHANNEL_NAME:Qf,DebouncedBatchRetriever:qi,SET_CHANNEL_NAME:Xf,Writer:Gi,analyzeParams:ee,calculationStatusZ:Zf,isCalculated:wr,keyZ:D,nameZ:pe,newZ:Fi,ontologyID:Wi,paramsZ:Fe,payloadZ:dt,resolveCalculatedIndex:Hi,retrieveRequired:Yi},Symbol.toStringTag,{value:"Module"})),Ze=s.z.uuid(),xr=s.z.object({key:Ze,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),pp=xr.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),yp=s.z.object({keys:Ze.array().optional(),usernames:s.z.string().array().optional()}),gp=s.z.object({key:Ze}).transform(({key:r})=>({keys:[r]})),mp=s.z.object({username:s.z.string()}).transform(({username:r})=>({usernames:[r]})),wp=s.z.object({usernames:s.z.string().array()}).transform(({usernames:r})=>({usernames:r})),bp=s.z.union([gp,mp,wp,yp]),vp=s.z.object({users:F(xr)}),Tp=s.z.object({users:pp.array()}),Op=s.z.object({users:xr.array()}),Sp=s.z.object({key:Ze,username:s.z.string().min(1)}),zp=s.z.object({}),Ep=s.z.object({key:Ze,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Np=s.z.object({}),Ap=s.z.object({keys:Ze.array()}),kp=s.z.object({}),xp="/user/retrieve",Ip="/user/create",Cp="/user/change-username",jp="/user/rename",Rp="/user/delete";let Up=class{client;constructor(r){this.client=r}async create(r){const e=Array.isArray(r),t=await g(this.client,Ip,{users:O.toArray(r)},Tp,Op);return e?t.users:t.users[0]}async changeUsername(r,e){await g(this.client,Cp,{key:r,username:e},Sp,zp)}async retrieve(r){const e="key"in r||"username"in r,t=await g(this.client,xp,r,bp,vp);if(!e)return t.users;if(t.users.length===0){const n="key"in r?`key ${r.key}`:`username ${r.username}`;throw new st(`No user with ${n} found`)}if(t.users.length>1){const n="key"in r?`key ${r.key}`:`username ${r.username}`;throw new mr(`Multiple users found with ${n}`)}return t.users[0]}async rename(r,e,t){await g(this.client,jp,{key:r,firstName:e,lastName:t},Ep,Np)}async delete(r){await g(this.client,Rp,{keys:O.toArray(r)},Ap,kp)}};const Lp=s.z.object({username:s.z.string(),password:s.z.string()}),Mp=s.z.object({token:s.z.string(),user:xr}),Qs="/auth/login",Pp=3,Dp="/auth/change-password",Bp=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),$p=s.z.object({}),Fp=[Tn,On];let Zp=class{token;client;credentials;authenticating;authenticated;user;retryCount;constructor(r,e){this.client=r,this.authenticated=!1,this.credentials=e,this.retryCount=0}async changePassword(r){if(!this.authenticated)throw new Error("Not authenticated");await g(this.client,Dp,{username:this.credentials.username,password:this.credentials.password,newPassword:r},Bp,$p),this.credentials.password=r}middleware(){const r=async(e,t)=>{if(!this.authenticated&&!e.target.endsWith(Qs)){this.authenticating??=new Promise((o,l)=>{this.client.send(Qs,this.credentials,Lp,Mp).then(([c,u])=>{if(u!=null)return o(u);this.token=c?.token,this.user=c?.user,this.authenticated=!0,o(null)}).catch(l)});const i=await this.authenticating;if(i!=null)return[e,i]}e.params.Authorization=`Bearer ${this.token}`;const[n,a]=await t(e);return Fp.some(i=>i.matches(a))&&this.retryCount<Pp?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,r(e,t)):(this.retryCount=0,[n,a])};return r}};const qp=s.z.enum(["disconnected","connecting","connected","failed"]),Yp=s.z.object({status:qp,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string(),clientVersion:s.z.string(),clientServerCompatible:s.z.boolean(),nodeVersion:s.z.string().optional()}),_p=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),ea={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.44.1"},ta=(r,e,t)=>{const n=t?"cluster":"client";return`Synnax cluster node version ${r!=null?`${r} `:""}is too ${t?"old":"new"} for client version ${e}.
|
|
22
|
-
This may cause compatibility issues. We recommend updating the ${n}. For more information, see
|
|
23
|
-
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`};class br{static ENDPOINT="/connectivity/check";static DEFAULT=ea;_state;pollFrequency=z.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=Yp;versionWarned=!1;constructor(e,t=z.seconds(30),n,a){this._state={...ea},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=a,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){const e=this._state.status;try{const[t,n]=await this.client.send(br.ENDPOINT,{},s.z.object({}),_p);if(n!=null)throw n;const a=t.nodeVersion,i=this.clientVersion,o=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,o||(console.warn(ta(null,i,!0)),this.versionWarned=!0)):Gs.versionsEqual(i,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,o||(console.warn(ta(a,i,Gs.semVerNewer(i,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=t.clusterKey,this._state.nodeVersion=t.nodeVersion,this._state.clientVersion=this.clientVersion}catch(t){this._state.status="failed",this._state.error=t,this._state.message=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(t=>t(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}}const Vp=s.z.object({keys:D.array().optional(),bounds:L.z,names:pe.array().optional()}),Hp=s.z.object({}),Wp="/frame/delete";class Gp{client;constructor(e){this.client=e}async delete(e){await g(this.client,Wp,e,Vp,Hp)}}const ra=r=>{const e=O.toArray(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},na=(r,e)=>{const t=O.toArray(r);if(t.length===e.length)return;const n=ra(r);throw ra===null?new $("[Frame] - channel keys or names must be provided when constructing a frame."):new $(`[Frame] - ${n}s and series must be the same length.
|
|
24
|
-
Got ${t.length} ${n}s and ${e.length} series.`)};let K=class Je{columns=[];series=[];constructor(e=[],t=[]){if(e instanceof Je){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((n,a)=>this.push(a,...O.toArray(n)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const n=e;n.series??=[],n.keys??=[];const a=n.series.map(i=>Ki(i));na(n.keys,a),n.keys.forEach((i,o)=>this.push(i,a[o]))}else Object.entries(e).forEach(([n,a])=>{const i=parseInt(n);if(!isNaN(i))return this.push(i,...O.toArray(a));this.push(n,...O.toArray(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const n=O.toArray(t),a=O.toArray(e);na(a,n),n.forEach((i,o)=>this.push(a[o],i));return}throw new $(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
|
|
25
|
-
payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
|
|
26
|
-
name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new W("colType is not key");return this.columns??[]}get uniqueKeys(){return Ps.unique(this.keys)}get names(){if(this.colType==="key")throw new W("colType is not name");return this.columns??[]}get uniqueNames(){return Ps.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Ji(e)),keys:[...this.keys]}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return L.ZERO;const n=E.min(...this.series.map(i=>i.timeRange.start)),a=E.max(...this.series.map(i=>i.timeRange.end));return new L(n,a)}const t=this.get(e);return t==null?L.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new jh(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof Je){if(this.colType!==null&&e.colType!==this.colType)throw new $("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...t),typeof e=="string"&&this.colType==="key")throw new $("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new $("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new Je([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const t=new Je;return this.forEach((n,a,i)=>t.push(...e(n,a,i))),t}forEach(e){this.columns.forEach((t,n)=>{const a=this.series[n];e(t,a,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(a=>{n[a]=this.get(a).at(e,t)}),n}filter(e){const t=new Je;return this.columns.forEach((n,a)=>{const i=this.series[a];e(n,i,a)&&t.push(n,i)}),t}get byteLength(){return new nt(this.series.reduce((e,t)=>e.add(t.byteLength),nt.ZERO))}get digest(){const e={};return this.keys.forEach((t,n)=>{const a=this.series[n].digest;t in e?e[t].push(a):e[t]=[a]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}toString(){let e=`Frame{
|
|
27
|
-
`;return this.uniqueColumns.forEach(t=>{e+=` ${t}: ${this.get(t).series.map(n=>n.toString()).join(",")}
|
|
28
|
-
`}),e+="}",e}};const Ir=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),Ae.crudeZ.array().optional().default([])])}),Ki=r=>{const{dataType:e,data:t,timeRange:n,alignment:a}=r;return new Ae({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:a})},Ji=r=>({timeRange:r.timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});var at=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.SetAuthority=3]="SetAuthority",r))(at||{}),jt=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(jt||{});const Kp=new z(-1);class zn extends le.sub("writer_closed"){constructor(){super("WriterClosed")}}const Jp=s.z.enum(jt).or(s.z.enum(["persist","stream","persistStream"]).transform(r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),Xi=s.z.object({start:E.z.optional(),controlSubject:X.subjectZ.optional(),authorities:s.z.union([X.authorityZ.transform(r=>[r]),X.authorityZ.array()]).default([X.ABSOLUTE_AUTHORITY]),mode:Jp.default(1),errOnUnauthorized:s.z.boolean().default(!1),enableAutoCommit:s.z.boolean().default(!1),autoIndexPersistInterval:z.z.default(z.SECOND),useExperimentalCodec:s.z.boolean().default(!1)}),Xp=Xi.extend({keys:D.array().optional()}),sa=Xi.extend({channels:Fe}),Qi=sa.or(Fe.transform(r=>sa.parse({channels:r,start:E.now()}))),Qp=s.z.object({command:s.z.enum(at),config:Xp.optional(),frame:Ir.optional(),buffer:s.z.instanceof(Uint8Array).optional()}),ey=s.z.object({command:s.z.enum(at),end:E.z,err:ye.payloadZ.optional()}),ty=s.z.tuple([s.z.union([s.z.record(D.or(pe),X.authorityZ),D.or(pe),X.authorityZ]),X.authorityZ.optional()]).transform(([r,e])=>{if(X.authorityZ.safeParse(r).success)return{keys:[],authorities:[r]};if(D.or(pe).safeParse(r).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[r],authorities:[e]}}const t=r;return{keys:Object.keys(t),authorities:Object.values(t)}});let eo=class En{static ENDPOINT="/frame/write";stream;adapter;closeErr=null;constructor(e,t){this.stream=e,this.adapter=t}static async _open(e,t,n){const a=Qi.parse(n),i=await is.open(e,a.channels);a.useExperimentalCodec&&(t=t.withCodec(new oy(i.codec)));const o=await t.stream(En.ENDPOINT,Qp,ey),l=new En(o,i);return await l.execute({command:0,config:{...a,keys:i.keys}}),l}async write(e,t){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const n=await this.adapter.adapt(e,t);this.stream.send({command:1,frame:n.toPayload()})}async setAuthority(e,t){if(this.closeErr!=null)throw this.closeErr;const n=ty.parse([e,t]),a={keys:await this.adapter.adaptParams(n.keys),authorities:n.authorities};await this.execute({command:3,config:a})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),E.ZERO):(await this.execute({command:2})).end}async close(){await this.closeInternal(null)}async closeInternal(e){if(this.closeErr!=null)throw this.closeErr;for(this.closeErr=e,this.stream.closeSend();;){if(this.closeErr!=null){if(zn.matches(this.closeErr))return null;throw this.closeErr}const[t,n]=await this.stream.receive();n!=null?this.closeErr=te.matches(n)?new zn:n:this.closeErr=ye.decode(t?.err)}}async execute(e){const t=this.stream.send(e);for(t!=null&&await this.closeInternal(t);;){const[n,a]=await this.stream.receive();a!=null&&await this.closeInternal(a);const i=ye.decode(n?.err);if(i!=null&&await this.closeInternal(i),n?.command==e.command)return n}}};const aa=r=>r.data.byteLength/r.dataType.density.valueOf(),ry=r=>{const{keys:e,series:t}=r;e.forEach((n,a)=>{t[a].key=n}),t.sort((n,a)=>n.key-a.key),e.sort((n,a)=>n-a),t.forEach(n=>delete n.key)},ia=5,oa=4,la=3,ca=2,ua=1,ha=0,ne=N.TIMESTAMP.density.valueOf(),Te=8,Oe=4,Hr=4,Wr=4,ny=1;class to{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],t=[]){(e.length>0||t.length>0)&&this.update(e,t)}update(e,t){this.seqNum++;const n={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((a,i)=>{const o=t[i];n.keyDataTypes.set(a,o),o.isVariable&&(n.hasVariableDataTypes=!0)}),n.keys.sort(),this.states.set(this.seqNum,n),this.currState=n}throwIfNotUpdated(e){if(this.seqNum<1)throw new $(`
|
|
29
|
-
The codec has not been updated with a list of channels and data types.
|
|
30
|
-
Please call the update method before calling ${e}.
|
|
31
|
-
`)}encode(e,t=0){this.throwIfNotUpdated("encode");let n=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(n=e.toPayload()),ry(n);let a=-1,i,o,l,c=t+ny+Wr,u=!this.currState?.hasVariableDataTypes,d=!0,h=!0,b=!0,S=!0,R=!0;n.keys.length!==this.currState?.keys.length&&(b=!1,c+=n.keys.length*Hr),n.series.forEach((M,re)=>{const Q=aa(M),mt=n.keys[re],Ue=this.currState?.keyDataTypes.get(mt);if(Ue==null)throw new $(`Channel ${mt} was not provided in the list of channels when opening the writer`);if(!Ue.equals(M.dataType))throw new $(`Series data type of ${M.dataType.toString()} does not match the data type of ${Ue.toString()} for channel ${mt}`);if(c+=M.data.byteLength,a===-1){a=Q,i=M.timeRange?.start,o=M.timeRange?.end,l=BigInt(M.alignment??0n);return}a!==Q&&(u=!1),(i?.valueOf()!==M.timeRange?.start.valueOf()||o?.valueOf()!==M.timeRange?.end.valueOf())&&(d=!1),l!==BigInt(M.alignment??0)&&(S=!1)}),h=d&&i==null&&o==null,R=S&&(l===void 0||l===0n),u?c+=Oe:c+=n.keys.length*Oe,h||(d?c+=ne*2:c+=n.keys.length*ne*2),R||(S?c+=Te:c+=n.keys.length*Te);const A=new Uint8Array(c),B=new DataView(A.buffer);let x=t;return A[x]=Number(R)<<ia|Number(S)<<oa|Number(u)<<la|Number(d)<<ca|Number(h)<<ua|Number(b)<<ha,x++,B.setUint32(x,this.seqNum,!0),x+=Wr,u&&(B.setUint32(x,a,!0),x+=Oe),d&&!h&&(B.setBigUint64(x,i?.valueOf()??0n,!0),B.setBigUint64(x,o?.valueOf()??0n,!0),x+=ne*2),S&&!R&&(B.setBigUint64(x,l??0n,!0),x+=Te),n.series.forEach((M,re)=>{if(b||(B.setUint32(x,n.keys[re],!0),x+=Hr),!u){let Q=M.data.byteLength;M.dataType.isVariable||(Q=aa(M)),B.setUint32(x,Q,!0),x+=Oe}A.set(new Uint8Array(M.data),x),x+=M.data.byteLength,!d&&!h&&(B.setBigUint64(x,M.timeRange?.start.valueOf()??0n,!0),B.setBigUint64(x,M.timeRange?.end.valueOf()??0n,!0),x+=ne*2),!S&&!R&&(B.setBigUint64(x,M.alignment??0n,!0),x+=Te)}),A}decode(e,t=0){this.throwIfNotUpdated("decode");const n=e instanceof Uint8Array?e:new Uint8Array(e),a={keys:[],series:[]};let i=t,o=0,l=0,c,u,d;const h=new DataView(n.buffer,n.byteOffset,n.byteLength),b=!!(n[i]>>ia&1),S=!!(n[i]>>oa&1),R=!!(n[i]>>la&1),A=!!(n[i]>>ca&1),B=!!(n[i]>>ua&1),x=!!(n[i]>>ha&1);i++;const M=h.getUint32(i,!0);i+=Wr;const re=this.states.get(M);if(re==null)return a;if(R){if(i+Oe>h.byteLength)return a;o=h.getUint32(i,!0),i+=Oe}if(A&&!B){if(i+ne>h.byteLength)return a;c=new E(h.getBigUint64(i,!0)),i+=ne,u=new E(h.getBigUint64(i,!0)),i+=ne}if(S&&!b){if(i+Te>h.byteLength)return a;d=h.getBigUint64(i,!0),i+=Te}return x&&(a.keys=[...re.keys]),re.keys.forEach((Q,mt)=>{if(!x){if(i>=h.byteLength||h.getUint32(i,!0)!==Q)return;i+=Hr,a.keys.push(Q)}const Ue=re.keyDataTypes.get(Q);if(l=0,R)l=o;else{if(i+Oe>h.byteLength)return;l=h.getUint32(i,!0),i+=Oe}let Xt=l;if(Ue.isVariable||(Xt*=Ue.density.valueOf()),i+Xt>h.byteLength){a.keys.splice(mt,1);return}const Le={dataType:Ue,data:n.slice(i,i+Xt).buffer};if(i+=Xt,!A&&!B){if(i+ne*2>h.byteLength)return;const yl=h.getBigUint64(i,!0);i+=ne;const gl=h.getBigUint64(i,!0);i+=ne,Le.timeRange=new L({start:yl,end:gl})}else B?Le.timeRange=new L({start:0n,end:0n}):Le.timeRange=new L({start:c?.valueOf()??0n,end:u?.valueOf()??0n});if(!S&&!b){if(i+Te>h.byteLength)return;d=h.getBigUint64(i,!0),i+=Te,Le.alignment=d}else b?Le.alignment=0n:Le.alignment=d;a.series.push(Le)}),a}}const as=254,sy=new Uint8Array([as]),ay=255,iy=new Uint8Array([ay]),ro="application/sy-framer";class oy{contentType=ro;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=$e.JSON_CODEC}encode(e){const t=e;if(t.type=="close"||t.payload?.command!=at.Write){const a=this.lowPerfCodec.encode(t),i=new Uint8Array({length:a.byteLength+1});return i.set(sy,0),i.set(new Uint8Array(a),1),i}const n=this.base.encode(t.payload?.frame,1);return n.set(iy,0),n}decode(e,t){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===as)return this.lowPerfCodec.decode(e.slice(1),t);const n={type:"data"},a=this.base.decode(e,1);return n.payload={command:at.Write,frame:a},n}}class ly{contentType=ro;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=$e.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,t){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===as?this.lowPerfCodec.decode(e.slice(1),t):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class Cr{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new to}static async open(e,t){const n=new Cr(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=ee(e),a=await this.retriever.retrieve(n),i=a.map(l=>l.key);if(Ds.uniqueUnorderedPrimitiveArrays(this.keys,i)===Ds.EQUAL)return!1;if(this.codec.update(i,a.map(l=>l.dataType)),t==="keys")return this.adapter=null,this.keys=n,!0;const o=new Map;return this.adapter=o,n.forEach(l=>{const c=a.find(u=>u.name===l);if(c==null)throw new Error(`Channel ${l} not found`);o.set(c.key,c.name)}),this.keys=Array.from(this.adapter.keys()),!0}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,a)=>{if(typeof n=="number"){const i=t.get(n);if(i==null)throw new Error(`Channel ${n} not found`);return[i,a]}return[n,a]})}}class is{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new to}static async open(e,t){const n=new is(e);return await n.update(t),n}async adaptParams(e){const t=Fe.parse(e);return await Promise.all(t.map(async n=>await this.adaptToKey(n)))}async update(e){const t=await Yi(this.retriever,e),n=t.map(c=>c.key),a=new Set(this.keys),i=new Set(n),o=!i.isSubsetOf(a),l=!a.isSubsetOf(i);return o||l?(this.adapter=new Map(t.map(c=>[c.name,c.key])),this.keys=n,this.codec.update(this.keys,t.map(c=>c.dataType)),!0):!1}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new $(`
|
|
32
|
-
Received a single channel name or key but no series.
|
|
33
|
-
`);if(Array.isArray(t)){if(t.some(c=>c instanceof Ae||Array.isArray(c)))throw new $(`
|
|
34
|
-
Received a single channel name or key but multiple series.
|
|
35
|
-
`);t=t}const o=await this.fetchChannel(e),l=new Ae({data:t,dataType:o.dataType});return new K(o.key,l)}if(Array.isArray(e)){if(t==null)throw new $(`
|
|
36
|
-
Received an array of channel names or keys but no series.
|
|
37
|
-
`);if(!Array.isArray(t))throw new $(`
|
|
38
|
-
Received an array of channel names or keys but no array of series.
|
|
39
|
-
`);const o=[],l=[];for(let c=0;c<e.length;c++){const u=await this.fetchChannel(e[c]);if(c>=t.length)throw new $(`
|
|
40
|
-
Received an array of channel names or keys but not enough series.
|
|
41
|
-
`);const d=new Ae({data:t[c],dataType:u.dataType});o.push(u.key),l.push(d)}return new K(o,l)}if(e instanceof K||e instanceof Map){const o=new K(e);if(this.adapter==null)return o;const l=o.columns.map(c=>{const u=typeof c=="string"?this.adapter?.get(c):c;if(u==null)throw new $(`
|
|
42
|
-
Channel ${c} was not provided in the list of channels when opening the writer
|
|
43
|
-
`);return u});return new K(l,o.series)}const n=[],a=[],i=Object.entries(e);for(let o=0;o<i.length;o++){const[l,c]=i[o],u=await this.fetchChannel(l),d=new Ae({data:c,dataType:u.dataType});n.push(u.key),a.push(d)}return new K(n,a)}}class no{name;stream;constructor(e,t){this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
|
|
44
|
-
Please report this error to the Synnax team.`),t!=null){if(te.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const vr=new z(-1);var os=(r=>(r[r.Open=0]="Open",r[r.Next=1]="Next",r[r.Prev=2]="Prev",r[r.SeekFirst=3]="SeekFirst",r[r.SeekLast=4]="SeekLast",r[r.SeekLE=5]="SeekLE",r[r.SeekGE=6]="SeekGE",r[r.Valid=7]="Valid",r[r.Error=8]="Error",r))(os||{}),so=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(so||{});const cy=s.z.object({command:s.z.enum(os),span:z.z.optional(),bounds:L.z.optional(),stamp:E.z.optional(),keys:D.array().optional(),chunkSize:s.z.number().optional()}),uy=s.z.object({variant:s.z.enum(so),ack:s.z.boolean(),command:s.z.enum(os),error:ye.payloadZ.optional().nullable(),frame:Ir.optional()});class Rt{static ENDPOINT="/frame/iterate";stream;adapter;value;constructor(e,t){this.stream=new no("Iterator",e),this.value=new K,this.adapter=t}static async _open(e,t,n,a,i={}){const o=await Cr.open(n,t),l=await a.stream(Rt.ENDPOINT,cy,uy),c=new Rt(l,o);return await c.execute({command:0,keys:o.keys,bounds:new L(e),chunkSize:i.chunkSize??1e5}),c}async next(e=vr){return await this.execute({command:1,span:new z(e)})}async prev(e=vr){return await this.execute({command:2,span:new z(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new E(e)})}async seekGE(e){return await this.execute({command:6,stamp:new E(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new hy(this)}async execute(e){for(this.stream.send(e),this.value=new K;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new K(t.frame)))}}}class hy{iter;open=!1;constructor(e){this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const dy=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),fy=s.z.object({frame:Ir}),py="/frame/stream",da=s.z.object({channels:Fe,downsampleFactor:s.z.number().optional().default(1),useExperimentalCodec:s.z.boolean().optional().default(!1)}),ls=da.or(Fe.transform(r=>da.parse({channels:r}))),ao=(r,e)=>async t=>{const n=ls.parse(t),a=await Cr.open(r,n.channels);n.useExperimentalCodec&&(e=e.withCodec(new ly(a.codec)));const i=await e.stream(py,dy,fy),o=new yy(i,a);i.send({keys:a.keys,downsampleFactor:n.downsampleFactor??1});const[,l]=await i.receive();if(l!=null)throw l;return o},io=async(r,e,t)=>await ao(r,e)(t);class yy{stream;adapter;downsampleFactor;constructor(e,t){this.stream=new no("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(te.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new K((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e)&&this.stream.send({keys:this.adapter.keys,downsampleFactor:this.downsampleFactor})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class jr{wrapped_=null;breaker;opener;config;constructor(e,t,n={}){this.opener=e,this.config=ls.parse(t);const{maxRetries:a=5e3,baseInterval:i=z.seconds(1),scale:o=1}=n??{};this.breaker=new bi.Breaker({maxRetries:a,baseInterval:i,scale:o})}static async open(e,t,n){const a=new jr(e,t,n);return await a.runStreamer(),a}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=Fe.parse(e);try{await this.wrapped.update(e)}catch{return await this.runStreamer(),await this.update(e)}}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(te.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{const e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(te.matches(e))throw e;return await this.runStreamer(),await this.read()}}close(){this.wrapped.close()}get keys(){return this.wrapped.keys}[Symbol.asyncIterator](){return this}}class oo extends $h.Observer{streamer;closePromise;constructor(e,t){super(t),this.streamer=e,this.closePromise=this.stream()}async update(e){await this.streamer.update(e)}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}const gy=r=>({type:"framer",key:r.toString()});let lo=class{streamClient;retriever;deleter;constructor(r,e,t){this.streamClient=r,this.retriever=t,this.deleter=new Gp(e)}async openIterator(r,e,t){return await Rt._open(r,e,this.retriever,this.streamClient,t)}async openWriter(r){return await eo._open(this.retriever,this.streamClient,r)}async openStreamer(r){return await io(this.retriever,this.streamClient,r)}async write(r,e,t){if(t==null){const a=e,i=await this.openWriter({start:r,channels:Object.keys(a),mode:jt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});return await i.write(a),await i.close()}const n=await this.openWriter({start:r,channels:e,mode:jt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});await n.write(e,t),await n.close()}async read(r,e){const{single:t}=ee(e),n=await this.readFrame(r,e);return t?n.get(e):n}async readFrame(r,e){const t=await this.openIterator(r,e),n=new K;try{for await(const a of t)n.push(a)}finally{await t.close()}return n}async readLatest(r,e=1){const{single:t}=ee(r),n=await this.readLatestNFrame(r,e);return t?n.get(r):n}async readLatestNFrame(r,e){const t=await this.openIterator(L.MAX,r,{chunkSize:e}),n=new K;if(e>0)try{await t.seekLast(),await t.prev(vr),n.push(t.value)}finally{await t.close()}return n}async delete(r,e){const{normalized:t,variant:n}=ee(r);return n==="keys"?await this.deleter.delete({keys:t,bounds:e}):await this.deleter.delete({names:t,bounds:e})}};const my=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Kp,AUTO_SPAN:vr,Client:lo,Frame:K,HardenedStreamer:jr,Iterator:Rt,ObservableStreamer:oo,Writer:eo,WriterClosedError:zn,WriterCommand:at,WriterMode:jt,createStreamOpener:ao,frameZ:Ir,ontologyID:gy,openStreamer:io,seriesFromPayload:Ki,seriesToPayload:Ji,streamerConfigZ:ls,writerConfigZ:Qi},Symbol.toStringTag,{value:"Module"})),wy=X.ABSOLUTE_AUTHORITY,by=X.ZERO_AUTHORITY,vy=X.stateZ(s.z.number()),Ty=r=>r.to==null?`${r.from?.resource} - ${r.from?.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`,Oy=s.z.object({transfers:s.z.array(X.transferZ(D))});class co extends oo{states;codec;constructor(e){super(e,t=>{const n=this.codec.decode(t.series[0].buffer,Oy);return this.merge(n),[n.transfers,!0]}),this.states=new Map,this.codec=new $e.JSONCodec}subjects(){const e=new Map;return this.states.forEach(t=>e.set(t.subject.key,t.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(t=>{t.from==null&&t.to==null&&console.warn("Invalid transfer: ",t),t.to==null?this.states.delete(t.from.resource):this.states.set(t.to.resource,t.to)})}}const uo="sy_node_1_control";let ho=class{framer;constructor(r){this.framer=r}async openStateTracker(){const r=await jr.open(async e=>await this.framer.openStreamer(e),uo);return new co(r)}};const Sy=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:wy,CONTROL_STATE_CHANNEL_NAME:uo,Client:ho,StateTracker:co,ZERO_AUTHORITY:by,stateZ:vy,transferString:Ty},Symbol.toStringTag,{value:"Module"}));let zy=class{tasks;racks;devices;constructor(r,e,t){this.tasks=r,this.racks=e,this.devices=t}};const ce=s.z.uint32(),fo=Nr.statusZ(s.z.object({rack:ce})),Rr=s.z.object({key:ce,name:s.z.string(),status:At.nullToUndefined(fo)}),po=Rr.partial({key:!0}),yo=r=>r?$e.JSON_CODEC.decodeString(r,ge.unknownZ):{},pt=s.z.string(),go=Nr.statusZ(s.z.object({rack:ce,device:pt})),Ur=s.z.object({key:pt,rack:ce,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:ge.unknownZ.or(s.z.string().transform(yo)),status:At.nullToUndefined(go)}),mo=Ur.extend({properties:s.z.unknown().transform(r=>$e.JSON_CODEC.encodeString(r))}),Ey="sy_device_set",Ny="sy_device_delete",Ay="sy_device_status",ky="/hardware/device/retrieve",xy="/hardware/device/create",Iy="/hardware/device/delete",Cy=s.z.object({devices:mo.array()}),jy=s.z.object({devices:Ur.array()}),Ry=s.z.object({keys:pt.array()}),Uy=s.z.object({}),Ly=s.z.object({keys:pt.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional(),models:s.z.string().array().optional(),locations:s.z.string().array().optional(),racks:ce.array().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),My=s.z.object({devices:F(Ur)}),Py=s.z.object({key:pt,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),Dy=s.z.union([Py,Ly]);let wo=class{type="device";client;constructor(r){this.client=r}async retrieve(r){const e=typeof r=="object"&&"key"in r,t=await g(this.client,ky,r,Dy,My);ft("Device",r,t.devices,e);const n=t.devices;return e?n[0]:n}async create(r){const e=!Array.isArray(r),t=(await g(this.client,xy,{devices:O.toArray(r)},Cy,jy)).devices;return e?t[0]:t}async delete(r){await g(this.client,Iy,{keys:O.toArray(r)},Ry,Uy)}};const By=r=>({type:"device",key:r}),$y=Object.freeze(Object.defineProperty({__proto__:null,Client:wo,DELETE_CHANNEL_NAME:Ny,SET_CHANNEL_NAME:Ey,STATUS_CHANNEL_NAME:Ay,deviceZ:Ur,keyZ:pt,newZ:mo,ontologyID:By,statusZ:go},Symbol.toStringTag,{value:"Module"})),Fy="/hardware/rack/retrieve",Zy="/hardware/rack/create",qy="/hardware/rack/delete",Yy="sy_rack_status",_y="sy_rack_set",Vy="sy_rack_delete",Hy=s.z.object({keys:ce.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),embedded:s.z.boolean().optional(),hostIsNode:s.z.boolean().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),Wy=s.z.object({racks:F(Rr)}),Gy=s.z.union([s.z.object({key:ce,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:r,includeStatus:e})=>({names:[r],includeStatus:e}))]),Ky=Hy,Jy=s.z.union([Gy,Ky]),Xy=s.z.object({racks:po.array()}),Qy=s.z.object({racks:Rr.array()}),eg=s.z.object({keys:ce.array()}),tg=s.z.object({});let bo=class{type="rack";client;tasks;constructor(r,e){this.client=r,this.tasks=e}async delete(r){await g(this.client,qy,{keys:O.toArray(r)},eg,tg)}async create(r){const e=!Array.isArray(r),t=await g(this.client,Zy,{racks:O.toArray(r)},Xy,Qy),n=this.sugar(t.racks);return e?n[0]:n}async retrieve(r){const e="key"in r||"name"in r,t=await g(this.client,Fy,r,Jy,Wy),n=this.sugar(t.racks);return ft("Rack",r,n,e),e?n[0]:n}sugar(r){const e=!Array.isArray(r),t=O.toArray(r).map(({key:n,name:a,status:i})=>new vo(n,a,this.tasks,i));return e?t[0]:t}};class vo{key;name;status;tasks;constructor(e,t,n,a){this.key=e,this.name=t,this.tasks=n,this.status=a}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,t){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,t)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const rg=r=>({type:"rack",key:r.toString()}),ng=Object.freeze(Object.defineProperty({__proto__:null,Client:bo,DELETE_CHANNEL_NAME:Vy,Rack:vo,SET_CHANNEL_NAME:_y,STATUS_CHANNEL_NAME:Yy,keyZ:ce,newZ:po,ontologyID:rg,rackZ:Rr,statusZ:fo},Symbol.toStringTag,{value:"Module"})),me=r=>r?JSON.parse(r):{},we=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),To=r=>s.z.object({task:we,running:s.z.boolean(),data:r}),cs=r=>Nr.statusZ(To(r)),_t=(r={typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()})=>s.z.object({key:we,name:s.z.string(),type:r.typeSchema,internal:s.z.boolean().optional(),config:s.z.string().transform(yo).or(r.configSchema),status:cs(r.statusDataSchema).optional().nullable(),snapshot:s.z.boolean().optional()}),Oo=r=>_t(r).omit({key:!0}).extend({key:we.transform(e=>e.toString()).optional(),config:s.z.unknown().transform(e=>$e.JSON_CODEC.encodeString(e))}),sg=s.z.object({task:we,type:s.z.string(),key:s.z.string(),args:ge.unknownZ.or(s.z.string().transform(me)).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),ag=r=>Number(BigInt(r)>>32n),Nn="sy_task_status",An="sy_task_cmd",ig="sy_task_set",og="sy_task_delete",Me=new Error("Task not created"),So=async(r,e)=>{const t=await e.retrieveParents(us(r));return t.length===0?null:t[0]};class zo{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw Me;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw Me;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw Me;return this.rangeClient_}constructor({key:e,type:t,name:n,config:a,internal:i=!1,snapshot:o=!1,status:l},c,u,d,h){this.key=e,this.name=n,this.type=t,this.config=a,this.schemas=c??{typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()},this.internal=i,this.snapshot=o,this.status=l,this.frameClient_=u,this.ontologyClient_=d,this.rangeClient_=h}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return us(this.key)}async executeCommand(e,t){return await hs(this.frameClient,this.key,e,t)}async executeCommandSync(e,t,n){return await No(this.frameClient,this.key,e,t,this.name,this.schemas?.statusDataSchema,n)}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Me;return this.snapshot?await So(this.key,this.ontologyClient):null}}const lg=s.z.object({rack:ce.optional(),keys:we.array().optional(),names:s.z.string().array().optional(),types:s.z.string().array().optional(),includeStatus:s.z.boolean().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),cg=s.z.union([s.z.object({key:we,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:r,includeStatus:e})=>({names:[r],includeStatus:e}))]),ug=lg,hg=s.z.union([cg,ug]),dg=r=>s.z.object({tasks:F(_t(r))}),fg="/hardware/task/retrieve",pg="/hardware/task/create",yg="/hardware/task/delete",gg="/hardware/task/copy",mg=r=>s.z.object({tasks:Oo(r).array()}),wg=r=>s.z.object({tasks:_t(r).array()}),bg=s.z.object({keys:we.array()}),vg=s.z.object({}),Tg=s.z.object({key:we,name:s.z.string(),snapshot:s.z.boolean()}),Og=r=>s.z.object({task:_t(r)});let Eo=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(r,e,t,n){this.client=r,this.frameClient=e,this.ontologyClient=t,this.rangeClient=n}async create(r,e){const t=!Array.isArray(r),n=mg(e),a=wg(e),i=await g(this.client,pg,{tasks:O.toArray(r)},n,a),o=this.sugar(i.tasks,e);return t?o[0]:o}async delete(r){await g(this.client,yg,{keys:O.toArray(r)},bg,vg)}async retrieve({schemas:r,...e}){const t="key"in e||"name"in e,n=(await g(this.client,fg,e,hg,dg(r))).tasks,a=this.sugar(n,r);return ft("Task",e,a,t),t?a[0]:a}async copy(r,e,t){const n=Og(),a=await g(this.client,gg,{key:r,name:e,snapshot:t},Tg,n);return this.sugar(a.task)}async retrieveSnapshottedTo(r){if(this.ontologyClient==null)throw Me;return await So(r,this.ontologyClient)}sugar(r,e){const t=!Array.isArray(r),n=O.toArray(r).map(({key:a,name:i,type:o,config:l,status:c,internal:u,snapshot:d})=>new zo({key:a,name:i,type:o,config:l,internal:u,snapshot:d,status:c},e,this.frameClient,this.ontologyClient,this.rangeClient));return t?n[0]:n}async executeCommand(r,e,t){return await hs(this.frameClient,r,e,t)}async executeCommandSync(r,e,t,n,a,i=s.z.unknown()){const o=async()=>(await this.retrieve({key:r})).name;return await No(this.frameClient,r,e,t,a??o,i,n)}};const us=r=>({type:"task",key:r}),hs=async(r,e,t,n)=>{if(r==null)throw Me;const a=mh.create(),i=await r.openWriter(An);return await i.write(An,[{args:n,key:a,task:e,type:t}]),await i.close(),a},No=async(r,e,t,n,a,i,o)=>{if(r==null)throw Me;const l=await r.openStreamer(Nn),c=await hs(r,e,t,o),u=new z(n);let d;const h=new Promise((b,S)=>{d=setTimeout(()=>{(async()=>S(await Sg(t,a,u,e)))()},u.milliseconds)});try{for(;;){const b=await Promise.race([l.read(),h]),S=cs(i).parse(b.at(-1)[Nn]);if(S.key===c)return S}}finally{clearTimeout(d),l.close()}},Sg=async(r,e,t,n)=>{const a=zu.capitalize(r),i=t.toString();try{const o=typeof e=="string"?e:await e();return new Error(`${a} command to ${o} timed out after ${i}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${a} command to task with key ${n} timed out after ${i}`)}},zg=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:An,Client:Eo,DELETE_CHANNEL_NAME:og,SET_CHANNEL_NAME:ig,STATUS_CHANNEL_NAME:Nn,Task:zo,commandZ:sg,keyZ:we,newZ:Oo,ontologyID:us,rackKey:ag,statusDetailsZ:To,statusZ:cs,taskZ:_t},Symbol.toStringTag,{value:"Module"})),Re=s.z.uuid(),Vt=s.z.object({key:Re,name:s.z.string().min(1),color:s.z.string()}),Eg="labeled_by",Ng="sy_label_set",Ag="sy_label_delete",Ao=Vt.extend({key:Re.optional()}),kg=s.object({labels:Ao.array()}),xg=s.object({labels:Vt.array()}),Ig=s.object({keys:Re.array()}),ko=s.object({id:U,labels:Re.array(),replace:s.boolean().optional()}),Cg=ko.omit({replace:!0}),Gr=s.object({}),jg="/label/create",Rg="/label/delete",Ug="/label/set",Lg="/label/remove",Mg="/label/retrieve",Pg=s.object({keys:Re.array().optional(),for:U.optional(),searchTerm:s.string().optional(),offset:s.number().optional(),limit:s.number().optional()}),Dg=s.object({key:Re}).transform(({key:r})=>({keys:[r]})),Bg=s.union([Dg,Pg]),$g=s.object({labels:F(Vt)});let xo=class{type="label";client;constructor(r){this.client=r}async retrieve(r){const e="key"in r,t=await g(this.client,Mg,r,Bg,$g);return ft("Label",r,t.labels,e),e?t.labels[0]:t.labels}async label(r,e,t={}){await g(this.client,Ug,{id:r,labels:e,replace:t.replace},ko,Gr)}async remove(r,e){await g(this.client,Lg,{id:r,labels:e},Cg,Gr)}async create(r){const e=Array.isArray(r),t=await g(this.client,jg,{labels:O.toArray(r)},kg,xg);return e?t.labels:t.labels[0]}async delete(r){await g(this.client,Rg,{keys:O.toArray(r)},Ig,Gr)}};const Fg=r=>({type:"label",key:r}),Zg=Object.freeze(Object.defineProperty({__proto__:null,Client:xo,DELETE_CHANNEL_NAME:Ag,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:Eg,SET_CHANNEL_NAME:Ng,keyZ:Re,labelZ:Vt,newZ:Ao,ontologyID:Fg},Symbol.toStringTag,{value:"Module"})),_=s.z.uuid(),ds=s.z.string().min(1),Ht=s.z.object({key:_,name:ds,timeRange:L.z,color:s.z.string().optional(),labels:F(Vt),get parent(){return Ht.optional().nullable().transform(r=>r===void 0?null:r)}}),Io=Ht.omit({parent:!0,labels:!0}).partial({key:!0}),qg="sy_range_alias_set",Yg="sy_range_alias_delete",_g=s.z.object({range:_,aliases:s.z.string().array()}),Vg=s.z.object({aliases:s.z.record(s.z.string(),D)}),Hg=s.z.object({range:_,aliases:s.z.record(D.or(s.z.string()),s.z.string())}),Wg=s.z.unknown(),Gg=s.z.object({range:_,channels:D.array()}),Kg=s.z.unknown(),Jg=s.z.object({range:_}),Xg=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())});class Xe{static SET_ENDPOINT="/range/alias/set";static RESOLVE_ENDPOINT="/range/alias/resolve";static LIST_ENDPOINT="/range/alias/list";static DELETE_ENDPOINT="/range/alias/delete";frameClient;cache=new Map;client;rangeKey;constructor(e,t,n){this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",a={};if(n){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const l=this.cache.get(o);l!=null?a[o]=l:t.push(o)});if(t.length===0)return a;const i=await g(this.client,Xe.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},_g,Vg);return Object.entries(i.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?i.aliases[t[0]]:{...a,...i.aliases}}async set(e){await g(this.client,Xe.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Hg,Wg)}async list(){return(await g(this.client,Xe.LIST_ENDPOINT,{range:this.rangeKey},Jg,Xg)).aliases}async delete(e){await g(this.client,Xe.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Gg,Kg)}}const Qg=s.z.object({alias:s.z.string(),channel:D,range:_}),em="---",tm=r=>{const[e,t]=r.split(em);return{range:e,channel:Number(t)}},rm="sy_range_kv_set",nm="sy_range_kv_delete",fs=s.z.object({range:_,key:s.z.string(),value:s.z.string()}),sm=s.z.object({range:_,keys:s.z.string().array()}),am=s.z.object({pairs:F(fs)}),im=s.z.object({range:_,pairs:fs.array()}),om=s.z.object({range:_,keys:s.z.string().array()});class Be{static GET_ENDPOINT="/range/kv/get";static SET_ENDPOINT="/range/kv/set";static DELETE_ENDPOINT="/range/kv/delete";rangeKey;client;constructor(e,t){this.rangeKey=e,this.client=t}async get(e){const t=await g(this.client,Be.GET_ENDPOINT,{range:this.rangeKey,keys:O.toArray(e)},sm,am);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,t=""){let n;Wa(e)?n=Object.entries(e).map(([a,i])=>({range:this.rangeKey,key:a,value:i})):n=[{range:this.rangeKey,key:e,value:t}],await g(this.client,Be.SET_ENDPOINT,{range:this.rangeKey,pairs:n},im,s.z.unknown())}async delete(e){await g(this.client,Be.DELETE_ENDPOINT,{range:this.rangeKey,keys:O.toArray(e)},om,s.z.unknown())}}const lm="sy_range_set",cm="sy_range_delete";class Co{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:t=L.ZERO,key:n,color:a,parent:i,labels:o=[]},{frameClient:l,kv:c,aliaser:u,channels:d,labelClient:h,ontologyClient:b,rangeClient:S}){this.key=n,this.name=e,this.timeRange=t,this.parent=i,this.labels=o,this.frameClient=l,this.color=a,this.kv=c,this.aliaser=u,this.channels=d,this.labelClient=h,this.ontologyClient=b,this.rangeClient=S}get ontologyID(){return Qe(this.key)}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:this.parent}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new je(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async retrieveLabels(){return await this.labelClient.retrieve({for:Qe(this.key)})}async addLabel(...e){await this.labelClient.label(Qe(this.key),e)}async removeLabel(...e){await this.labelClient.remove(Qe(this.key),e)}static sort(e,t){return L.sort(e.timeRange,t.timeRange)}}const um=s.z.object({keys:_.array().optional(),names:s.z.array(s.z.string()).optional(),searchTerm:s.z.string().optional(),overlapsWith:L.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional(),hasLabels:Re.array().optional(),includeLabels:s.z.boolean().optional(),includeParent:s.z.boolean().optional()}),hm=um.or(_.array().transform(r=>({keys:r}))).or(_.transform(r=>({keys:[r]}))).or(s.z.string().transform(r=>({names:[r]}))).or(s.z.string().array().transform(r=>({names:r}))).or(L.z.transform(r=>({overlapsWith:r}))),dm="/range/retrieve",fm=s.z.object({ranges:F(Ht)});let jo=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(r,e,t,n,a,i){this.frameClient=r,this.writer=e,this.unaryClient=t,this.channels=n,this.labelClient=a,this.ontologyClient=i}async create(r,e){const t=!Array.isArray(r),n=this.sugarMany(await this.writer.create(O.toArray(r),e));return t?n[0]:n}async rename(r,e){await this.writer.rename(r,e)}async delete(r){await this.writer.delete(O.toArray(r))}async retrieve(r){const e=typeof r=="string",{ranges:t}=await g(this.unaryClient,dm,r,hm,fm);return ft("Range",r,t,e),e?this.sugarMany(t)[0]:this.sugarMany(t)}getKV(r){return new Be(r,this.unaryClient)}async retrieveParent(r){const e=await this.ontologyClient.retrieveParents(Qe(r));if(e.length===0)return null;const t=e[0];return t.id.type!=="range"?null:await this.retrieve(t.id.key)}sugarOntologyResource(r){return this.sugarOne(Ro(r))}sugarOne(r){return new Co(r,{frameClient:this.frameClient,kv:new Be(r.key,this.unaryClient),aliaser:new Xe(r.key,this.frameClient,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(r){return r.map(e=>this.sugarOne(e))}resourceToRange(r){return this.sugarOne({key:r.id.key,name:r.data?.name,timeRange:new L(r.data?.timeRange),color:r.data?.color,labels:[],parent:null})}};const Qe=r=>({type:"range",key:r}),pm=r=>({type:"range-alias",key:r}),Ro=({data:r,id:{key:e},name:t})=>{const n=L.z.parse(r?.timeRange);return{key:e,name:t,timeRange:n,color:typeof r?.color=="string"?r.color:void 0,labels:[],parent:null}},ym=s.z.object({ranges:Ht.array()}),gm=s.z.object({parent:U.optional(),ranges:Io.array()}),mm=s.z.object({keys:_.array()}),wm=s.z.object({}),bm=s.z.object({key:_,name:ds}),vm=s.z.object({}),Tm="/range/create",Om="/range/delete",Sm="/range/rename";class Uo{client;constructor(e){this.client=e}async rename(e,t){await g(this.client,Sm,{key:e,name:t},bm,vm)}async create(e,t){return(await g(this.client,Tm,{ranges:e,...t},gm,ym)).ranges}async delete(e){await g(this.client,Om,{keys:e},mm,wm)}}const zm=Object.freeze(Object.defineProperty({__proto__:null,Client:jo,DELETE_ALIAS_CHANNEL_NAME:Yg,DELETE_CHANNEL_NAME:cm,KV:Be,KV_DELETE_CHANNEL:nm,KV_SET_CHANNEL:rm,Range:Co,SET_ALIAS_CHANNEL_NAME:qg,SET_CHANNEL_NAME:lm,Writer:Uo,aliasOntologyID:pm,aliasZ:Qg,convertOntologyResourceToPayload:Ro,decodeDeleteAliasChange:tm,keyZ:_,kvPairZ:fs,nameZ:ds,newZ:Io,ontologyID:Qe,payloadZ:Ht},Symbol.toStringTag,{value:"Module"})),Em="/api/v1/";class Nm{url;unary;stream;secure;constructor(e,t={},n=!1){this.secure=n,this.url=e.child(Em);const a=new $e.JSONCodec;this.unary=uu(new cu(this.url,a,this.secure),t),this.stream=new yu(this.url,a,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Wt=s.z.uuid(),ps=s.z.object({key:Wt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(me))}),Am=ps.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),ue=s.z.uuid(),Lr=s.z.object({key:ue,name:s.z.string(),layout:ge.unknownZ.or(s.z.string().transform(me))}),Lo=Lr.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Mo=Lr.omit({layout:!0}).extend({layout:s.z.string().transform(me)}),km="/workspace/lineplot/retrieve",xm="/workspace/lineplot/create",Im="/workspace/lineplot/rename",Cm="/workspace/lineplot/set-data",jm="/workspace/lineplot/delete",Rm=s.z.object({keys:Wt.array()}),Um=s.z.object({workspace:ue,linePlots:Am.array()}),Lm=s.z.object({key:Wt,name:s.z.string()}),Mm=s.z.object({key:Wt,data:s.z.string()}),Pm=s.z.object({keys:Wt.array()}),Dm=s.z.object({linePlots:F(ps)}),Bm=s.z.object({linePlots:ps.array()}),Kr=s.z.object({});let $m=class{client;constructor(r){this.client=r}async create(r,e){const t=Array.isArray(e),n=await g(this.client,xm,{workspace:r,linePlots:O.toArray(e)},Um,Bm);return t?n.linePlots:n.linePlots[0]}async rename(r,e){await g(this.client,Im,{key:r,name:e},Lm,Kr)}async setData(r,e){await g(this.client,Cm,{key:r,data:JSON.stringify(e)},Mm,Kr)}async retrieve(r){const e=Array.isArray(r),t=await g(this.client,km,{keys:O.toArray(r)},Rm,Dm);return e?t.linePlots:t.linePlots[0]}async delete(r){await g(this.client,jm,{keys:O.toArray(r)},Pm,Kr)}};const Gt=s.z.uuid(),ys=s.z.object({key:Gt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(me))}),Fm=ys.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Zm="/workspace/log/retrieve",qm="/workspace/log/create",Ym="/workspace/log/rename",_m="/workspace/log/set-data",Vm="/workspace/log/delete",Hm=s.z.object({keys:Gt.array()}),Wm=s.z.object({workspace:ue,logs:Fm.array()}),Gm=s.z.object({key:Gt,name:s.z.string()}),Km=s.z.object({key:Gt,data:s.z.string()}),Jm=s.z.object({keys:Gt.array()}),Xm=s.z.object({logs:ys.array()}),Qm=s.z.object({logs:ys.array()}),Jr=s.z.object({});let ew=class{client;constructor(r){this.client=r}async create(r,e){const t=Array.isArray(e),n=await g(this.client,qm,{workspace:r,logs:O.toArray(e)},Wm,Qm);return t?n.logs:n.logs[0]}async rename(r,e){await g(this.client,Ym,{key:r,name:e},Gm,Jr)}async setData(r,e){await g(this.client,_m,{key:r,data:JSON.stringify(e)},Km,Jr)}async retrieve(r){const e=Array.isArray(r),t=await g(this.client,Zm,{keys:O.toArray(r)},Hm,Xm);return e?t.logs:t.logs[0]}async delete(r){await g(this.client,Vm,{keys:O.toArray(r)},Jm,Jr)}};const yt=s.z.uuid(),gs=s.z.object({key:yt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(me)),snapshot:s.z.boolean()}),tw=gs.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Po=gs.extend({data:s.z.string().transform(me)}),rw="/workspace/schematic/retrieve",nw="/workspace/schematic/create",sw="/workspace/schematic/rename",aw="/workspace/schematic/set-data",iw="/workspace/schematic/delete",ow="/workspace/schematic/copy",lw=s.z.object({keys:yt.array()}),cw=s.z.object({workspace:ue,schematics:tw.array()}),uw=s.z.object({key:yt,name:s.z.string()}),hw=s.z.object({key:yt,data:s.z.string()}),dw=s.z.object({keys:yt.array()}),fw=s.z.object({key:yt,name:s.z.string(),snapshot:s.z.boolean()}),pw=s.z.object({schematics:F(Po)}),yw=s.z.object({schematics:Po.array()}),gw=s.z.object({schematic:gs}),Xr=s.z.object({});let mw=class{client;constructor(r){this.client=r}async create(r,e){const t=Array.isArray(e),n=await g(this.client,nw,{workspace:r,schematics:O.toArray(e)},cw,yw);return t?n.schematics:n.schematics[0]}async rename(r,e){await g(this.client,sw,{key:r,name:e},uw,Xr)}async setData(r,e){await g(this.client,aw,{key:r,data:JSON.stringify(e)},hw,Xr)}async retrieve(r){const e=Array.isArray(r),t=await g(this.client,rw,{keys:O.toArray(r)},lw,pw);return e?t.schematics:t.schematics[0]}async delete(r){await g(this.client,iw,{keys:O.toArray(r)},dw,Xr)}async copy(r,e,t){return(await g(this.client,ow,{key:r,name:e,snapshot:t},fw,gw)).schematic}};const Kt=s.z.uuid(),Do=s.z.object({key:Kt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(me))}),ww=Do.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Bo=Do.extend({data:s.z.string().transform(me)}),bw="/workspace/table/retrieve",vw="/workspace/table/create",Tw="/workspace/table/rename",Ow="/workspace/table/set-data",Sw="/workspace/table/delete",zw=s.z.object({keys:Kt.array()}),Ew=s.z.object({workspace:ue,tables:ww.array()}),Nw=s.z.object({key:Kt,name:s.z.string()}),Aw=s.z.object({key:Kt,data:s.z.string()}),kw=s.z.object({keys:Kt.array()}),xw=s.z.object({tables:Bo.array()}),Iw=s.z.object({tables:Bo.array()}),Qr=s.z.object({});let Cw=class{client;constructor(r){this.client=r}async create(r,e){const t=Array.isArray(e),n=await g(this.client,vw,{workspace:r,tables:O.toArray(e)},Ew,Iw);return t?n.tables:n.tables[0]}async rename(r,e){await g(this.client,Tw,{key:r,name:e},Nw,Qr)}async setData(r,e){await g(this.client,Ow,{key:r,data:JSON.stringify(e)},Aw,Qr)}async retrieve(r){const e=Array.isArray(r),t=await g(this.client,bw,{keys:O.toArray(r)},zw,xw);return e?t.tables:t.tables[0]}async delete(r){await g(this.client,Sw,{keys:O.toArray(r)},kw,Qr)}};const fa="/workspace/retrieve",jw="/workspace/create",Rw="/workspace/rename",Uw="/workspace/set-layout",Lw="/workspace/delete",pa=s.z.object({keys:ue.array().optional(),searchTerm:s.z.string().optional(),author:Ze.optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Mw=s.z.object({workspaces:Lo.array()}),Pw=s.z.object({key:ue,name:s.z.string()}),Dw=s.z.object({key:ue,layout:s.z.string()}),Bw=s.z.object({keys:ue.array()}),ya=s.z.object({workspaces:F(Lr)}),$w=s.z.object({workspaces:Mo.array()}),en=s.z.object({}),Fw="sy_workspace_set",Zw="sy_workspace_delete";class $o{type="workspace";schematic;linePlot;log;table;client;constructor(e){this.client=e,this.schematic=new mw(e),this.linePlot=new $m(e),this.log=new ew(e),this.table=new Cw(e)}async create(e){const t=Array.isArray(e),n=await g(this.client,jw,{workspaces:O.toArray(e)},Mw,$w);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await g(this.client,Rw,{key:e,name:t},Pw,en)}async setLayout(e,t){await g(this.client,Uw,{key:e,layout:JSON.stringify(t)},Dw,en)}async retrieve(e){let t;const n=typeof e!="string";typeof e=="string"||Array.isArray(e)?t={keys:O.toArray(e)}:t=e;const a=await g(this.client,fa,t,pa,ya);return n?a.workspaces:a.workspaces[0]}async retrieveByAuthor(e){return(await g(this.client,fa,{author:e},pa,ya)).workspaces}async delete(e){await g(this.client,Lw,{keys:O.toArray(e)},Bw,en)}}const qw=r=>({type:"workspace",key:r}),Yw=Object.freeze(Object.defineProperty({__proto__:null,Client:$o,DELETE_CHANNEL_NAME:Zw,SET_CHANNEL_NAME:Fw,keyZ:ue,newZ:Lo,ontologyID:qw,remoteZ:Mo,workspaceZ:Lr},Symbol.toStringTag,{value:"Module"})),Fo=s.z.object({host:s.z.string({error:"Host is required"}).min(1,"Host is required"),port:s.z.number({error:"Port is required"}).or(s.z.string({error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:z.z.default(z.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional(),retry:bi.breakerConfigZ.optional()});class _w extends lo{createdAt;props;ranges;channels;auth;user;access;connectivity;ontology;workspaces;labels;hardware;control;static connectivity=br;transport;clientVersion="0.44.1";constructor(e){const t=Fo.parse(e),{host:n,port:a,username:i,password:o,connectivityPollFrequency:l,secure:c,retry:u}=t,d=new Nm(new Nt({host:n,port:Number(a)}),u,c);d.use(Kd);let h;i!=null&&o!=null&&(h=new Zp(d.unary,{username:i,password:o}),d.use(h.middleware()));const b=new ss(new Yt(d.unary)),S=new Gi(d.unary,b);super(d.stream,d.unary,b),this.createdAt=E.now(),this.props=t,this.auth=h,this.transport=d,this.channels=new Vi(this,b,d.unary,S),this.connectivity=new br(d.unary,l,this.clientVersion,t.name),this.control=new ho(this),this.ontology=new $i(d.unary,this);const R=new Uo(this.transport.unary);this.labels=new xo(this.transport.unary),this.ranges=new jo(this,R,this.transport.unary,b,this.labels,this.ontology),this.access=new Ff(this.transport.unary),this.user=new Up(this.transport.unary),this.workspaces=new $o(this.transport.unary);const A=new wo(this.transport.unary),B=new Eo(this.transport.unary,this,this.ontology,this.ranges),x=new bo(this.transport.unary,B);this.hardware=new zy(B,x,A)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}const Vw=r=>Array.isArray(r)?r:r==null?[]:[r],Hw=Object.freeze(Object.defineProperty({__proto__:null,toArray:Vw},Symbol.toStringTag,{value:"Module"})),tn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Ww=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Gw=(r,e)=>{let t=null;return e===0?r:(...n)=>{t===null&&(t=setTimeout(()=>{r(...n),t=null},e))}},Zo=(r,e,t=".")=>{const n=r.split(t);return n.map((a,i)=>{const o=e(a,i,n);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(a=>a!=null).join(t)},qo=(r,e)=>{if(!Array.isArray(r))return r[e];const t=r[e];if(t!=null||r.length==0)return t;const n=r[0];if(typeof n=="object"&&"key"in n)return r.find(a=>a.key===e)},ms=(r,e,t={optional:!1,separator:"."})=>{t.separator??=".";const{optional:n,getter:a=qo}=t,i=e.split(t.separator);if(i.length===1&&i[0]==="")return r;let o=r;for(const l of i){const c=a(o,l);if(c==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${l} is null`)}o=c}return o},Kw=(r,e,t)=>{const n=e.split(".");let a=r;for(let i=0;i<n.length-1;i++){const o=n[i],l=qo(a,o);if(l==null)throw new Error(`Path ${e} does not exist. ${o} is null`);a=l}try{if(!Array.isArray(a)){a[n[n.length-1]]=t;return}if(a.length===0)return;const i=parseInt(n[n.length-1]);if(isNaN(i)){const o=a[0];if(typeof o=="object"&&"key"in o){const l=a.findIndex(c=>c.key===n[n.length-1]);if(l!==-1){a[l]=t;return}}return}a[i]=t}catch(i){throw console.error("failed to set value",t,"at path",e,"on object",r),i}},Jw=(r,e)=>{const t=e.split(".");let n=r;for(let a=0;a<t.length-1;a++){const i=t[a];if(n[i]==null)return;n=n[i]}if(Array.isArray(n)){const a=parseInt(t[t.length-1]);if(isNaN(a))return;n.splice(a,1);return}delete n[t[t.length-1]]},Xw=(r,e)=>{const t=r.split(".");return e<0?t[t.length+e]:t[e]},Qw=(r,e)=>{try{return ms(r,e),!0}catch{return!1}},eb=(r,e)=>{if(e.length===0)return!0;const t=r.split("."),n=e.split(".");if(n.length>t.length)return!1;for(let a=0;a<n.length;a++){const i=t[a],o=n[a];if(o!=="*"&&i!==o)return!1}return!0},tb=r=>JSON.parse(JSON.stringify(r)),rb=(r,...e)=>(e.forEach(t=>{let n=r;const a=t.split(".");a.forEach((i,o)=>{typeof n!="object"||n===null||(o===a.length-1?delete n[i]:i in n&&(n=n[i]))})}),r),nb=(r,e,t="")=>{const n={},a=(i,o,l)=>{if(typeof i!=typeof o||i===null||o===null){n[l]=[i,o];return}if(typeof i=="object"&&typeof o=="object")if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length){n[l]=[i,o];return}for(let c=0;c<i.length;c++)a(i[c],o[c],`${l}[${c}]`)}else new Set([...Object.keys(i),...Object.keys(o)]).forEach(c=>{a(i[c],o[c],l!==""?`${l}.${c}`:c)});else i!==o&&(n[l]=[i,o])};return a(r,e,t),n},kn=(r,e)=>{const t=Array.isArray(r),n=Array.isArray(e);if(t!==n)return!1;if(t&&n){const o=r,l=e;if(o.length!==l.length)return!1;for(let c=0;c<o.length;c++)if(!kn(o[c],l[c]))return!1;return!0}if(r==null||e==null||typeof r!="object"||typeof e!="object")return r===e;if("equals"in r)return r.equals(e);const a=Object.keys(r),i=Object.keys(e);if(a.length!==i.length)return!1;for(const o of a){const l=r[o],c=e[o];if(typeof l=="object"&&typeof c=="object"){if(!kn(l,c))return!1}else if(l!==c)return!1}return!0},Yo=(r,e)=>{if(typeof r!="object"||r==null)return r===e;const t=Object.keys(r),n=Object.keys(e);if(n.length>t.length)return!1;for(const a of n){const i=r[a],o=e[a];if(typeof i=="object"&&typeof o=="object"){if(!Yo(i,o))return!1}else if(i!==o)return!1}return!0},xn=(r,...e)=>{if(e.length===0)return r;const t=e.shift();if(tn(r)&&tn(t))for(const n in t)try{tn(t[n])?(n in r||Object.assign(r,{[n]:{}}),xn(r[n],t[n])):Object.assign(r,{[n]:t[n]})}catch(a){throw a instanceof TypeError?new TypeError(`.${n}: ${a.message}`):a}return xn(r,...e)},sb=(r,e,t)=>{const n=(a,i,o)=>{if(o.def?.type==="union")return o.def.options.reduce((l,c)=>n(l,i,c),a);if(o.def?.type==="intersection"){const l=n(a,i,o.def.left);return n(l,i,o.def.right)}for(const l in i){const c=i[l];let u=o?.shape;if(u!=null)for(;u!=null;){if(u[l]!=null){const d=u[l].safeParse(c);if(d.success){a[l]=d.data;break}}u=u.def?.shape}typeof c=="object"&&!Array.isArray(c)&&c!==null&&o&&o.shape&&o.shape[l]&&(a[l]||={},n(a[l],c,o.shape[l]))}return a};return n({...r},e,t)},_o=Object.freeze(Object.defineProperty({__proto__:null,copy:tb,deleteD:rb,difference:nb,element:Xw,equal:kn,get:ms,has:Qw,override:xn,overrideValidItems:sb,partialEqual:Yo,pathsMatch:eb,remove:Jw,set:Kw,transformPath:Zo},Symbol.toStringTag,{value:"Module"}));let ab=class{sender;handlers;constructor(e){this.sender=e,this.handlers=new Map}handle({data:e}){const t=this.handlers.get(e.type)?.handler;t==null?console.warn(`No handler for ${e.type}`):t(e.payload)}route(e){const t=ib(e,this.sender),n=new ob(t);return this.handlers.set(e,n),n}};const ib=(r,e)=>(t,n)=>e({type:r,payload:t},n);class ob{_send;handler;constructor(e){this._send=e,this.handler=null}send(e,t=[]){this._send(e,t)}handle(e){this.handler=e}}const In=(r,e,t="")=>{try{return r.parse(e)}catch(n){if(n instanceof s.z.ZodError){const a=n.issues.map(i=>i.path.length===0?i.message:`${i.path.join(".")}: ${i.message}`);throw new Error(`${t} - ${a.join(`
|
|
45
|
-
`)}`)}else throw n}},Vo=r=>typeof r=="function",ws=(r,e)=>Vo(r)?r(e):r,Jt=r=>Ho(r)?r():r,Ho=r=>typeof r=="function",Wo=({initial:r,value:e,onChange:t})=>{const[n,a]=Fn.useState(Jt(e??r));return e!=null&&t!=null?[e,t]:[n,a]},Go=({initial:r,value:e,onChange:t})=>{const[n,a]=Fn.useState(Jt(e??r));return e!=null&&t!=null?[e,t]:[n,a]},lb=(r,e)=>{const[t,n]=Fn.useState(()=>{const a=localStorage.getItem(e);return a==null?Jt(r):JSON.parse(a)});return[t,a=>{n(a),localStorage.setItem(e,JSON.stringify(a))}]},cb=Object.freeze(Object.defineProperty({__proto__:null,executeInitialSetter:Jt,executeSetter:ws,isInitialSetter:Ho,isSetter:Vo,usePassthrough:Wo,usePersisted:lb,usePurePassthrough:Go},Symbol.toStringTag,{value:"Module"}));let ga=null;const ub=()=>(ga??=document.createElement("canvas"),ga),hb=(r,e,t)=>{if(f.S.RUNTIME==="node")return{width:0,height:0};t??=ub().getContext("2d"),t.font=e;const n=t.measureText(r);return Mr(n)},Mr=r=>({width:Math.trunc(Math.abs(r.actualBoundingBoxLeft)+Math.abs(r.actualBoundingBoxRight)),height:Math.trunc(Math.abs(r.actualBoundingBoxAscent)+Math.abs(r.actualBoundingBoxDescent))}),kt=["h1","h2","h3","h4","h5","p","small"],db=s.z.enum(kt),fb=r=>{const e=kt.indexOf(r);return e===-1||e===kt.length-1?r:kt[e+1]},pb=s.z.union([s.z.number(),s.z.enum(["normal","bold","bolder","lighter"])]),Ee=s.z.object({size:s.z.number(),weight:s.z.union([s.z.number(),s.z.string()]),lineHeight:s.z.number(),textTransform:s.z.string().optional()}),yb={tiny:"small",small:"small",medium:"p",large:"h5",huge:"h2"},gb={h1:"huge",h2:"huge",h3:"huge",h4:"large",h5:"small",p:"medium",small:"small"},mb=s.z.object({l0:f.ir.colorZ,l1:f.ir.colorZ,l2:f.ir.colorZ,l3:f.ir.colorZ,l4:f.ir.colorZ,l5:f.ir.colorZ,l6:f.ir.colorZ,l7:f.ir.colorZ,l8:f.ir.colorZ,l9:f.ir.colorZ,l10:f.ir.colorZ,l11:f.ir.colorZ}),J=(r,e)=>[r[0],r[1],e,r[3]],wb=s.z.object({m2:f.ir.colorZ,m1:f.ir.colorZ,z:f.ir.colorZ,p1:f.ir.colorZ,p2:f.ir.colorZ}),sr=wb.or(f.ir.colorZ.transform(r=>{const e=f.ir.hsla(r);return{m2:f.ir.fromHSLA(J(e,40)),m1:f.ir.fromHSLA(J(e,45)),z:r,p1:f.ir.fromHSLA(J(e,55)),p2:f.ir.fromHSLA(J(e,65))}})),Ko=s.z.object({name:s.z.string(),key:s.z.string(),colors:s.z.object({border:f.ir.colorZ,primary:sr,gray:mb,error:sr,secondary:sr,warning:sr,palettes:s.z.record(s.z.string(),f.ir.paletteZ),visualization:s.z.object({palettes:s.z.record(s.z.string(),s.z.array(f.ir.colorZ))}).optional().default({palettes:{}}),white:f.ir.colorZ,black:f.ir.colorZ,text:f.ir.colorZ,textInverted:f.ir.colorZ,textOnPrimary:f.ir.colorZ.optional().default(f.ir.ZERO),logo:s.z.string()}),sizes:s.z.object({base:s.z.number(),border:s.z.object({radius:s.z.number(),width:s.z.number(),thickWidth:s.z.number()}),schematic:s.z.object({elementStrokeWidth:s.z.number()})}),typography:s.z.object({family:s.z.string(),codeFamily:s.z.string(),h1:Ee,h2:Ee,h3:Ee,h4:Ee,h5:Ee,p:Ee,small:Ee})}).transform(r=>((r.colors.textOnPrimary==null||f.ir.isZero(r.colors.textOnPrimary))&&(r.colors.textOnPrimary=f.ir.pickByContrast(r.colors.primary.z,r.colors.text,r.colors.textInverted)),r)),bb="'Inter Variable', sans-serif",vb="'Geist Mono', monospace",Tb=6,wt=[357,91,55,1],bt=[48,90,55,1],Ob=["#FEFEFE","#FAFAFA","#F2F2F2","#ECECEC","#E4E4E4","#D1D1D1","#BCBCBC","#ACACAC","#8F8F8F","#4F4F4F","#292929","#050505"],vt=Object.fromEntries(Ob.map((r,e)=>[`l${e}`,r])),Sb=()=>typeof window>"u"?!1:window.devicePixelRatio>1,zb=Sb(),Cn={key:"synnaxBase",name:"Synnax Base",colors:{primary:{m2:"#041B3D",m1:"#356fc5",z:"#3774D0",p1:"#5E94EE",p2:"#8AB8FF"},secondary:{m2:"#2D8F4E",m1:"#38B261",z:"#50C878",p1:"#73D393",p2:"#96DEAE"},gray:vt,border:vt.l4,error:{m2:f.ir.fromHSLA(J(wt,30)),m1:f.ir.fromHSLA(J(wt,40)),z:f.ir.fromHSLA(wt),p1:f.ir.fromHSLA(J(wt,65)),p2:f.ir.fromHSLA(J(wt,77))},warning:{m2:f.ir.fromHSLA(J(bt,30)),m1:f.ir.fromHSLA(J(bt,40)),z:f.ir.fromHSLA(bt),p1:f.ir.fromHSLA(J(bt,65)),p2:f.ir.fromHSLA(J(bt,75))},palettes:{recent:{key:"recent",name:"Recent",swatches:[]}},visualization:{palettes:{default:["#DC136C","#20A4F3","#7AC74F","#FFC43D","#FE5F55","#8075FF","#D90429","#f7aef8","#f18f01","#791e94","#279af1","#d9fff5","#ff6b6b","#52ffb8"]}},logo:"url(#synnax-linear-gradient)",white:"#FFFFFF",black:"#000000",text:vt.l11,textInverted:vt.l0,textOnPrimary:vt.l0},sizes:{base:Tb,border:{radius:3,width:zb?.5:1,thickWidth:1},schematic:{elementStrokeWidth:2}},typography:{family:bb,codeFamily:vb,h1:{size:6,weight:"500",lineHeight:6*1.5},h2:{size:4.5,weight:"medium",lineHeight:4.5*1.5},h3:{size:3.5,weight:"medium",lineHeight:3.5*1.5},h4:{size:2.6666,weight:"medium",lineHeight:2.6666*1.5},h5:{size:2.333333,weight:450,lineHeight:2.333333*1.5},p:{size:2.1666666666,weight:"regular",lineHeight:2*1.5},small:{size:1.916666,weight:"regular",lineHeight:2.3333333}}},Jo=Object.freeze({...Cn,key:"synnaxLight",name:"Synnax Light"}),Eb=["#020202","#080808","#151515","#242424","#2F2F2F","#3B3B3B","#4A4A4A","#5C5C5C","#767676","#959595","#dadada","#FAFAFA"],Tt=Object.fromEntries(Eb.map((r,e)=>[`l${e}`,r])),Xo=Object.freeze({...Cn,key:"synnaxDark",name:"Synnax Dark",colors:{...Cn.colors,gray:Tt,logo:"var(--pluto-text-color)",border:Tt.l3,text:Tt.l11,textInverted:Tt.l0,textOnPrimary:Tt.l11}}),Nb={synnaxDark:Xo,synnaxLight:Jo},Qo=["tiny","small","medium","large","huge"],el=s.z.enum(Qo),Ab=r=>el.safeParse(r).success;class it{_noop=!1;key;path;serviceName;constructor(e,t,n="",a=!1){this.key=e,this.path=t,this.serviceName=n,this._noop=a}child(e){return new it(e,this.extendPath(e),this.serviceName,this.noop)}extendPath(e){return`${this.path}.${e}`}get noop(){return this._noop}static NOOP=new it("","","")}const jn=["debug","info","warn","error"],tl=r=>{const e=jn.indexOf(r);return({level:t})=>jn.indexOf(t)>=e},kb=r=>{const{include:e,exclude:t}=r;return({path:n})=>!(e!=null&&!e.some(a=>n.startsWith(a))||t!=null&&t.some(a=>n.startsWith(a)))};class ot{meta=it.NOOP;filters;constructor(e={}){const{filters:t=[]}=e;this.filters=t}filter(e){return!this.meta.noop&&this.filters.every(t=>t({key:this.meta.key,path:this.meta.path,level:e}))}child(e){const t=new ot({filters:this.filters});return t.meta=e,t}debug(e,t,n=!1){!this.filter("debug")&&!n||(t==null?console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e):console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e,ar(t)))}info(e,t,n=!1){!this.filter("info")&&!n||(t==null?console.log("%cINFO","color: #005eff;",this.meta.path,e):console.log("%cINFO","color: #005eff;",this.meta.path,e,ar(t)))}warn(e,t,n=!1){!this.filter("warn")&&!n||(t==null?console.warn("WARN",this.meta.path,e):console.warn("WARN",this.meta.path,e,ar(t)))}error(e,t,n=!1){!this.filter("error")&&!n||(t==null?console.error("ERROR",this.meta.path,e):console.error("ERROR",this.meta.path,e,ar(t)))}static NOOP=new ot}const ar=r=>typeof r=="function"?r():r;var xb=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Pe="1.9.0",ma=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ib(r){var e=new Set([r]),t=new Set,n=r.match(ma);if(!n)return function(){return!1};var a={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(a.prerelease!=null)return function(l){return l===r};function i(l){return t.add(l),!1}function o(l){return e.add(l),!0}return function(l){if(e.has(l))return!0;if(t.has(l))return!1;var c=l.match(ma);if(!c)return i(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||a.major!==u.major?i(l):a.major===0?a.minor===u.minor&&a.patch<=u.patch?o(l):i(l):a.minor<=u.minor?o(l):i(l)}}var Cb=Ib(Pe),jb=Pe.split(".")[0],Ut=Symbol.for("opentelemetry.js.api."+jb),Lt=xb;function bs(r,e,t,n){var a;n===void 0&&(n=!1);var i=Lt[Ut]=(a=Lt[Ut])!==null&&a!==void 0?a:{version:Pe};if(!n&&i[r]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(o.stack||o.message),!1}if(i.version!==Pe){var o=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Pe);return t.error(o.stack||o.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Pe+"."),!0}function Mt(r){var e,t,n=(e=Lt[Ut])===null||e===void 0?void 0:e.version;if(!(!n||!Cb(n)))return(t=Lt[Ut])===null||t===void 0?void 0:t[r]}function vs(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Pe+".");var t=Lt[Ut];t&&delete t[r]}var Rb=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},Ub=function(r,e,t){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Lb=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ot("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ot("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ot("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ot("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ot("verbose",this._namespace,e)},r}();function Ot(r,e,t){var n=Mt("diag");if(n)return t.unshift(e),n[r].apply(n,Ub([],Rb(t),!1))}var G;(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(G||(G={}));function Mb(r,e){r<G.NONE?r=G.NONE:r>G.ALL&&(r=G.ALL),e=e||{};function t(n,a){var i=e[n];return typeof i=="function"&&r>=a?i.bind(e):function(){}}return{error:t("error",G.ERROR),warn:t("warn",G.WARN),info:t("info",G.INFO),debug:t("debug",G.DEBUG),verbose:t("verbose",G.VERBOSE)}}var Pb=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},Db=function(r,e,t){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Bb="diag",Pt=function(){function r(){function e(a){return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var l=Mt("diag");if(l)return l[a].apply(l,Db([],Pb(i),!1))}}var t=this,n=function(a,i){var o,l,c;if(i===void 0&&(i={logLevel:G.INFO}),a===t){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((o=u.stack)!==null&&o!==void 0?o:u.message),!1}typeof i=="number"&&(i={logLevel:i});var d=Mt("diag"),h=Mb((l=i.logLevel)!==null&&l!==void 0?l:G.INFO,a);if(d&&!i.suppressOverrideMessage){var b=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+b),h.warn("Current logger will overwrite one already registered from "+b)}return bs("diag",h,t,!0)};t.setLogger=n,t.disable=function(){vs(Bb,t)},t.createComponentLogger=function(a){return new Lb(a)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}(),$b=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},Fb=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Zb=function(){function r(e){this._entries=e?new Map(e):new Map}return r.prototype.getEntry=function(e){var t=this._entries.get(e);if(t)return Object.assign({},t)},r.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var t=$b(e,2),n=t[0],a=t[1];return[n,a]})},r.prototype.setEntry=function(e,t){var n=new r(this._entries);return n._entries.set(e,t),n},r.prototype.removeEntry=function(e){var t=new r(this._entries);return t._entries.delete(e),t},r.prototype.removeEntries=function(){for(var e,t,n=[],a=0;a<arguments.length;a++)n[a]=arguments[a];var i=new r(this._entries);try{for(var o=Fb(n),l=o.next();!l.done;l=o.next()){var c=l.value;i._entries.delete(c)}}catch(u){e={error:u}}finally{try{l&&!l.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}return i},r.prototype.clear=function(){return new r},r}();Pt.instance();function qb(r){return r===void 0&&(r={}),new Zb(new Map(Object.entries(r)))}function Yb(r){return Symbol.for(r)}var _b=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,a){var i=new r(t._currentContext);return i._currentContext.set(n,a),i},t.deleteValue=function(n){var a=new r(t._currentContext);return a._currentContext.delete(n),a}}return r}(),Vb=new _b,Hb={get:function(r,e){if(r!=null)return r[e]},keys:function(r){return r==null?[]:Object.keys(r)}},Wb={set:function(r,e,t){r!=null&&(r[e]=t)}},Gb=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},Kb=function(r,e,t){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Jb=function(){function r(){}return r.prototype.active=function(){return Vb},r.prototype.with=function(e,t,n){for(var a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return t.call.apply(t,Kb([n],Gb(a),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}(),Xb=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},Qb=function(r,e,t){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},rn="context",ev=new Jb,rl=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return bs(rn,e,Pt.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var a,i=[],o=3;o<arguments.length;o++)i[o-3]=arguments[o];return(a=this._getContextManager()).with.apply(a,Qb([e,t,n],Xb(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Mt(rn)||ev},r.prototype.disable=function(){this._getContextManager().disable(),vs(rn,Pt.instance())},r}(),Rn;(function(r){r[r.UNSET=0]="UNSET",r[r.OK=1]="OK",r[r.ERROR=2]="ERROR"})(Rn||(Rn={}));var tv=rl.getInstance(),rv=function(){function r(){}return r.prototype.inject=function(e,t){},r.prototype.extract=function(e,t){return e},r.prototype.fields=function(){return[]},r}(),Ts=Yb("OpenTelemetry Baggage Key");function nl(r){return r.getValue(Ts)||void 0}function nv(){return nl(rl.getInstance().active())}function sv(r,e){return r.setValue(Ts,e)}function av(r){return r.deleteValue(Ts)}var nn="propagation",iv=new rv,ov=function(){function r(){this.createBaggage=qb,this.getBaggage=nl,this.getActiveBaggage=nv,this.setBaggage=sv,this.deleteBaggage=av}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalPropagator=function(e){return bs(nn,e,Pt.instance())},r.prototype.inject=function(e,t,n){return n===void 0&&(n=Wb),this._getGlobalPropagator().inject(e,t,n)},r.prototype.extract=function(e,t,n){return n===void 0&&(n=Hb),this._getGlobalPropagator().extract(e,t,n)},r.prototype.fields=function(){return this._getGlobalPropagator().fields()},r.prototype.disable=function(){vs(nn,Pt.instance())},r.prototype._getGlobalPropagator=function(){return Mt(nn)||iv},r}(),lv=ov.getInstance();const wa=["bench","debug","prod"],cv=r=>e=>wa.indexOf(e)>=wa.indexOf(r);class Dt{meta=it.NOOP;otelTracer;filter;constructor(e,t=cv("debug")){this.otelTracer=e,this.filter=t}child(e){const t=new Dt(this.otelTracer,this.filter);return t.meta=e,t}debug(e,t){return this.trace(e,"debug",t)}bench(e,t){return this.trace(e,"bench",t)}prod(e,t){return this.trace(e,"prod",t)}trace(e,t,n){const a=this.meta.noop||!this.filter(t)||this.otelTracer==null;if(n==null){if(a)return()=>{};const i=new Un(e,this.otelTracer.startSpan(e));return i.start(),()=>i.end()}return a?n(new sl(e)):this.otelTracer.startActiveSpan(e,i=>{const o=new Un(e,i);return n(o)})}propagate(e){if(this.meta.noop)return;const t=tv.active();lv.inject(t,e,{set:(n,a,i)=>{n[a]=i}})}static NOOP=new Dt}class Un{key;otel;constructor(e,t){this.key=e,this.otel=t}set(e,t){this.otel.setAttribute(e,t)}recordError(e){e!=null&&(this.otel.recordException(e),this.otel.setStatus({code:Rn.ERROR}))}start(){performance.mark(`alamos.trace.start.${this.key}`)}end(){try{performance.mark(`alamos.trace.end.${this.key}`);const e=performance.measure(`alamos.trace.duration.${this.key}`,`alamos.trace.start.${this.key}`,`alamos.trace.end.${this.key}`);this.set("duration",e.duration),this.otel.end()}catch(e){console.error(e)}}}class sl{key;constructor(e){this.key=e}set(){}recordError(e){}}class lt{meta;T;L;constructor({key:e="",serviceName:t="",logger:n=ot.NOOP,tracer:a=Dt.NOOP,noop:i=!1,__meta:o}){this.meta=o??new it(e,e,t,i),this.T=a.child(this.meta),this.L=n.child(this.meta)}child(e){const t=this.meta.child(e);return new lt({__meta:t,tracer:this.T,logger:this.L})}static NOOP=new lt({noop:!0})}const uv=lt.NOOP,ke=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:lt,LOG_LEVELS:jn,Logger:ot,NOOP:uv,NoopSpan:sl,Tracer:Dt,_Span:Un,logLevelKeyFiler:kb,logThresholdFilter:tl},Symbol.toStringTag,{value:"Module"})),sn=(r,e)=>r instanceof Error?(r.message=`[${e}] - ${r.message}`,r):new Error(e??"unknown error",{cause:r});class Pr{type;key;sender;_internalState;_state;_prevState;_deleted=!1;parentCtxValues;childCtxValues;childCtxChangedKeys;instrumentation;schema=void 0;constructor({key:e,type:t,sender:n,instrumentation:a,parentCtxValues:i}){this.type=t,this.key=e,this.sender=n,this._internalState={},this.instrumentation=a.child(this.toString()),this.parentCtxValues=new Map,i?.forEach((o,l)=>this.parentCtxValues.set(l,o)),this.childCtxValues=new Map,this.childCtxChangedKeys=new Set}get _schema(){if(this.schema==null)throw new $(`[AetherLeaf] - expected subclass to define component schema, but none was found.
|
|
46
|
-
Make sure to define a property 'schema' on the class.`);return this.schema}setState(e){const t=ws(e,this.state);this._prevState=f.br(this._state),this._state=In(this._schema,t,`${this.toString()}`),this.sender.send({variant:"update",key:this.key,state:this._state})}get state(){if(this._state==null)throw new W(`[AetherLeaf] - state not defined in ${this.toString()}`);return this._state}get internal(){return this._internalState}get prevState(){if(this._prevState===void 0)throw new Error("prevState not defined");return this._prevState}get deleted(){return this._deleted}get ctx(){return{get:e=>{const t=this.parentCtxValues.get(e);if(t===void 0)throw new st(`Context value for ${e} not found on ${this.toString()}`);return t},getOptional:e=>this.parentCtxValues.get(e),has:e=>this.parentCtxValues.has(e),wasSetPreviously:e=>this.childCtxValues.has(e),set:(e,t,n=!0)=>{this.childCtxValues.set(e,t),n&&this.childCtxChangedKeys.add(e)}}}toString(){return`${this.type}(${this.key})`}_updateState({path:e,state:t}){if(!this.deleted)try{const n=this.instrumentation.T.debug(`${this.toString()}:updateState`);this.validatePath(e);const a=In(this._schema,t,`${this.toString()}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:_o.difference(this.state,a)})):this.instrumentation.L.debug("setting initial state",{state:t,path:e}),this._prevState=this._state??a,this._state=a,this.afterUpdate(this.ctx),n()}catch(n){throw sn(n,`${this.toString()}.updateState`)}}_updateContext(e){try{const t=this.instrumentation.T.debug(`${this.toString()}:updateContext`);e.forEach((n,a)=>this.parentCtxValues.set(a,n)),this.afterUpdate(this.ctx),t()}catch(t){throw sn(t,`${this.type}.${this.key}.updateContext`)}}_delete(e){try{const t=this.instrumentation.T.debug(`${this.toString()}:delete`);this.validatePath(e),this._deleted=!0,this.afterDelete(this.ctx),t()}catch(t){throw sn(t,`[${this.toString()}:delete]`)}}afterUpdate(e){}afterDelete(e){}validatePath(e){if(e.length===0)throw new W(`[Leaf.setState] - ${this.toString()} received an empty path`);const t=e[e.length-1];if(e.length>1)throw new W(`[Leaf.setState] - ${this.toString()} received a subPath ${e.join(".")} but is a leaf`);if(t!==this.key)throw new W(`[Leaf.setState] - ${this.toString()} received a key ${t} but expected ${this.key}`)}}class gt extends Pr{_children=new Map;get children(){return Array.from(this._children.values())}getChild(e){return this._children.get(e)??null}childrenOfType(...e){return this.children.filter(t=>e.includes(t.type))}_updateState(e){const{path:t,type:n,create:a}=e;if(this.deleted)return;const i=this.parsePath(t);if(i.length===0){if(this.childCtxChangedKeys.clear(),super._updateState(e),this.childCtxChangedKeys.size==0)return;this.updateChildContexts();return}const l=i[0],c=this.getChild(l);if(c!=null)return c._updateState({...e,path:i});if(i.length>1){const d=t.slice(0,t.indexOf(l)+1).join("."),h=t.join(".");throw new W(`Child of ${this.toString()} at path ${d} does not exist,
|
|
47
|
-
but an extended path ${h} was provided. This means that the aether
|
|
48
|
-
tree is attempting to create a new child of type ${n} (or nested children)
|
|
49
|
-
on a child that does not exist.
|
|
50
|
-
|
|
51
|
-
Children present: ${this.children.map(b=>`${b.type}:${b.key}`).join(".")}
|
|
52
|
-
|
|
53
|
-
`)}const u=a(this.childCtx());u._updateState({...e,path:i}),this._children.set(l,u)}_updateContext(e){super._updateContext(e),this.updateChildContexts()}childCtx(){return{get:e=>this.childCtxValues.get(e)??this.parentCtxValues.get(e),forEach:e=>{this.childCtxValues.forEach((t,n)=>e(t,n,this.childCtxValues)),this.parentCtxValues.forEach((t,n)=>{this.childCtxValues.has(n)||e(t,n,this.parentCtxValues)})}}}updateChildContexts(){const e=this.childCtx();this.children.forEach(t=>t._updateContext(e))}_delete(e){const t=this.parsePath(e);if(t.length===0){for(const a of this.children)a._delete([a.key]);this._children.clear(),super._delete([this.key])}const n=this.getChild(t[0]);if(n!=null){if(t.length>1)return n._delete(t);this._children.delete(n.key),n._delete(t)}}parsePath(e,t){const[n,...a]=e;if(n==null)throw new Error(`Composite ${this.toString()} received an empty path${t!=null?` for ${t}`:""}`);if(n!==this.key)throw new W(`[Composite.getRequiredKey] - ${this.toString()} received a key ${n} but expected ${this.key}`);return a}}const hv=s.z.object({}),dv=()=>{throw new Error("should not call create")};class xe extends gt{static TYPE="root";static KEY="root";comms;registry;schema=hv;constructor({comms:e,instrumentation:t=ke.Instrumentation.NOOP,registry:n}){super({key:xe.KEY,type:xe.TYPE,sender:e,instrumentation:t,parentCtxValues:null}),this.comms=e,this.registry=n}static render(e){const t=new xe(e);return t._updateState({path:[xe.KEY],type:"",state:{},create:dv}),t.comms.handle(n=>{try{t.handle(n)}catch(a){const i={name:"unknown",message:JSON.stringify(a),stack:"unknown"};a instanceof Error&&(i.name=a.name,i.message=a.message,i.stack=a.stack),t.comms.send({variant:"error",error:i})}}),t}handle(e){const{path:t,variant:n,type:a}=e;if(n==="delete"){this._delete(t);return}const{state:i}=e;this._updateState({path:t,type:a,state:i,create:o=>{const l=t[t.length-1];return this.create({key:l,type:a,parentCtxValues:o})}})}create({key:e,type:t,parentCtxValues:n}){const a=this.registry[t];if(a==null)throw new W(`[Root.create] - ${t} not found in registry`);return new a({key:e,type:t,sender:this.comms,instrumentation:this.instrumentation,parentCtxValues:n})}}const al=xe.render.bind(xe),fv=Object.freeze(Object.defineProperty({__proto__:null,Composite:gt,Leaf:Pr,Root:xe,render:al},Symbol.toStringTag,{value:"Module"})),il=s.z.object({statuses:f._r.statusZ().array()}),Tr="status.aggregator";class Ln extends gt{static TYPE="status.Aggregator";schema=il;afterUpdate(e){e.wasSetPreviously(Tr)||e.set(Tr,{add:this.add.bind(this),create:f._r.create})}add(e){this.setState(t=>({...t,statuses:[...t.statuses,f._r.create(e)]}))}}const Os=r=>r.get(Tr).add,pv=r=>{const e=r.getOptional(Tr);return e!=null?e.add:()=>{}},ol=r=>(e,t)=>{if(typeof e!="function")return r(f._r.fromException(e,t));(async()=>{try{await e()}catch(n){r(f._r.fromException(n,t))}})()},Ss=r=>ol(Os(r)),yv={[Ln.TYPE]:Ln},Mn="pluto-theming-context",ll=s.z.object({name:s.z.string(),url:s.z.string()}),gv=s.z.object({theme:Ko,fontURLs:s.z.array(ll)});let Pn=class cl extends gt{static TYPE="theming.Provider";static z=gv;schema=cl.z;afterUpdate(e){if(e.getOptional(Mn)!=null&&this.state.theme.key===this.prevState.theme.key)return;e.set(Mn,this.state.theme),Ss(e)(async()=>{await this.loadFonts()},"failed to load theme fonts")}async loadFonts(){await Promise.all(this.state.fontURLs.map(async({name:e,url:t})=>{const n=new FontFace(e,`url(${t})`);try{await n.load(),self.fonts.add(n)}catch(a){console.error(a)}}))}};const mv=r=>r.get(Mn),wv={[Pn.TYPE]:Pn},ul=s.z.object({include:s.z.string().array().optional(),exclude:s.z.string().array().optional(),level:s.z.enum(ke.LOG_LEVELS).optional().default("info")}),Dn="alamos-provider";class Bn extends gt{static TYPE="alamos.Provider";schema=ul;afterUpdate(e){if(e.getOptional(Dn)!=null)return;const n=[],{include:a,exclude:i,level:o}=this.state;(a!=null||i!=null)&&n.push(ke.logLevelKeyFiler({include:a,exclude:i})),o!=null&&n.push(ke.logThresholdFilter(o)),n.length===0&&n.push(()=>!1),this.internal.ins=new ke.Instrumentation({key:"aether",logger:new ke.Logger({filters:n})}),e.set(Dn,this.internal.ins)}}const hl=(r,e)=>{const t=r.get(Dn);if(t==null)throw new Error("No instrumentation provider");return e==null?t:t.child(e)},bv={[Bn.TYPE]:Bn},fr=(r,e)=>f.Ho.construct(f.Ho.left(r)-e.x,f.Ho.top(r)-e.y,f.Ho.width(r)+e.x*2,f.Ho.height(r)+e.y*2);class Or{scale_;wrapped;atlasRegistry;cachedFont=null;cachedFillStyle=null;cachedStrokeStyle=null;cachedLineWidth=null;cachedGlobalAlpha=null;cachedTextAlign=null;cachedTextBaseline=null;cachedLineCap=null;cachedLineJoin=null;cachedMiterLimit=null;dpr;constructor(e,t,n,a=f.C.XY.IDENTITY){this.wrapped=e,this.scale_=a,this.atlasRegistry=t,this.dpr=n}get fontStretch(){return this.wrapped.fontStretch}set fontStretch(e){this.wrapped.fontStretch=e}get fontVariantCaps(){return this.wrapped.fontVariantCaps}set fontVariantCaps(e){this.wrapped.fontVariantCaps=e}isContextLost(){return this.wrapped.isContextLost()}get wordSpacing(){return this.wrapped.wordSpacing}set wordSpacing(e){this.wrapped.wordSpacing=e}get letterSpacing(){return this.wrapped.letterSpacing}set letterSpacing(e){this.wrapped.letterSpacing=e}get textRendering(){return this.wrapped.textRendering}set textRendering(e){this.wrapped.textRendering=e}checkAtlasFillStyle(e=!1){return e&&typeof this.fillStyle=="string"?[!0,this.fillStyle]:(e&&console.warn("attempted to use a text atlas with a gradient fill style. This is not supported. Falling back to default canvas fill."),[!1,null])}reset(){this.wrapped.reset()}applyScale(e){return new Or(this,this.atlasRegistry,this.dpr,e)}get canvas(){return this.wrapped.canvas}get miterLimit(){return this.cachedMiterLimit??this.wrapped.miterLimit}set miterLimit(e){const t=this.scale_.x.dim(e);t!==this.cachedMiterLimit&&(this.cachedMiterLimit=t,this.wrapped.miterLimit=t)}get globalAlpha(){return this.cachedGlobalAlpha??this.wrapped.globalAlpha}set globalAlpha(e){e!==this.cachedGlobalAlpha&&(this.cachedGlobalAlpha=e,this.wrapped.globalAlpha=e)}get globalCompositeOperation(){return this.wrapped.globalCompositeOperation}set globalCompositeOperation(e){this.wrapped.globalCompositeOperation=e}get fillStyle(){return this.cachedFillStyle??this.wrapped.fillStyle}set fillStyle(e){e!==this.cachedFillStyle&&(this.cachedFillStyle=e,this.wrapped.fillStyle=e)}get strokeStyle(){return this.cachedStrokeStyle??this.wrapped.strokeStyle}set strokeStyle(e){e!==this.cachedStrokeStyle&&(this.cachedStrokeStyle=e,this.wrapped.strokeStyle=e)}drawImage(e,t,n,a,i,o,l,c,u){this.wrapped.drawImage(e,t,n,a,i,o!=null?this.scale_.x.pos(o):o,l!=null?this.scale_.y.pos(l):l,c!=null?this.scale_.x.dim(c):c,u!=null?this.scale_.y.dim(u):u)}beginPath(){this.wrapped.beginPath()}clip(e,t){this.wrapped.clip(e,t)}fill(e,t){if(e==null)return this.wrapped.fill();this.wrapped.fill(e,t)}isPointInPath(e,t,n,a){return this.wrapped.isPointInPath(e,t,n,a)}isPointInStroke(e,t,n){return this.wrapped.isPointInStroke(e,t,n)}stroke(e){if(e==null)return this.wrapped.stroke();this.wrapped.stroke(e)}createConicGradient(e,t,n){return this.wrapped.createConicGradient(e,t,n)}createLinearGradient(e,t,n,a){return this.wrapped.createLinearGradient(e,t,n,a)}createPattern(e,t){return this.wrapped.createPattern(e,t)}createRadialGradient(e,t,n,a,i,o){return this.wrapped.createRadialGradient(e,t,n,a,i,o)}get filter(){return this.wrapped.filter}set filter(e){this.wrapped.filter=e}createImageData(e,t,n){return this.wrapped.createImageData(e,t,n)}getImageData(e,t,n,a,i){return this.wrapped.getImageData(e,t,n,a,i)}putImageData(e,t,n,a,i,o,l){this.wrapped.putImageData(e,t,n,a,i,o,l)}get imageSmoothingEnabled(){return this.wrapped.imageSmoothingEnabled}set imageSmoothingEnabled(e){this.wrapped.imageSmoothingEnabled=e}get imageSmoothingQuality(){return this.wrapped.imageSmoothingQuality}set imageSmoothingQuality(e){this.wrapped.imageSmoothingQuality=e}arc(e,t,n,a,i,o){this.wrapped.arc(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),a,i,o)}arcTo(e,t,n,a,i){this.wrapped.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.dim(i))}bezierCurveTo(e,t,n,a,i,o){this.wrapped.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.pos(i),this.scale_.y.pos(o))}closePath(){this.wrapped.closePath()}ellipse(e,t,n,a,i,o,l,c){this.wrapped.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a),i,o,l,c)}lineTo(e,t){this.wrapped.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}moveTo(e,t){this.wrapped.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}quadraticCurveTo(e,t,n,a){this.wrapped.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a))}rect(e,t,n,a){this.wrapped.rect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a))}roundRect(e,t,n,a,i){this.wrapped.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a),typeof i=="number"?this.scale_.x.dim(i):i)}get lineCap(){return this.cachedLineCap??this.wrapped.lineCap}set lineCap(e){e!==this.cachedLineCap&&(this.cachedLineCap=e,this.wrapped.lineCap=e)}get lineDashOffset(){return this.wrapped.lineDashOffset}set lineDashOffset(e){this.wrapped.lineDashOffset=this.scale_.x.dim(e)}get lineJoin(){return this.cachedLineJoin??this.wrapped.lineJoin}set lineJoin(e){e!==this.cachedLineJoin&&(this.cachedLineJoin=e,this.wrapped.lineJoin=e)}get lineWidth(){return this.cachedLineWidth??this.wrapped.lineWidth}set lineWidth(e){const t=this.scale_.x.dim(e);t!==this.cachedLineWidth&&(this.cachedLineWidth=t,this.wrapped.lineWidth=t)}getLineDash(){return this.wrapped.getLineDash()}setLineDash(e){const t=Array.from(e).map(n=>this.scale_.x.dim(n));this.wrapped.setLineDash(t)}clearRect(e,t,n,a){this.wrapped.clearRect(e,t,n,a)}fillRect(e,t,n,a){this.wrapped.fillRect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a))}strokeRect(e,t,n,a){this.wrapped.strokeRect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a))}get shadowBlur(){return this.wrapped.shadowBlur}set shadowBlur(e){this.wrapped.shadowBlur=e}get shadowColor(){return this.wrapped.shadowColor}set shadowColor(e){this.wrapped.shadowColor=e}get shadowOffsetX(){return this.wrapped.shadowOffsetX}set shadowOffsetX(e){this.wrapped.shadowOffsetX=e}get shadowOffsetY(){return this.wrapped.shadowOffsetY}restore(){this.cachedFillStyle=null,this.cachedStrokeStyle=null,this.cachedLineWidth=null,this.cachedGlobalAlpha=null,this.cachedTextAlign=null,this.cachedTextBaseline=null,this.cachedLineCap=null,this.cachedLineJoin=null,this.cachedMiterLimit=null,this.cachedFont=null,this.wrapped.restore()}save(){this.wrapped.save()}fillText(e,t,n,a,i={}){const[o,l]=this.checkAtlasFillStyle(i.useAtlas);if(o){this.atlasRegistry.get({font:this.font,textColor:l}).fillText(this,e,t,n);return}this.wrapped.fillText(e,this.scale_.x.pos(t),this.scale_.y.pos(n),a!=null?this.scale_.x.dim(a):void 0)}measureText(e){return this.wrapped.measureText(e)}textDimensions(e,t={}){const[n,a]=this.checkAtlasFillStyle(t.useAtlas);return n?this.atlasRegistry.get({font:this.font,textColor:a}).measureText(e):Mr(this.measureText(e))}strokeText(e,t,n,a){this.wrapped.strokeText(e,this.scale_.x.pos(t),this.scale_.y.pos(n),a!=null?this.scale_.x.dim(a):void 0)}get direction(){return this.wrapped.direction}set direction(e){this.wrapped.direction=e}get font(){return this.cachedFont!=null?this.cachedFont:this.wrapped.font}set font(e){e!==this.cachedFont&&(this.cachedFont=e,this.wrapped.font=this.cachedFont)}get fontKerning(){return this.wrapped.fontKerning}set fontKerning(e){this.wrapped.fontKerning=e}get textAlign(){return this.cachedTextAlign??this.wrapped.textAlign}set textAlign(e){e!==this.cachedTextAlign&&(this.cachedTextAlign=e,this.wrapped.textAlign=e)}get textBaseline(){return this.cachedTextBaseline??this.wrapped.textBaseline}set textBaseline(e){e!==this.cachedTextBaseline&&(this.cachedTextBaseline=e,this.wrapped.textBaseline=e)}getTransform(){return this.wrapped.getTransform()}resetTransform(){this.wrapped.resetTransform()}rotate(e){this.wrapped.rotate(e)}scale(e,t){this.wrapped.scale(e,t),this.dpr=e}scissor(e,t=f.K.ZERO){const n=new vv(this.scale_);return e=fr(e,t),n.rect(...f.K.couple(f.Ho.topLeft(e)),...f._.couple(f.Ho.dims(e))),this.save(),this.clip(n.getPath()),()=>this.restore()}setTransform(e,t,n,a,i,o){this.wrapped.setTransform(e,t,n,a,i,o)}transform(e,t,n,a,i,o){this.wrapped.transform(e,t,n,a,i,o)}translate(e,t){this.wrapped.translate(e,t)}}class vv{scale_;path;constructor(e=f.C.XY.IDENTITY,t){this.scale_=e,t instanceof Path2D||typeof t=="string"?this.path=new Path2D(t):this.path=new Path2D}addPath(e,t){this.path.addPath(e,t)}arc(e,t,n,a,i,o){this.path.arc(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),a,i,o)}arcTo(e,t,n,a,i){this.path.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.dim(i))}bezierCurveTo(e,t,n,a,i,o){this.path.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.pos(i),this.scale_.y.pos(o))}closePath(){this.path.closePath()}ellipse(e,t,n,a,i,o,l,c){this.path.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a),i,o,l,c)}lineTo(e,t){this.path.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}moveTo(e,t){this.path.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}quadraticCurveTo(e,t,n,a){this.path.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a))}rect(e,t,n,a){this.path.rect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a))}roundRect(e,t,n,a,i){const o=this.scaleRadii(i);this.path.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a),o)}scaleRadii(e){return e==null?e:typeof e=="number"?this.scale_.x.dim(e):Array.isArray(e)?e.map(t=>this.scaleRadius(t)):this.scaleRadius(e)}scaleRadius(e){return typeof e=="number"?this.scale_.x.dim(e):{x:this.scale_.x.dim(e.x??0),y:this.scale_.y.dim(e.y??0)}}getPath(){return this.path}}const Tv=`precision mediump float;
|
|
54
|
-
|
|
55
|
-
void main(void) {
|
|
56
|
-
gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
|
|
57
|
-
}
|
|
58
|
-
`,Ov=`attribute vec4 a_position;
|
|
59
|
-
|
|
60
|
-
void main(void) {
|
|
61
|
-
gl_Position = a_position;
|
|
62
|
-
}
|
|
63
|
-
`,ba=r=>new Error(`failed to compile webgl program: ${r}`),Sv=new Error("null shader encountered");let dl=class{renderCtx;prog;vertShader;fragShader;uniformLocCache=new Map;constructor(e,t,n){this.renderCtx=e;const a=e.gl.createProgram();if(a==null)throw ba("failed to create program");this.prog=a,this.vertShader=t,this.fragShader=n,this.compile()}setAsActive(){return this.renderCtx.gl.useProgram(this.prog),()=>this.renderCtx.gl.useProgram(null)}uniformXY(e,t){this.renderCtx.gl.uniform2fv(this.getUniformLoc(e),f.K.couple(t))}uniformColor(e,t){this.renderCtx.gl.uniform4fv(this.getUniformLoc(e),f.ir.rgba1(t))}getUniformLoc(e){const t=this.uniformLocCache.get(e);if(t!=null)return t;const n=this.renderCtx.gl.getUniformLocation(this.prog,e);if(n==null)throw new Error(`unexpected missing uniform ${e}`);return this.uniformLocCache.set(e,n),n}compile(){const e=this.renderCtx.gl;this.compileShader(this.vertShader,e.VERTEX_SHADER),this.compileShader(this.fragShader,e.FRAGMENT_SHADER),e.linkProgram(this.prog)}compileShader(e,t){const n=this.renderCtx.gl,a=n.createShader(t);if(a==null)throw Sv;if(n.shaderSource(a,e),n.compileShader(a),!n.getShaderParameter(a,n.COMPILE_STATUS)){const o=n.getShaderInfoLog(a);throw n.deleteShader(a),ba(o??"unknown")}n.attachShader(this.prog,a)}};const zv=new Float32Array([0,0,0,0,0,0]);class Ev extends dl{positionBuffer;constructor(e){super(e,Ov,Tv);const t=e.gl.createBuffer();if(t==null)throw new W("webgl: failed to create buffer");this.positionBuffer=t,e.gl.bindBuffer(e.gl.ARRAY_BUFFER,this.positionBuffer),e.gl.bufferData(e.gl.ARRAY_BUFFER,zv,e.gl.STATIC_DRAW)}exec(){const{gl:e}=this.renderCtx,t=e.getAttribLocation(this.prog,"a_position");e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer);const n=e.createVertexArray();e.bindVertexArray(n),e.enableVertexAttribArray(t),e.vertexAttribPointer(t,2,e.FLOAT,!1,0,0),this.setAsActive(),e.drawArrays(e.TRIANGLES,0,3)}}const va={high:1,low:0};class fl{requests=new Map;cleanup=new Map;afterRender;instrumentation;handleError;constructor({afterRender:e,instrumentation:t=ke.Instrumentation.NOOP,handleError:n}){this.afterRender=e,this.instrumentation=t,this.handleError=n,this.start()}set(e){const t=this.requests.get(e.key);if(t==null)this.requests.set(e.key,e);else{const n=va[e.priority]>=va[t.priority],a=e.canvases.length>=t.canvases.length;n&&a&&this.requests.set(e.key,e)}}render(){const{requests:e}=this;e.size!==0&&(this.runCleanupsSync(),this.renderSync(),this.requests.clear(),this.afterRender?.())}runCleanupsSync(){const{cleanup:e,requests:t}=this;e.forEach((n,a)=>{const i=t.get(a);i!=null&&(n(i),e.delete(a))})}renderSync(){const{requests:e}=this;e.forEach(t=>{try{const n=t.render();n!=null&&this.cleanup.set(t.key,n)}catch(n){this.handleError(n,"render loop failed")}})}start(){const e=()=>{try{this.render()}catch(t){this.handleError(t,"render loop failed")}requestAnimationFrame(e)};requestAnimationFrame(e)}}const ir=2,he=2;class zs{atlas;charDims;charMap;static DEFAULT_CHARS="0123456789.:-µmsNa∞ᴇ";constructor(e){const{font:t,characters:n=zs.DEFAULT_CHARS,textColor:a}=e;this.charMap=new Map;const i=f.c.unique(Array.from(n)),l=new OffscreenCanvas(1,1).getContext("2d");l.font=t;const c=l.measureText("0");this.charDims=Mr(c),this.charDims.width+=ir,this.charDims.height+=ir;const u=i.length,d=this.charDims.width,h=this.charDims.height,b=Math.ceil(Math.sqrt(u)),S=Math.ceil(u/b);this.atlas=new OffscreenCanvas(d*b*he,h*(S+1)*he);const R=this.atlas.getContext("2d");R.scale(he,he),R.font=t,R.textBaseline="alphabetic",R.textAlign="left",R.fillStyle=f.ir.hex(a),R.clearRect(0,0,this.atlas.width,this.atlas.height),i.forEach((A,B)=>{const x=B%b,M=Math.floor(B/b),re=x*d,Q=(M+1)*h;R.fillText(A,re,Q),this.charMap.set(A,B)})}fillText(e,t,n,a){const{width:i,height:o}=this.charDims,l=Math.ceil(Math.sqrt(this.charMap.size));for(let c=0;c<t.length;c++){const u=t[c],d=this.charMap.get(u);if(d===void 0)continue;const h=d%l,b=Math.floor(d/l);e.drawImage(this.atlas,h*i*he,b*o*he+ir,i*he,o*he,n+c*i,a-o-ir/he,i,o)}}measureText(e){return{width:e.length*this.charDims.width,height:this.charDims.height}}}class Nv{atlases;constructor(){this.atlases=new Map}get(e){const t=`${e.font}-${f.ir.hex(e.textColor)}-${e.characters}`;if(this.atlases.has(t))return this.atlases.get(t);const n=new zs(e);return this.atlases.set(t,n),n}}const Ta=r=>(r.textRendering="optimizeSpeed",r.imageSmoothingEnabled=!1,r);class Ne{glCanvas;upper2dCanvas;lower2dCanvas;gl;lower2d;upper2d;region;dpr;loop;clearProgram;os;static CONTEXT_KEY=f.CSS.B("render-context");instrumentation;static create(e,t,n,a,i){const o=hl(e,"render_context"),l=new Ne(t,n,a,i,o,Os(e),Ss(e));return e.set(Ne.CONTEXT_KEY,l),l}constructor(e,t,n,a,i,o,l){this.upper2dCanvas=n,this.lower2dCanvas=t,this.glCanvas=e,this.os=a,this.instrumentation=i,this.dpr=1;const c=this.lower2dCanvas.getContext("2d");if(c==null)throw new Error("Could not get 2D context");const u=new Nv;this.lower2d=Ta(new Or(c,u,this.dpr));const d=this.upper2dCanvas.getContext("2d");if(d==null)throw new Error("Could not get 2D context");this.upper2d=Ta(new Or(d,u,this.dpr));const h={preserveDrawingBuffer:!0,powerPreference:"high-performance",stencil:!1,depth:!1},b=this.glCanvas.getContext("webgl2",h);if(b==null)throw new Error("Could not get WebGL context");b.disable(b.DEPTH_TEST),b.disable(b.STENCIL_TEST),b.disable(b.CULL_FACE),b.disable(b.DITHER),this.gl=b,this.glCanvas.oncontextlost=()=>o({variant:"error",message:"WebGL context lost"});const S=()=>{this.gl.flush(),this.gl.finish()};this.loop=new fl({afterRender:S,instrumentation:this.instrumentation,handleError:l}),this.region=f.Ho.ZERO,this.os==="Windows"&&(this.clearProgram=new Ev(this))}static useOptional(e){return e.getOptional(Ne.CONTEXT_KEY)}static use(e){return e.get(Ne.CONTEXT_KEY)}update(e){e.set(Ne.CONTEXT_KEY,this)}resize(e,t){f.Ho.equals(this.region,e)&&this.dpr===t||(this.region=e,this.dpr=t,this.resizeCanvas(this.glCanvas),this.resizeCanvas(this.upper2dCanvas),this.resizeCanvas(this.lower2dCanvas),this.lower2d.scale(this.dpr,this.dpr),this.upper2d.scale(this.dpr,this.dpr),this.gl.viewport(0,0,f.Ho.width(e)*t,f.Ho.height(e)*t))}resizeCanvas(e){e.width=f.Ho.width(this.region)*this.dpr,e.height=f.Ho.height(this.region)*this.dpr}get aspect(){return f.Ho.aspect(this.region)}scaleRegion(e){return new f.C.XY(f.C.Scale.scale(0,1).scale(f.Ho.width(e)).translate(f.Ho.left(e)).reBound(f.Ho.width(this.region)).scale(-1,1),f.C.Scale.scale(0,1).scale(f.Ho.height(e)).invert().translate(f.Ho.top(e)).reBound(f.Ho.height(this.region)).scale(-1,1).invert())}scissor(e,t=f.K.ZERO,n){const a=[];return n.includes("upper2d")&&a.push(this.upper2d.scissor(e,t)),n.includes("lower2d")&&a.push(this.lower2d.scissor(e,t)),n.includes("gl")&&a.push(this.scissorGL(e,t)),()=>a.forEach(i=>i())}scissorGL(e,t=f.K.ZERO){return this.gl.enable(this.gl.SCISSOR_TEST),e=fr(e,t),this.gl.scissor(f.Ho.left(e)*this.dpr,(f.Ho.height(this.region)-f.Ho.bottom(e))*this.dpr,f.Ho.width(e)*this.dpr,f.Ho.height(e)*this.dpr),()=>this.gl.disable(this.gl.SCISSOR_TEST)}erase(e,t=f.K.ZERO,...n){t=f.K.construct(t),n.length===0&&(n=["upper2d","lower2d","gl"]),n.includes("upper2d")&&this.eraseCanvas(this.upper2d,e,t),n.includes("lower2d")&&this.eraseCanvas(this.lower2d,e,t),n.includes("gl")&&this.eraseGL(e,t)}eraseGL(e,t=f.K.ZERO){const{gl:n}=this,a=this.scissorGL(fr(e,t));n.clearColor(...f.ir.rgba1(f.ir.ZERO)),n.clear(n.COLOR_BUFFER_BIT),this.os==="Windows"&&this.clearProgram?.exec(),a()}eraseCanvas(e,t,n=f.K.ZERO){const a=fr(t,n);e.clearRect(...f.K.couple(f.Ho.topLeft(a)),...f._.couple(f.Ho.dims(a)))}}const pl=s.z.object({region:f.Ho.box,enabled:s.z.boolean().optional().default(!1)}),Oa=["gl","lower2d","upper2d"];class $n extends Pr{static TYPE="eraser";schema=pl;afterUpdate(e){this.deleted||(this.internal.renderCtx=Ne.use(e),this.renderOnLifecycleChange())}afterDelete(){this.renderOnLifecycleChange()}renderOnLifecycleChange(){this.internal.renderCtx.loop.set({key:`${this.type}-${this.key}`,render:this.render.bind(this),priority:"high",canvases:Oa})}render(){this.deleted||!this.state.enabled||this.internal.renderCtx.erase(this.state.region,f.K.construct(0),...Oa)}}const Av={[$n.TYPE]:$n};exports.$=N;exports.Aggregator=Ln;exports.COMPONENT_SIZE_LEVELS=yb;exports.Composite=gt;exports.Context=Ne;exports.Eraser=$n;exports.Ft=st;exports.GLProgram=dl;exports.Gm=Zg;exports.Km=zm;exports.Kp=Fo;exports.LEVELS=kt;exports.LEVEL_COMPONENT_SIZES=gb;exports.Leaf=Pr;exports.Lm=Sy;exports.Loop=fl;exports.Nm=Nf;exports.O=lt;exports.O$1=z;exports.P=$;exports.Provider=Pn;exports.Provider$1=Bn;exports.REGISTRY=wv;exports.REGISTRY$1=yv;exports.REGISTRY$2=Av;exports.REGISTRY$3=bv;exports.S=E;exports.SIZES=Qo;exports.SYNNAX_DARK=Xo;exports.SYNNAX_LIGHT=Jo;exports.SYNNAX_THEMES=Nb;exports.Vm=ng;exports.Xp=_w;exports.Zm=my;exports._=ot;exports._m=zg;exports.aether=fv;exports.aggregatorStateZ=il;exports.be=tl;exports.c=ms;exports.createErrorHandler=ol;exports.d=ab;exports.dimensions=hb;exports.dimensionsFromMetrics=Mr;exports.downLevel=fb;exports.eraserStateZ=pl;exports.executeInitialSetter=Jt;exports.executeSetter=ws;exports.f=Zo;exports.fontSpecZ=ll;exports.g=ke;exports.isSize=Ab;exports.iw=Yw;exports.ke=je;exports.levelZ=db;exports.lt=W;exports.m=_o;exports.o=Ww;exports.prettyParse=In;exports.providerStateZ=ul;exports.r=Gw;exports.render=al;exports.size=el;exports.specZ=Ee;exports.state=cb;exports.t=Hw;exports.themeZ=Ko;exports.use=mv;exports.useAdder=Os;exports.useErrorHandler=Ss;exports.useInstrumentation=hl;exports.useOptionalAdder=pv;exports.usePassthrough=Wo;exports.usePurePassthrough=Go;exports.weightZ=pb;exports.wm=Hd;exports.xm=fp;exports.zm=$y;
|