@synnaxlabs/freighter 0.40.0 → 0.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/alamos.d.ts.map +1 -1
- package/dist/errors.d.ts +18 -87
- package/dist/errors.d.ts.map +1 -1
- package/dist/freighter.cjs +9 -9
- package/dist/freighter.js +2101 -991
- package/dist/http.d.ts +1 -1
- package/dist/http.d.ts.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/unary.d.ts +2 -2
- package/dist/unary.d.ts.map +1 -1
- package/dist/websocket.d.ts +8 -1
- package/dist/websocket.d.ts.map +1 -1
- package/package.json +9 -8
- package/src/alamos.ts +4 -3
- package/src/errors.spec.ts +6 -73
- package/src/errors.ts +20 -168
- package/src/http.ts +19 -12
- package/src/index.ts +2 -14
- package/src/unary.ts +7 -6
- package/src/websocket.spec.ts +9 -17
- package/src/websocket.ts +51 -29
package/dist/alamos.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alamos.d.ts","sourceRoot":"","sources":["../src/alamos.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAE1D,OAAO,
|
|
1
|
+
{"version":3,"file":"alamos.d.ts","sourceRoot":"","sources":["../src/alamos.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAE1D,OAAO,EAAgB,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAE7D,eAAO,MAAM,UAAU,GACpB,iBAAiB,eAAe,KAAG,UAenC,CAAC"}
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,103 +1,34 @@
|
|
|
1
|
-
import { URL } from '@synnaxlabs/x';
|
|
2
|
-
|
|
3
|
-
/** Basic interface for an error or error type that can be matched against a candidate error */
|
|
4
|
-
export interface MatchableErrorType {
|
|
5
|
-
/**
|
|
6
|
-
* @returns a function that matches errors of the given type. Returns true if
|
|
7
|
-
* the provided instance of Error or a string message contains the provided error type.
|
|
8
|
-
*/
|
|
9
|
-
matches: (e: string | Error | unknown) => boolean;
|
|
10
|
-
}
|
|
11
|
-
export interface TypedError extends Error {
|
|
12
|
-
discriminator: "FreighterError";
|
|
13
|
-
/**
|
|
14
|
-
* @description Returns a unique type identifier for the error. Freighter uses this to
|
|
15
|
-
* determine the correct decoder to use on the other end of the freighter.
|
|
16
|
-
*/
|
|
17
|
-
type: string;
|
|
18
|
-
}
|
|
1
|
+
import { errors, URL } from '@synnaxlabs/x';
|
|
2
|
+
declare const FreighterError_base: errors.TypedClass;
|
|
19
3
|
/**
|
|
20
|
-
* @
|
|
21
|
-
* @returns a function that matches errors of the given type. Returns true if
|
|
22
|
-
* the provided instance of Error or a string message contains the provided error type.
|
|
4
|
+
* @description Base class for all freighter-specific errors
|
|
23
5
|
*/
|
|
24
|
-
export declare
|
|
25
|
-
export declare class BaseTypedError extends Error implements TypedError {
|
|
26
|
-
readonly discriminator = "FreighterError";
|
|
27
|
-
type: string;
|
|
6
|
+
export declare class FreighterError extends FreighterError_base {
|
|
28
7
|
}
|
|
29
|
-
|
|
30
|
-
type ErrorEncoder = (error: TypedError) => ErrorPayload | null;
|
|
31
|
-
export declare const isTypedError: (error: unknown) => error is TypedError;
|
|
32
|
-
export declare const assertErrorType: <T>(type: string, error?: Error | null) => T;
|
|
33
|
-
export declare const UNKNOWN = "unknown";
|
|
34
|
-
export declare const NONE = "nil";
|
|
35
|
-
export declare const FREIGHTER = "freighter";
|
|
36
|
-
export declare const errorZ: z.ZodObject<{
|
|
37
|
-
type: z.ZodString;
|
|
38
|
-
data: z.ZodString;
|
|
39
|
-
}, "strip", z.ZodTypeAny, {
|
|
40
|
-
type: string;
|
|
41
|
-
data: string;
|
|
42
|
-
}, {
|
|
43
|
-
type: string;
|
|
44
|
-
data: string;
|
|
45
|
-
}>;
|
|
46
|
-
export type ErrorPayload = z.infer<typeof errorZ>;
|
|
47
|
-
/**
|
|
48
|
-
* Registers a custom error type with the error registry, which allows it to be
|
|
49
|
-
* encoded/decoded and sent over the network.
|
|
50
|
-
*
|
|
51
|
-
* @param type - A unique string identifier for the error type.
|
|
52
|
-
* @param encode - A function that encodes the error into a string.
|
|
53
|
-
* @param decode - A function that decodes the error from a string.
|
|
54
|
-
*/
|
|
55
|
-
export declare const registerError: ({ encode, decode, }: {
|
|
56
|
-
encode: ErrorEncoder;
|
|
57
|
-
decode: ErrorDecoder;
|
|
58
|
-
}) => void;
|
|
59
|
-
/**
|
|
60
|
-
* Encodes an error into a payload that can be sent between a freighter server
|
|
61
|
-
* and client.
|
|
62
|
-
* @param error - The error to encode.
|
|
63
|
-
* @returns The encoded error.
|
|
64
|
-
*/
|
|
65
|
-
export declare const encodeError: (error: unknown) => ErrorPayload;
|
|
8
|
+
declare const EOF_base: errors.TypedClass;
|
|
66
9
|
/**
|
|
67
|
-
*
|
|
68
|
-
* for the error type, it will be used. Otherwise, a generic Error containing
|
|
69
|
-
* the error data is returned.
|
|
70
|
-
*
|
|
71
|
-
* @param payload - The encoded error payload.
|
|
72
|
-
* @returns The decoded error.
|
|
10
|
+
* @description Error thrown when reaching the end of a file or stream
|
|
73
11
|
*/
|
|
74
|
-
export declare
|
|
75
|
-
export declare class UnknownError extends BaseTypedError implements TypedError {
|
|
76
|
-
type: string;
|
|
77
|
-
}
|
|
78
|
-
/** Thrown/returned when a stream closed normally. */
|
|
79
|
-
export declare class EOF extends BaseTypedError implements TypedError {
|
|
80
|
-
static readonly TYPE = "freighter.eof";
|
|
81
|
-
type: string;
|
|
82
|
-
static readonly matches: (e: string | Error | unknown) => boolean;
|
|
12
|
+
export declare class EOF extends EOF_base {
|
|
83
13
|
constructor();
|
|
84
14
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
15
|
+
declare const StreamClosed_base: errors.TypedClass;
|
|
16
|
+
/**
|
|
17
|
+
* @description Error thrown when attempting to operate on a closed stream
|
|
18
|
+
*/
|
|
19
|
+
export declare class StreamClosed extends StreamClosed_base {
|
|
90
20
|
constructor();
|
|
91
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* @description Arguments for constructing an Unreachable error
|
|
24
|
+
*/
|
|
92
25
|
export interface UnreachableArgs {
|
|
93
26
|
message?: string;
|
|
94
27
|
url?: URL;
|
|
95
28
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
type: string;
|
|
100
|
-
static readonly matches: (e: string | Error | unknown) => boolean;
|
|
29
|
+
declare const Unreachable_base: errors.TypedClass;
|
|
30
|
+
/** @description Thrown when a network target is unreachable. */
|
|
31
|
+
export declare class Unreachable extends Unreachable_base {
|
|
101
32
|
url: URL;
|
|
102
33
|
constructor(args?: UnreachableArgs);
|
|
103
34
|
}
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;;AAE5C;;GAEG;AACH,qBAAa,cAAe,SAAQ,mBAA+B;CAAG;;AAEtE;;GAEG;AACH,qBAAa,GAAI,SAAQ,QAAyB;;CAIjD;;AAED;;GAEG;AACH,qBAAa,YAAa,SAAQ,iBAAmC;;CAIpE;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,GAAG,CAAC;CACX;;AAED,gEAAgE;AAChE,qBAAa,WAAY,SAAQ,gBAAiC;IAChE,GAAG,EAAE,GAAG,CAAC;gBAEG,IAAI,GAAE,eAAoB;CAKvC"}
|
package/dist/freighter.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var dt=Object.defineProperty;var ft=(r,e,t)=>e in r?dt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var y=(r,e,t)=>ft(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("zod"),gt=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)},Ve=r=>{const e=(t,n=pe)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!he(t))return t;n=mt(n);const s={},a=t;return Object.keys(a).forEach(c=>{let d=a[c];const f=r(c);n.recursive&&(he(d)?Ae(d,n.keepTypesOnRecursion)||(d=e(d,n)):n.recursiveInArray&&Ee(d)&&(d=[...d].map(p=>{let m=p;return he(p)?Ae(m,n.keepTypesOnRecursion)||(m=e(p,n)):Ee(p)&&(m=e({key:p},n).key),m}))),s[f]=d}),s};return e},Ze=Ve(gt),pt=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),yt=Ve(pt),pe={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},mt=(r=pe)=>(r.recursive==null?r=pe:r.recursiveInArray??(r.recursiveInArray=!1),r),Ee=r=>r!=null&&Array.isArray(r),he=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Ae=(r,e)=>(e||[]).some(t=>r instanceof t),Je=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var wt=Object.defineProperty,bt=(r,e,t)=>e in r?wt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,_=(r,e,t)=>bt(r,typeof e!="symbol"?e+"":e,t);let Tt=class{constructor(){_(this,"contentType","application/json"),_(this,"decoder"),_(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),s=Ze(n);return t!=null?t.parse(s):s}encodeString(e){const t=yt(e);return JSON.stringify(t,(n,s)=>ArrayBuffer.isView(s)?Array.from(s):Je(s)&&"encode_value"in s?typeof s.value=="bigint"?s.value.toString():s.value:typeof s=="bigint"?s.toString():s)}static registerCustomType(){}},Ot=class{constructor(){_(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Je(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(s=>{const a=t.map(c=>JSON.stringify(s[c]??""));n.push(a.join(","))}),n.join(`
|
|
2
|
-
`)}decodeString(e,t){const[n
|
|
3
|
-
`).map(d=>d.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(d=>d.trim()),c={};return a.forEach(d=>{c[d]=[]}),s.forEach(d=>{const f=d.split(",").map(p=>p.trim());a.forEach((p,m)=>{const l=this.parseValue(f[m]);l!=null&&c[p].push(l)})}),t!=null?t.parse(c):c}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},vt=class{constructor(){_(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const re=new Tt;new Ot;new vt;const St=r=>r!=null&&typeof r=="object"&&"toString"in r,It=(r,e=!1)=>{const t=St(r)?"stringer":typeof r;let n;switch(t){case"string":n=(s,a)=>s.localeCompare(a);break;case"stringer":n=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":n=(s,a)=>Number(s)-Number(a);break;case"bigint":n=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":n=(s,a)=>Number(s)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Nt(n):n},Nt=r=>(e,t)=>r(t,e),ue=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const He=i.z.object({width:i.z.number(),height:i.z.number()}),Et=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),At=["width","height"];i.z.enum(At);const xt=["start","center","end"],zt=["signedWidth","signedHeight"];i.z.enum(zt);const ie=i.z.object({x:i.z.number(),y:i.z.number()}),Mt=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),$t=["x","y"],Xe=i.z.enum($t),Ke=["top","right","bottom","left"];i.z.enum(Ke);const Ut=["left","right"],Qe=i.z.enum(Ut),Bt=["top","bottom"],_e=i.z.enum(Bt),et=["center"],xe=i.z.enum(et),Rt=[...Ke,...et],tt=i.z.enum(Rt);i.z.enum(xt);const Ct=["first","last"];i.z.enum(Ct);const Dt=i.z.object({lower:i.z.number(),upper:i.z.number()}),Pt=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([Dt,ue]);i.z.union([Pt,ue]);i.z.enum([...Xe.options,...tt.options]);i.z.union([Xe,tt,i.z.instanceof(String)]);const Lt=r=>typeof r=="bigint"||r instanceof BigInt,q=(r,e)=>Lt(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),j=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return ze(r);return ze(t)},ze=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Me=(r,e)=>{const t=j(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};i.z.object({x:Qe.or(xe),y:_e.or(xe)});const Yt=i.z.object({x:Qe,y:_e}),kt=Object.freeze({x:"left",y:"top"}),jt=(r,e)=>r.x===e.x&&r.y===e.y,$e=i.z.union([i.z.number(),ie,ue,He,Et,Mt]),qt=(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}},Ue=Object.freeze({x:0,y:0}),te=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:te,left:te,width:te,height:te});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:ie,two:ie,root:Yt});const ve=(r,e,t=0,n=0,s)=>{const a={one:{...Ue},two:{...Ue},root:s??kt};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:s??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},de=r=>{const e=ve(r);return{lower:e.one.x,upper:e.two.x}},fe=r=>{const e=ve(r);return{lower:e.one.y,upper:e.two.y}},Ft=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,Gt=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([He,Gt,ie,ue]);var Wt=Object.defineProperty,Vt=(r,e,t)=>e in r?Wt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,D=(r,e,t)=>Vt(r,typeof e!="symbol"?e+"":e,t);const Zt=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;i.z.object({offset:$e,scale:$e});i.z.object({offset:i.z.number(),scale:i.z.number()});const Jt=r=>(e,t,n,s)=>t==="dimension"?[e,n]:[e,s?n-r:n+r],Ht=r=>(e,t,n,s)=>[e,s?n/r:n*r],Xt=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:s,upper:a}=e,{lower:c,upper:d}=r,f=a-s,p=d-c;if(t==="dimension")return[r,n*(p/f)];const m=(n-s)*(p/f)+c;return[r,m]},Kt=r=>(e,t,n)=>[r,n],Qt=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:s}=r;return[r,s-(t-n)]},_t=r=>(e,t,n)=>{const{lower:s,upper:a}=r;return n=Zt(n,s,a),[e,n]},ye=class V{constructor(){D(this,"ops",[]),D(this,"currBounds",null),D(this,"currType",null),D(this,"reversed",!1),this.ops=[]}static translate(e){return new V().translate(e)}static magnify(e){return new V().magnify(e)}static scale(e,t){return new V().scale(e,t)}translate(e){const t=this.new(),n=Jt(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Ht(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=j(e,t),s=this.new(),a=Xt(n);return a.type="scale",s.ops.push(a),s}clamp(e,t){const n=j(e,t),s=this.new(),a=_t(n);return a.type="clamp",s.ops.push(a),s}reBound(e,t){const n=j(e,t),s=this.new(),a=Kt(n);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Qt();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 V;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,s],a)=>a(n,e,s,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,s)=>{if(n.type==="scale"||t.some(([c,d])=>s>=c&&s<=d))return;const a=e.ops.findIndex((c,d)=>c.type==="scale"&&d>s);a!==-1&&t.push([s,a])}),t.forEach(([n,s])=>{const a=e.ops.slice(n,s);a.unshift(e.ops[s]),e.ops.splice(n,s-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};D(ye,"IDENTITY",new ye);let Be=ye;const Re=class C{constructor(e=new Be,t=new Be,n=null){D(this,"x"),D(this,"y"),D(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new C().translate(e,t)}static translateX(e){return new C().translateX(e)}static translateY(e){return new C().translateY(e)}static clamp(e){return new C().clamp(e)}static magnify(e){return new C().magnify(e)}static scale(e){return new C().scale(e)}static reBound(e){return new C().reBound(e)}translate(e,t){const n=qt(e,t),s=this.copy();return s.x=this.x.translate(n.x),s.y=this.y.translate(n.y),s}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(Ft(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!jt(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(de(e)),t.y=t.y.scale(fe(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(de(e)),t.y=this.y.reBound(fe(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(de(e)),t.y=this.y.clamp(fe(e)),t}copy(){const e=new C;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 ve(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})}}};D(Re,"IDENTITY",new Re);var er=Object.defineProperty,tr=(r,e,t)=>e in r?er(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,u=(r,e,t)=>tr(r,typeof e!="symbol"?e+"":e,t);let rr=(r,e=21)=>(t=e)=>{let n="",s=t|0;for(;s--;)n+=r[Math.random()*r.length|0];return n};const nr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",sr=rr(nr,11),ir=()=>sr(),ar=i.z.enum(["static","dynamic"]),rt=(r,e)=>{const t=new v(e);if(![O.DAY,O.HOUR,O.MINUTE,O.SECOND,O.MILLISECOND,O.MICROSECOND,O.NANOSECOND].some(s=>s.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 v?new v(n):new O(n)},b=class h{constructor(e,t="UTC"){if(u(this,"value"),u(this,"encodeValue",!0),e==null)this.value=h.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*h.MILLISECOND.valueOf();else if(typeof e=="string")this.value=h.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=h.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=h.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=h.MAX:e=h.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const s=new Date(e,t-1,n,0,0,0,0);return new h(BigInt(s.getTime())*h.MILLISECOND.valueOf()).truncate(h.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,s,a]=e.split(":");let c="00",d="00";a!=null&&([c,d]=a.split("."));let f=h.hours(parseInt(n??"00")).add(h.minutes(parseInt(s??"00"))).add(h.seconds(parseInt(c??"00"))).add(h.milliseconds(parseInt(d??"00")));return t==="local"&&(f=f.add(h.utcOffset)),f.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return h.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new h(BigInt(n.getTime())*h.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(h.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 O(BigInt(new Date().getTimezoneOffset())*h.MINUTE.valueOf())}static since(e){return new h().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new h(e).valueOf()}span(e){return this.range(e).span}range(e){return new Se(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new h(e).valueOf()}afterEq(e){return this.valueOf()>=new h(e).valueOf()}before(e){return this.valueOf()<new h(e).valueOf()}beforeEq(e){return this.valueOf()<=new h(e).valueOf()}add(e){return new h(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new h(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(O.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(O.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(O.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(O.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(h.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new h(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new h(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new h(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new h(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new h(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new h(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new h(t)}toString(){return this.date().toISOString()}remainder(e){return rt(this,e)}get isToday(){return this.truncate(O.DAY).equals(h.now().truncate(O.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new h(new Date)}static max(...e){let t=h.MIN;for(const n of e){const s=new h(n);s.after(t)&&(t=s)}return t}static min(...e){let t=h.MAX;for(const n of e){const s=new h(n);s.before(t)&&(t=s)}return t}static nanoseconds(e){return new h(e)}static microseconds(e){return h.nanoseconds(e*1e3)}static milliseconds(e){return h.microseconds(e*1e3)}static seconds(e){return h.milliseconds(e*1e3)}static minutes(e){return h.seconds(e*60)}static hours(e){return h.minutes(e*60)}static days(e){return h.hours(e*24)}};u(b,"NANOSECOND",b.nanoseconds(1)),u(b,"MICROSECOND",b.microseconds(1)),u(b,"MILLISECOND",b.milliseconds(1)),u(b,"SECOND",b.seconds(1)),u(b,"MINUTE",b.minutes(1)),u(b,"HOUR",b.hours(1)),u(b,"DAY",b.days(1)),u(b,"MAX",new b((1n<<63n)-1n)),u(b,"MIN",new b(0)),u(b,"ZERO",new b(0)),u(b,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new b(r.value)),i.z.string().transform(r=>new b(BigInt(r))),i.z.instanceof(Number).transform(r=>new b(r)),i.z.number().transform(r=>new b(r)),i.z.instanceof(b)]));let v=b;const T=class g{constructor(e){u(this,"value"),u(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof g?e:e instanceof Ce?e.period:e instanceof v?new g(e):["number","bigint"].includes(typeof e)?g.seconds(e):new g(e)}static fromMilliseconds(e){return e instanceof g?e:e instanceof Ce?e.period:e instanceof v?new g(e):["number","bigint"].includes(typeof e)?g.milliseconds(e):new g(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new g(e).valueOf()}greaterThan(e){return this.valueOf()>new g(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new g(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new g(e).valueOf()}remainder(e){return rt(this,e)}truncate(e){return new g(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(g.DAY),t=this.truncate(g.HOUR),n=this.truncate(g.MINUTE),s=this.truncate(g.SECOND),a=this.truncate(g.MILLISECOND),c=this.truncate(g.MICROSECOND),d=this.truncate(g.NANOSECOND),f=e,p=t.sub(e),m=n.sub(t),l=s.sub(n),N=a.sub(s),M=c.sub(a),B=d.sub(c);let z="";return f.isZero||(z+=`${f.days}d `),p.isZero||(z+=`${p.hours}h `),m.isZero||(z+=`${m.minutes}m `),l.isZero||(z+=`${l.seconds}s `),N.isZero||(z+=`${N.milliseconds}ms `),M.isZero||(z+=`${M.microseconds}µs `),B.isZero||(z+=`${B.nanoseconds}ns`),z.trim()}mult(e){return new g(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(g.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(g.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(g.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(g.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(g.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(g.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new g(e).valueOf()}add(e){return new g(this.valueOf()+new g(e).valueOf())}sub(e){return new g(this.valueOf()-new g(e).valueOf())}static nanoseconds(e=1){return new g(e)}static microseconds(e=1){return g.nanoseconds(q(e,1e3))}static milliseconds(e=1){return g.microseconds(q(e,1e3))}static seconds(e=1){return g.milliseconds(q(e,1e3))}static minutes(e=1){return g.seconds(q(e,60))}static hours(e){return g.minutes(q(e,60))}static days(e){return g.hours(q(e,24))}};u(T,"NANOSECOND",T.nanoseconds(1)),u(T,"MICROSECOND",T.microseconds(1)),u(T,"MILLISECOND",T.milliseconds(1)),u(T,"SECOND",T.seconds(1)),u(T,"MINUTE",T.minutes(1)),u(T,"HOUR",T.hours(1)),u(T,"DAY",T.days(1)),u(T,"MAX",new T((1n<<63n)-1n)),u(T,"MIN",new T(0)),u(T,"ZERO",new T(0)),u(T,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new T(r.value)),i.z.string().transform(r=>new T(BigInt(r))),i.z.instanceof(Number).transform(r=>new T(r)),i.z.number().transform(r=>new T(r)),i.z.instanceof(T)]));let O=T;const Z=class ne extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new ne(e).valueOf()}get period(){return O.seconds(1/this.valueOf())}sampleCount(e){return new O(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new x(t).valueOf()}span(e){return O.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new ne(e)}static khz(e){return ne.hz(e*1e3)}};u(Z,"z",i.z.union([i.z.number().transform(r=>new Z(r)),i.z.instanceof(Number).transform(r=>new Z(r)),i.z.instanceof(Z)]));let Ce=Z;const E=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new me(e*this.valueOf())}};u(E,"UNKNOWN",new E(0)),u(E,"BIT128",new E(16)),u(E,"BIT64",new E(8)),u(E,"BIT32",new E(4)),u(E,"BIT16",new E(2)),u(E,"BIT8",new E(1)),u(E,"z",i.z.union([i.z.number().transform(r=>new E(r)),i.z.instanceof(Number).transform(r=>new E(r)),i.z.instanceof(E)]));let x=E;const $=class se{constructor(e,t){u(this,"start"),u(this,"end"),typeof e=="object"&&"start"in e?(this.start=new v(e.start),this.end=new v(e.end)):(this.start=new v(e),this.end=new v(t))}get span(){return new O(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 se(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=O.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 s=v.max(n.start,e.start),a=v.min(n.end,e.end);return a.before(s)?!1:new O(a.sub(s)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return n<0&&(n=-n),s<0&&(s=-s),n<=t.valueOf()&&s<=t.valueOf()}contains(e){return e instanceof se?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new se(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}};u($,"MAX",new $(v.MIN,v.MAX)),u($,"MIN",new $(v.MAX,v.MIN)),u($,"ZERO",new $(v.ZERO,v.ZERO)),u($,"z",i.z.union([i.z.object({start:v.z,end:v.z}).transform(r=>new $(r.start,r.end)),i.z.instanceof($)]));let Se=$;const o=class S extends String{constructor(e){if(e instanceof S||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=S.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(S.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=S.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(S.JSON)||this.equals(S.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(S.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=S.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(S.UINT8)||this.equals(S.UINT16)||this.equals(S.UINT32)||this.equals(S.UINT64)}get isSigned(){return this.equals(S.INT8)||this.equals(S.INT16)||this.equals(S.INT32)||this.equals(S.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(S.INT32)&&e.equals(S.FLOAT64)||this.equals(S.INT8)&&e.equals(S.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return S.BIG_INT_TYPES.some(e=>e.equals(this))}};u(o,"UNKNOWN",new o("unknown")),u(o,"FLOAT64",new o("float64")),u(o,"FLOAT32",new o("float32")),u(o,"INT64",new o("int64")),u(o,"INT32",new o("int32")),u(o,"INT16",new o("int16")),u(o,"INT8",new o("int8")),u(o,"UINT64",new o("uint64")),u(o,"UINT32",new o("uint32")),u(o,"UINT16",new o("uint16")),u(o,"UINT8",new o("uint8")),u(o,"BOOLEAN",o.UINT8),u(o,"TIMESTAMP",new o("timestamp")),u(o,"UUID",new o("uuid")),u(o,"STRING",new o("string")),u(o,"JSON",new o("json")),u(o,"ARRAY_CONSTRUCTORS",new Map([[o.UINT8.toString(),Uint8Array],[o.UINT16.toString(),Uint16Array],[o.UINT32.toString(),Uint32Array],[o.UINT64.toString(),BigUint64Array],[o.FLOAT32.toString(),Float32Array],[o.FLOAT64.toString(),Float64Array],[o.INT8.toString(),Int8Array],[o.INT16.toString(),Int16Array],[o.INT32.toString(),Int32Array],[o.INT64.toString(),BigInt64Array],[o.TIMESTAMP.toString(),BigInt64Array],[o.STRING.toString(),Uint8Array],[o.JSON.toString(),Uint8Array],[o.UUID.toString(),Uint8Array]])),u(o,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,o.UINT8],[Uint16Array.name,o.UINT16],[Uint32Array.name,o.UINT32],[BigUint64Array.name,o.UINT64],[Float32Array.name,o.FLOAT32],[Float64Array.name,o.FLOAT64],[Int8Array.name,o.INT8],[Int16Array.name,o.INT16],[Int32Array.name,o.INT32],[BigInt64Array.name,o.INT64]])),u(o,"DENSITIES",new Map([[o.UINT8.toString(),x.BIT8],[o.UINT16.toString(),x.BIT16],[o.UINT32.toString(),x.BIT32],[o.UINT64.toString(),x.BIT64],[o.FLOAT32.toString(),x.BIT32],[o.FLOAT64.toString(),x.BIT64],[o.INT8.toString(),x.BIT8],[o.INT16.toString(),x.BIT16],[o.INT32.toString(),x.BIT32],[o.INT64.toString(),x.BIT64],[o.TIMESTAMP.toString(),x.BIT64],[o.STRING.toString(),x.UNKNOWN],[o.JSON.toString(),x.UNKNOWN],[o.UUID.toString(),x.BIT128]])),u(o,"ALL",[o.UNKNOWN,o.FLOAT64,o.FLOAT32,o.INT64,o.INT32,o.INT16,o.INT8,o.UINT64,o.UINT32,o.UINT16,o.UINT8,o.TIMESTAMP,o.UUID,o.STRING,o.JSON]),u(o,"BIG_INT_TYPES",[o.INT64,o.UINT64,o.TIMESTAMP]),u(o,"z",i.z.union([i.z.string().transform(r=>new o(r)),i.z.instanceof(o)]));let w=o;const A=class I extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return I.bytes(this.valueOf()+e.valueOf())}sub(e){return I.bytes(this.valueOf()-e.valueOf())}truncate(e){return new I(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return I.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/I.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/I.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/I.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/I.TERABYTE.valueOf()}toString(){const e=this.truncate(I.TERABYTE),t=this.truncate(I.GIGABYTE),n=this.truncate(I.MEGABYTE),s=this.truncate(I.KILOBYTE),a=this.truncate(I.BYTE),c=e,d=t.sub(e),f=n.sub(t),p=s.sub(n),m=a.sub(s);let l="";return c.isZero||(l+=`${c.terabytes}TB `),d.isZero||(l+=`${d.gigabytes}GB `),f.isZero||(l+=`${f.megabytes}MB `),p.isZero||(l+=`${p.kilobytes}KB `),(!m.isZero||l==="")&&(l+=`${m.valueOf()}B`),l.trim()}static bytes(e=1){return new I(e)}static kilobytes(e=1){return I.bytes(e.valueOf()*1e3)}static megabytes(e=1){return I.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return I.megabytes(e.valueOf()*1e3)}static terabytes(e){return I.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};u(A,"BYTE",new A(1)),u(A,"KILOBYTE",A.kilobytes(1)),u(A,"MEGABYTE",A.megabytes(1)),u(A,"GIGABYTE",A.gigabytes(1)),u(A,"TERABYTE",A.terabytes(1)),u(A,"ZERO",new A(0)),u(A,"z",i.z.union([i.z.number().transform(r=>new A(r)),i.z.instanceof(A)]));let me=A;i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const nt=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof v||r instanceof O||r instanceof Date},or=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):J(t,-n).valueOf(),J=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e),ur=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof hr?!0:nt(r),k=-1,cr=i.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),lr=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),we=10,H=class U{constructor(e){u(this,"key",""),u(this,"isSynnaxSeries",!0),u(this,"dataType"),u(this,"sampleOffset"),u(this,"gl"),u(this,"_data"),u(this,"_timeRange"),u(this,"alignment",0n),u(this,"_cachedMin"),u(this,"_cachedMax"),u(this,"writePos",k),u(this,"_refCount",0),u(this,"_cachedLength"),u(this,"_cachedIndexes"),ur(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:s=0,glBufferUsage:a="static",alignment:c=0n,key:d=ir()}=e,f=e.data??[];if(f instanceof U||typeof f=="object"&&"isSynnaxSeries"in f&&f.isSynnaxSeries===!0){const l=f;this.key=l.key,this.dataType=l.dataType,this.sampleOffset=l.sampleOffset,this.gl=l.gl,this._data=l._data,this._timeRange=l._timeRange,this.alignment=l.alignment,this._cachedMin=l._cachedMin,this._cachedMax=l._cachedMax,this.writePos=l.writePos,this._refCount=l._refCount,this._cachedLength=l._cachedLength;return}const p=nt(f),m=Array.isArray(f);if(t!=null)this.dataType=new w(t);else{if(f instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(m||p){let l=f;if(!p){if(f.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");l=f[0]}if(typeof l=="string")this.dataType=w.STRING;else if(typeof l=="number")this.dataType=w.FLOAT64;else if(typeof l=="bigint")this.dataType=w.INT64;else if(typeof l=="boolean")this.dataType=w.BOOLEAN;else if(l instanceof v||l instanceof Date||l instanceof v)this.dataType=w.TIMESTAMP;else if(typeof l=="object")this.dataType=w.JSON;else throw new Error(`cannot infer data type of ${typeof l} when constructing a Series from a JS array`)}else this.dataType=new w(f)}if(!m&&!p)this._data=f;else{let l=p?[f]:f;const N=l[0];(N instanceof v||N instanceof Date||N instanceof O)&&(l=l.map(M=>new v(M).valueOf())),this.dataType.equals(w.STRING)?(this._cachedLength=l.length,this._data=new TextEncoder().encode(`${l.join(`
|
|
1
|
+
"use strict";var Rt=Object.defineProperty;var Dt=(s,e,t)=>e in s?Rt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var S=(s,e,t)=>Dt(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("zod"),kt=s=>{const e=s.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)},at=s=>{const e=(t,r=Se)=>{if(typeof t=="string")return s(t);if(Array.isArray(t))return t.map(o=>e(o,r));if(!me(t))return t;r=Pt(r);const n={},a=t;return Object.keys(a).forEach(o=>{let c=a[o];const d=s(o);r.recursive&&(me(c)?Ye(c,r.keepTypesOnRecursion)||(c=e(c,r)):r.recursiveInArray&&We(c)&&(c=[...c].map(p=>{let y=p;return me(p)?Ye(y,r.keepTypesOnRecursion)||(y=e(p,r)):We(p)&&(y=e({key:p},r).key),y}))),n[d]=c}),n};return e},Re=at(kt),Lt=s=>s.replace(/([a-z0-9])([A-Z])/g,(e,t,r)=>`${t}_${r.toLowerCase()}`),ot=at(Lt),Se={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Pt=(s=Se)=>(s.recursive==null?s=Se:s.recursiveInArray??(s.recursiveInArray=!1),s),We=s=>s!=null&&Array.isArray(s),me=s=>s!=null&&typeof s=="object"&&!Array.isArray(s),Ye=(s,e)=>(e||[]).some(t=>s instanceof t),De=s=>s!=null&&typeof s=="object"&&!Array.isArray(s);var jt=Object.defineProperty,Ft=(s,e,t)=>e in s?jt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Z=(s,e,t)=>Ft(s,typeof e!="symbol"?e+"":e,t);function Wt(s){const e=s.length;let t=0,r=0;for(;r<e;){let n=s.charCodeAt(r++);if((n&4294967168)===0){t++;continue}else if((n&4294965248)===0)t+=2;else{if(n>=55296&&n<=56319&&r<e){const a=s.charCodeAt(r);(a&64512)===56320&&(++r,n=((n&1023)<<10)+(a&1023)+65536)}(n&4294901760)===0?t+=3:t+=4}}return t}function Yt(s,e,t){const r=s.length;let n=t,a=0;for(;a<r;){let o=s.charCodeAt(a++);if((o&4294967168)===0){e[n++]=o;continue}else if((o&4294965248)===0)e[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&a<r){const c=s.charCodeAt(a);(c&64512)===56320&&(++a,o=((o&1023)<<10)+(c&1023)+65536)}(o&4294901760)===0?(e[n++]=o>>12&15|224,e[n++]=o>>6&63|128):(e[n++]=o>>18&7|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128)}e[n++]=o&63|128}}const qt=new TextEncoder,Vt=50;function Ht(s,e,t){qt.encodeInto(s,e.subarray(t))}function Zt(s,e,t){s.length>Vt?Ht(s,e,t):Yt(s,e,t)}const Gt=4096;function ht(s,e,t){let r=e;const n=r+t,a=[];let o="";for(;r<n;){const c=s[r++];if((c&128)===0)a.push(c);else if((c&224)===192){const d=s[r++]&63;a.push((c&31)<<6|d)}else if((c&240)===224){const d=s[r++]&63,p=s[r++]&63;a.push((c&31)<<12|d<<6|p)}else if((c&248)===240){const d=s[r++]&63,p=s[r++]&63,y=s[r++]&63;let l=(c&7)<<18|d<<12|p<<6|y;l>65535&&(l-=65536,a.push(l>>>10&1023|55296),l=56320|l&1023),a.push(l)}else a.push(c);a.length>=Gt&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}const Kt=new TextDecoder,Jt=200;function Xt(s,e,t){const r=s.subarray(e,e+t);return Kt.decode(r)}function Qt(s,e,t){return t>Jt?Xt(s,e,t):ht(s,e,t)}let ue=class{constructor(e,t){this.type=e,this.data=t}},M=class Ie extends Error{constructor(e){super(e);const t=Object.create(Ie.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Ie.name})}};const K=4294967295;function _t(s,e,t){const r=t/4294967296,n=t;s.setUint32(e,r),s.setUint32(e+4,n)}function ut(s,e,t){const r=Math.floor(t/4294967296),n=t;s.setUint32(e,r),s.setUint32(e+4,n)}function ct(s,e){const t=s.getInt32(e),r=s.getUint32(e+4);return t*4294967296+r}function es(s,e){const t=s.getUint32(e),r=s.getUint32(e+4);return t*4294967296+r}const ts=-1,ss=4294967296-1,rs=17179869184-1;function ns({sec:s,nsec:e}){if(s>=0&&e>=0&&s<=rs)if(e===0&&s<=ss){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,s),t}else{const t=s/4294967296,r=s&4294967295,n=new Uint8Array(8),a=new DataView(n.buffer);return a.setUint32(0,e<<2|t&3),a.setUint32(4,r),n}else{const t=new Uint8Array(12),r=new DataView(t.buffer);return r.setUint32(0,e),ut(r,4,s),t}}function is(s){const e=s.getTime(),t=Math.floor(e/1e3),r=(e-t*1e3)*1e6,n=Math.floor(r/1e9);return{sec:t+n,nsec:r-n*1e9}}function as(s){if(s instanceof Date){const e=is(s);return ns(e)}else return null}function os(s){const e=new DataView(s.buffer,s.byteOffset,s.byteLength);switch(s.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),r=e.getUint32(4),n=(t&3)*4294967296+r,a=t>>>2;return{sec:n,nsec:a}}case 12:{const t=ct(e,4),r=e.getUint32(0);return{sec:t,nsec:r}}default:throw new M(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${s.length}`)}}function hs(s){const e=os(s);return new Date(e.sec*1e3+e.nsec/1e6)}const us={type:ts,encode:as,decode:hs};let oe=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(us)}register({type:e,encode:t,decode:r}){if(e>=0)this.encoders[e]=t,this.decoders[e]=r;else{const n=-1-e;this.builtInEncoders[n]=t,this.builtInDecoders[n]=r}}tryToEncode(e,t){for(let r=0;r<this.builtInEncoders.length;r++){const n=this.builtInEncoders[r];if(n!=null){const a=n(e,t);if(a!=null){const o=-1-r;return new ue(o,a)}}}for(let r=0;r<this.encoders.length;r++){const n=this.encoders[r];if(n!=null){const a=n(e,t);if(a!=null){const o=r;return new ue(o,a)}}}return e instanceof ue?e:null}decode(e,t,r){const n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,r):new ue(t,e)}};oe.defaultCodec=new oe;function cs(s){return s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer}function Ue(s){return s instanceof Uint8Array?s:ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):cs(s)?new Uint8Array(s):Uint8Array.from(s)}const ls=100,ds=2048;let fs=class lt{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??oe.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??ls,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??ds,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new lt({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){const t=new ArrayBuffer(e),r=new Uint8Array(t),n=new DataView(t);r.set(this.bytes),this.view=n,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const t=Wt(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),Zt(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);const r=Ue(e);this.writeU8a(r)}encodeArray(e,t){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let r=0;for(const n of t)e[n]!==void 0&&r++;return r}encodeMap(e,t){const r=Object.keys(e);this.sortKeys&&r.sort();const n=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(const a of r){const o=e[a];this.ignoreUndefined&&o===void 0||(this.encodeString(a),this.doEncode(o,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),n=r.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(r);return}const t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),_t(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ut(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function X(s,e){return new fs(e).encodeSharedRef(s)}function be(s){return`${s<0?"-":""}0x${Math.abs(s).toString(16).padStart(2,"0")}`}const gs=16,ps=16;class ys{constructor(e=gs,t=ps){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,r){const n=this.caches[r-1];e:for(const a of n){const o=a.bytes;for(let c=0;c<r;c++)if(o[c]!==e[t+c])continue e;return a.str}return null}store(e,t){const r=this.caches[e.length-1],n={bytes:e,str:t};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=n:r.push(n)}decode(e,t,r){const n=this.find(e,t,r);if(n!=null)return this.hit++,n;this.miss++;const a=ht(e,t,r),o=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(o,a),a}}const xe="array",ne="map_key",dt="map_value",ws=s=>{if(typeof s=="string"||typeof s=="number")return s;throw new M("The type of key must be string or number but "+typeof s)};class ms{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=xe,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=ne,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===xe){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===ne||e.type===dt){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const J=-1,ke=new DataView(new ArrayBuffer(0)),bs=new Uint8Array(ke.buffer);try{ke.getInt8(0)}catch(s){if(!(s instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const qe=new RangeError("Insufficient data"),vs=new ys;let Ts=class ft{constructor(e){this.totalPos=0,this.pos=0,this.view=ke,this.bytes=bs,this.headByte=J,this.stack=new ms,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??oe.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??K,this.maxBinLength=(e==null?void 0:e.maxBinLength)??K,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??K,this.maxMapLength=(e==null?void 0:e.maxMapLength)??K,this.maxExtLength=(e==null?void 0:e.maxExtLength)??K,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:vs,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??ws}clone(){return new ft({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=J,this.stack.reset()}setBuffer(e){const t=Ue(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===J&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),r=Ue(e),n=new Uint8Array(t.length+r.length);n.set(t),n.set(r,t.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:r}=this;return new RangeError(`Extra ${t.byteLength-r} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,r;for await(const c of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{r=this.doDecodeSync(),t=!0}catch(d){if(!(d instanceof RangeError))throw d}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:n,pos:a,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${be(n)} at ${o} (${a} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let r=t,n=-1;for await(const a of e){if(t&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a),r&&(n=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){const n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{const n=e-160;t=this.decodeString(n,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){const n=this.lookU8();t=this.decodeString(n,1)}else if(e===218){const n=this.lookU16();t=this.decodeString(n,2)}else if(e===219){const n=this.lookU32();t=this.decodeString(n,4)}else if(e===220){const n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){const n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){const n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){const n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){const n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){const n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){const n=this.lookU32();t=this.decodeBinary(n,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){const n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){const n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){const n=this.lookU32();t=this.decodeExtension(n,4)}else throw new M(`Unrecognized type byte: ${be(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const n=r.top();if(n.type===xe)if(n.array[n.position]=t,n.position++,n.position===n.size)t=n.array,r.release(n);else continue e;else if(n.type===ne){if(t==="__proto__")throw new M("The key __proto__ is not allowed");n.key=this.mapKeyConverter(t),n.type=dt;continue e}else if(n.map[n.key]=t,n.readCount++,n.readCount===n.size)t=n.map,r.release(n);else{n.key=null,n.type=ne;continue e}}return t}}readHeadByte(){return this.headByte===J&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=J}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new M(`Unrecognized array type byte: ${be(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new M(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new M(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){var r;if(e>this.maxStrLength)throw new M(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw qe;const n=this.pos+t;let a;return this.stateIsMapKey()&&(r=this.keyDecoder)!=null&&r.canBeCached(e)?a=this.keyDecoder.decode(this.bytes,n,e):a=Qt(this.bytes,n,e),this.pos+=t+e,a}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ne:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new M(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw qe;const r=this.pos+t,n=this.bytes.subarray(r,r+e);return this.pos+=t+e,n}decodeExtension(e,t){if(e>this.maxExtLength)throw new M(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=es(this.view,this.pos);return this.pos+=8,e}readI64(){const e=ct(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function gt(s,e){return new Ts(e).decode(s)}let Os=class{constructor(){Z(this,"contentType","application/json"),Z(this,"decoder"),Z(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const r=JSON.parse(e),n=Re(r);return t!=null?t.parse(n):n}encodeString(e){const t=ot(e);return JSON.stringify(t,(r,n)=>ArrayBuffer.isView(n)?Array.from(n):De(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},Ss=class{constructor(){Z(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t)}decode(e,t){const r=new TextDecoder().decode(e);return this.decodeString(r,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!De(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),r=[t.join(",")];return e.forEach(n=>{const a=t.map(o=>JSON.stringify(n[o]??""));r.push(a.join(","))}),r.join(`
|
|
2
|
+
`)}decodeString(e,t){const[r,...n]=e.trim().split(`
|
|
3
|
+
`).map(c=>c.trim());if(r.length===0)return t!=null?t.parse({}):{};const a=r.split(",").map(c=>c.trim()),o={};return a.forEach(c=>{o[c]=[]}),n.forEach(c=>{const d=c.split(",").map(p=>p.trim());a.forEach((p,y)=>{const l=this.parseValue(d[y]);l!=null&&o[p].push(l)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},Is=class{constructor(){Z(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e)}decode(e,t){const r=new TextDecoder().decode(e);return t!=null?t.parse(r):r}};const P=new oe;P.register({type:0,encode:s=>{if(ArrayBuffer.isView(s)){const e=Array.from(s);return X(e,{extensionCodec:P})}return De(s)&&"encode_value"in s?typeof s.value=="bigint"?X(s.value.toString(),{extensionCodec:P}):X(s.value,{extensionCodec:P}):typeof s=="bigint"?X(s.toString(),{extensionCodec:P}):null},decode:s=>gt(s,{extensionCodec:P})});let Us=class{constructor(){Z(this,"contentType","application/msgpack")}encode(e){const t=ot(e);return X(t,{extensionCodec:P}).slice()}decode(e,t){const r=gt(e,{extensionCodec:P}),n=Re(r);return t!=null?t.parse(n):n}static registerCustomType(){}};const de=new Os;new Ss;new Is;new Us;const xs=s=>s!=null&&typeof s=="object"&&"toString"in s,Ns=(s,e=!1)=>{const t=xs(s)?"stringer":typeof s;let r;switch(t){case"string":r=(n,a)=>n.localeCompare(a);break;case"stringer":r=(n,a)=>n.toString().localeCompare(a.toString());break;case"number":r=(n,a)=>Number(n)-Number(a);break;case"bigint":r=(n,a)=>BigInt(n)-BigInt(a)>0n?1:-1;break;case"boolean":r=(n,a)=>Number(n)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Es(r):r},Es=s=>(e,t)=>s(t,e),ye=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const pt=i.z.object({width:i.z.number(),height:i.z.number()}),zs=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),As=["width","height"];i.z.enum(As);const Bs=["start","center","end"],$s=["signedWidth","signedHeight"];i.z.enum($s);const ge=i.z.object({x:i.z.number(),y:i.z.number()}),Ms=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),Cs=["x","y"],yt=i.z.enum(Cs),wt=["top","right","bottom","left"];i.z.enum(wt);const Rs=["left","right"],mt=i.z.enum(Rs),Ds=["top","bottom"],bt=i.z.enum(Ds),vt=["center"],Ve=i.z.enum(vt),ks=[...wt,...vt],Tt=i.z.enum(ks);i.z.enum(Bs);const Ls=["first","last"];i.z.enum(Ls);const Ps=i.z.object({lower:i.z.number(),upper:i.z.number()}),js=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([Ps,ye]);i.z.union([js,ye]);i.z.enum([...yt.options,...Tt.options]);i.z.union([yt,Tt,i.z.instanceof(String)]);const Fs=s=>typeof s=="bigint"||s instanceof BigInt,V=(s,e)=>Fs(s)?s.valueOf()*BigInt(e.valueOf()):s.valueOf()*Number(e.valueOf()),F=(s,e)=>{const t={};if(typeof s=="number"||typeof s=="bigint")e!=null?(t.lower=s,t.upper=e):(t.lower=typeof s=="bigint"?0n:0,t.upper=s);else if(Array.isArray(s)){if(s.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=s}else return He(s);return He(t)},He=s=>s.lower>s.upper?{lower:s.upper,upper:s.lower}:s,Ze=(s,e)=>{const t=F(s);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};i.z.object({x:mt.or(Ve),y:bt.or(Ve)});const Ws=i.z.object({x:mt,y:bt}),Ys=Object.freeze({x:"left",y:"top"}),qs=(s,e)=>s.x===e.x&&s.y===e.y,Ge=i.z.union([i.z.number(),ge,ye,pt,zs,Ms]),Vs=(s,e)=>{if(typeof s=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return s==="x"?{x:e,y:0}:{x:0,y:e}}return typeof s=="number"?{x:s,y:e??s}:Array.isArray(s)?{x:s[0],y:s[1]}:"signedWidth"in s?{x:s.signedWidth,y:s.signedHeight}:"clientX"in s?{x:s.clientX,y:s.clientY}:"width"in s?{x:s.width,y:s.height}:{x:s.x,y:s.y}},Ke=Object.freeze({x:0,y:0}),ce=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:ce,left:ce,width:ce,height:ce});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:ge,two:ge,root:Ws});const Le=(s,e,t=0,r=0,n)=>{const a={one:{...Ke},two:{...Ke},root:n??Ys};if(typeof s=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:s,y:e},a.two={x:a.one.x+t,y:a.one.y+r},a}return"one"in s&&"two"in s&&"root"in s?{...s,root:n??s.root}:("getBoundingClientRect"in s&&(s=s.getBoundingClientRect()),"left"in s?(a.one={x:s.left,y:s.top},a.two={x:s.right,y:s.bottom},a):(a.one=s,e==null?a.two={x:a.one.x+t,y:a.one.y+r}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},ve=s=>{const e=Le(s);return{lower:e.one.x,upper:e.two.x}},Te=s=>{const e=Le(s);return{lower:e.one.y,upper:e.two.y}},Hs=s=>typeof s!="object"||s==null?!1:"one"in s&&"two"in s&&"root"in s,Zs=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([pt,Zs,ge,ye]);var Gs=Object.defineProperty,Ks=(s,e,t)=>e in s?Gs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,k=(s,e,t)=>Ks(s,typeof e!="symbol"?e+"":e,t);const Js=(s,e,t)=>e!==void 0&&s<e?e:t!==void 0&&s>t?t:s;i.z.object({offset:Ge,scale:Ge});i.z.object({offset:i.z.number(),scale:i.z.number()});const Xs=s=>(e,t,r,n)=>t==="dimension"?[e,r]:[e,n?r-s:r+s],Qs=s=>(e,t,r,n)=>[e,n?r/s:r*s],_s=s=>(e,t,r)=>{if(e===null)return[s,r];const{lower:n,upper:a}=e,{lower:o,upper:c}=s,d=a-n,p=c-o;if(t==="dimension")return[s,r*(p/d)];const y=(r-n)*(p/d)+o;return[s,y]},er=s=>(e,t,r)=>[s,r],tr=()=>(s,e,t)=>{if(s===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[s,t];const{lower:r,upper:n}=s;return[s,n-(t-r)]},sr=s=>(e,t,r)=>{const{lower:n,upper:a}=s;return r=Js(r,n,a),[e,r]},Ne=class Q{constructor(){k(this,"ops",[]),k(this,"currBounds",null),k(this,"currType",null),k(this,"reversed",!1),this.ops=[]}static translate(e){return new Q().translate(e)}static magnify(e){return new Q().magnify(e)}static scale(e,t){return new Q().scale(e,t)}translate(e){const t=this.new(),r=Xs(e);return r.type="translate",t.ops.push(r),t}magnify(e){const t=this.new(),r=Qs(e);return r.type="magnify",t.ops.push(r),t}scale(e,t){const r=F(e,t),n=this.new(),a=_s(r);return a.type="scale",n.ops.push(a),n}clamp(e,t){const r=F(e,t),n=this.new(),a=sr(r);return a.type="clamp",n.ops.push(a),n}reBound(e,t){const r=F(e,t),n=this.new(),a=er(r);return a.type="re-bound",n.ops.push(a),n}invert(){const e=tr();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 Q;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([r,n],a)=>a(r,e,n,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((r,n)=>{if(r.type==="scale"||t.some(([o,c])=>n>=o&&n<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>n);a!==-1&&t.push([n,a])}),t.forEach(([r,n])=>{const a=e.ops.slice(r,n);a.unshift(e.ops[n]),e.ops.splice(r,n-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};k(Ne,"IDENTITY",new Ne);let Je=Ne;const Xe=class D{constructor(e=new Je,t=new Je,r=null){k(this,"x"),k(this,"y"),k(this,"currRoot"),this.x=e,this.y=t,this.currRoot=r}static translate(e,t){return new D().translate(e,t)}static translateX(e){return new D().translateX(e)}static translateY(e){return new D().translateY(e)}static clamp(e){return new D().clamp(e)}static magnify(e){return new D().magnify(e)}static scale(e){return new D().scale(e)}static reBound(e){return new D().reBound(e)}translate(e,t){const r=Vs(e,t),n=this.copy();return n.x=this.x.translate(r.x),n.y=this.y.translate(r.y),n}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(Hs(e)){const r=this.currRoot;return t.currRoot=e.root,r!=null&&!qs(r,e.root)&&(r.x!==e.root.x&&(t.x=t.x.invert()),r.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(ve(e)),t.y=t.y.scale(Te(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(ve(e)),t.y=this.y.reBound(Te(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(ve(e)),t.y=this.y.clamp(Te(e)),t}copy(){const e=new D;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 Le(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})}}};k(Xe,"IDENTITY",new Xe);var rr=Object.defineProperty,nr=(s,e,t)=>e in s?rr(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,h=(s,e,t)=>nr(s,typeof e!="symbol"?e+"":e,t);let ir=(s,e=21)=>(t=e)=>{let r="",n=t|0;for(;n--;)r+=s[Math.random()*s.length|0];return r};const ar="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",or=ir(ar,11),hr=()=>or(),ur=i.z.enum(["static","dynamic"]),Ot=(s,e)=>{const t=new T(e);if(![w.DAY,w.HOUR,w.MINUTE,w.SECOND,w.MILLISECOND,w.MICROSECOND,w.NANOSECOND].some(n=>n.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=s.valueOf()%t.valueOf();return s instanceof T?new T(r):new w(r)},m=class f{constructor(e,t="UTC"){if(h(this,"value"),h(this,"encodeValue",!0),e==null)this.value=f.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*f.MILLISECOND.valueOf();else if(typeof e=="string")this.value=f.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=f.parseDate(e);else{let r=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(r=f.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=f.MAX:e=f.MIN)),this.value=BigInt(e.valueOf())+r}}static parseDate([e=1970,t=1,r=1]){const n=new Date(e,t-1,r,0,0,0,0);return new f(BigInt(n.getTime())*f.MILLISECOND.valueOf()).truncate(f.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[r,n,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let d=f.hours(parseInt(r??"00")).add(f.minutes(parseInt(n??"00"))).add(f.seconds(parseInt(o??"00"))).add(f.milliseconds(parseInt(c??"00")));return t==="local"&&(d=d.add(f.utcOffset)),d.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return f.parseTimeString(e,t);const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new f(BigInt(r.getTime())*f.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(f.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const r=this.toISOString(t);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${t} ${r}`}static get utcOffset(){return new w(BigInt(new Date().getTimezoneOffset())*f.MINUTE.valueOf())}static since(e){return new f().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new f(e).valueOf()}span(e){return this.range(e).span}range(e){return new ie(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new f(e).valueOf()}afterEq(e){return this.valueOf()>=new f(e).valueOf()}before(e){return this.valueOf()<new f(e).valueOf()}beforeEq(e){return this.valueOf()<=new f(e).valueOf()}add(e){return new f(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new f(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(w.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(w.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(w.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(w.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(f.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(f.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new f(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new f(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new f(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new f(t,"UTC")}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new f(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new f(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new f(t)}toString(){return this.date().toISOString()}remainder(e){return Ot(this,e)}get isToday(){return this.truncate(w.DAY).equals(f.now().truncate(w.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new f(new Date)}static max(...e){let t=f.MIN;for(const r of e){const n=new f(r);n.after(t)&&(t=n)}return t}static min(...e){let t=f.MAX;for(const r of e){const n=new f(r);n.before(t)&&(t=n)}return t}static nanoseconds(e,t="UTC"){return new f(e,t)}static microseconds(e,t="UTC"){return f.nanoseconds(e*1e3,t)}static milliseconds(e,t="UTC"){return f.microseconds(e*1e3,t)}static seconds(e,t="UTC"){return f.milliseconds(e*1e3,t)}static minutes(e,t="UTC"){return f.seconds(e*60,t)}static hours(e,t="UTC"){return f.minutes(e*60,t)}static days(e,t="UTC"){return f.hours(e*24,t)}};h(m,"NANOSECOND",m.nanoseconds(1)),h(m,"MICROSECOND",m.microseconds(1)),h(m,"MILLISECOND",m.milliseconds(1)),h(m,"SECOND",m.seconds(1)),h(m,"MINUTE",m.minutes(1)),h(m,"HOUR",m.hours(1)),h(m,"DAY",m.days(1)),h(m,"MAX",new m((1n<<63n)-1n)),h(m,"MIN",new m(0)),h(m,"ZERO",new m(0)),h(m,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(s=>new m(s.value)),i.z.string().transform(s=>new m(BigInt(s))),i.z.instanceof(Number).transform(s=>new m(s)),i.z.number().transform(s=>new m(s)),i.z.instanceof(m)]));let T=m;const b=class g{constructor(e){h(this,"value"),h(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof g?e:e instanceof Qe?e.period:e instanceof T?new g(e):["number","bigint"].includes(typeof e)?g.seconds(e):new g(e)}static fromMilliseconds(e){return e instanceof g?e:e instanceof Qe?e.period:e instanceof T?new g(e):["number","bigint"].includes(typeof e)?g.milliseconds(e):new g(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new g(e).valueOf()}greaterThan(e){return this.valueOf()>new g(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new g(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new g(e).valueOf()}remainder(e){return Ot(this,e)}truncate(e){return new g(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(g.DAY),t=this.truncate(g.HOUR),r=this.truncate(g.MINUTE),n=this.truncate(g.SECOND),a=this.truncate(g.MILLISECOND),o=this.truncate(g.MICROSECOND),c=this.truncate(g.NANOSECOND),d=e,p=t.sub(e),y=r.sub(t),l=n.sub(r),U=a.sub(n),A=o.sub(a),R=c.sub(o);let z="";return d.isZero||(z+=`${d.days}d `),p.isZero||(z+=`${p.hours}h `),y.isZero||(z+=`${y.minutes}m `),l.isZero||(z+=`${l.seconds}s `),U.isZero||(z+=`${U.milliseconds}ms `),A.isZero||(z+=`${A.microseconds}µs `),R.isZero||(z+=`${R.nanoseconds}ns`),z.trim()}mult(e){return new g(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(g.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(g.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(g.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(g.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(g.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(g.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new g(e).valueOf()}add(e){return new g(this.valueOf()+new g(e).valueOf())}sub(e){return new g(this.valueOf()-new g(e).valueOf())}static nanoseconds(e=1){return new g(e)}static microseconds(e=1){return g.nanoseconds(V(e,1e3))}static milliseconds(e=1){return g.microseconds(V(e,1e3))}static seconds(e=1){return g.milliseconds(V(e,1e3))}static minutes(e=1){return g.seconds(V(e,60))}static hours(e){return g.minutes(V(e,60))}static days(e){return g.hours(V(e,24))}};h(b,"NANOSECOND",b.nanoseconds(1)),h(b,"MICROSECOND",b.microseconds(1)),h(b,"MILLISECOND",b.milliseconds(1)),h(b,"SECOND",b.seconds(1)),h(b,"MINUTE",b.minutes(1)),h(b,"HOUR",b.hours(1)),h(b,"DAY",b.days(1)),h(b,"MAX",new b((1n<<63n)-1n)),h(b,"MIN",new b(0)),h(b,"ZERO",new b(0)),h(b,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(s=>new b(s.value)),i.z.string().transform(s=>new b(BigInt(s))),i.z.instanceof(Number).transform(s=>new b(s)),i.z.number().transform(s=>new b(s)),i.z.instanceof(b)]));let w=b;const _=class fe extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new fe(e).valueOf()}get period(){return w.seconds(1/this.valueOf())}sampleCount(e){return new w(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new E(t).valueOf()}span(e){return w.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new fe(e)}static khz(e){return fe.hz(e*1e3)}};h(_,"z",i.z.union([i.z.number().transform(s=>new _(s)),i.z.instanceof(Number).transform(s=>new _(s)),i.z.instanceof(_)]));let Qe=_;const x=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new Ee(e*this.valueOf())}};h(x,"UNKNOWN",new x(0)),h(x,"BIT128",new x(16)),h(x,"BIT64",new x(8)),h(x,"BIT32",new x(4)),h(x,"BIT16",new x(2)),h(x,"BIT8",new x(1)),h(x,"z",i.z.union([i.z.number().transform(s=>new x(s)),i.z.instanceof(Number).transform(s=>new x(s)),i.z.instanceof(x)]));let E=x;const B=class ee{constructor(e,t){h(this,"start"),h(this,"end"),typeof e=="object"&&"start"in e?(this.start=new T(e.start),this.end=new T(e.end)):(this.start=new T(e),this.end=new T(t))}get span(){return new w(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 ee(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=w.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let r=this.start.sub(e.start).valueOf(),n=this.end.sub(e.end).valueOf();return r<0&&(r=-r),n<0&&(n=-n),r<=t.valueOf()&&n<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=w.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const n=T.max(r.start,e.start),a=T.min(r.end,e.end);return a.before(n)?!1:new w(a.sub(n)).greaterThanOrEqual(t)}contains(e){return e instanceof ee?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new ee(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 ee(T.min(...e.map(t=>t.start)),T.max(...e.map(t=>t.end)))}};h(B,"MAX",new B(T.MIN,T.MAX)),h(B,"MIN",new B(T.MAX,T.MIN)),h(B,"ZERO",new B(T.ZERO,T.ZERO)),h(B,"z",i.z.union([i.z.object({start:T.z,end:T.z}).transform(s=>new B(s.start,s.end)),i.z.instanceof(B)]));let ie=B;const u=class O{constructor(e){if(h(this,"value"),h(this,"encodeValue",!0),e instanceof O||typeof e=="string"||typeof e.valueOf()=="string"){this.value=e.valueOf();return}const t=O.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){this.value=t.valueOf();return}throw this.value=O.UNKNOWN.valueOf(),new Error(`unable to find data type for ${e.toString()}`)}valueOf(){return this.value}get Array(){const e=O.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(O.JSON)||this.equals(O.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(O.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=O.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(O.UINT8)||this.equals(O.UINT16)||this.equals(O.UINT32)||this.equals(O.UINT64)}get isSigned(){return this.equals(O.INT8)||this.equals(O.INT16)||this.equals(O.INT32)||this.equals(O.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(O.INT32)&&e.equals(O.FLOAT64)||this.equals(O.INT8)&&e.equals(O.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}toJSON(){return this.toString()}get usesBigInt(){return O.BIG_INT_TYPES.some(e=>e.equals(this))}};h(u,"UNKNOWN",new u("unknown")),h(u,"FLOAT64",new u("float64")),h(u,"FLOAT32",new u("float32")),h(u,"INT64",new u("int64")),h(u,"INT32",new u("int32")),h(u,"INT16",new u("int16")),h(u,"INT8",new u("int8")),h(u,"UINT64",new u("uint64")),h(u,"UINT32",new u("uint32")),h(u,"UINT16",new u("uint16")),h(u,"UINT8",new u("uint8")),h(u,"BOOLEAN",u.UINT8),h(u,"TIMESTAMP",new u("timestamp")),h(u,"UUID",new u("uuid")),h(u,"STRING",new u("string")),h(u,"JSON",new u("json")),h(u,"ARRAY_CONSTRUCTORS",new Map([[u.UINT8.toString(),Uint8Array],[u.UINT16.toString(),Uint16Array],[u.UINT32.toString(),Uint32Array],[u.UINT64.toString(),BigUint64Array],[u.FLOAT32.toString(),Float32Array],[u.FLOAT64.toString(),Float64Array],[u.INT8.toString(),Int8Array],[u.INT16.toString(),Int16Array],[u.INT32.toString(),Int32Array],[u.INT64.toString(),BigInt64Array],[u.TIMESTAMP.toString(),BigInt64Array],[u.STRING.toString(),Uint8Array],[u.JSON.toString(),Uint8Array],[u.UUID.toString(),Uint8Array]])),h(u,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,u.UINT8],[Uint16Array.name,u.UINT16],[Uint32Array.name,u.UINT32],[BigUint64Array.name,u.UINT64],[Float32Array.name,u.FLOAT32],[Float64Array.name,u.FLOAT64],[Int8Array.name,u.INT8],[Int16Array.name,u.INT16],[Int32Array.name,u.INT32],[BigInt64Array.name,u.INT64]])),h(u,"DENSITIES",new Map([[u.UINT8.toString(),E.BIT8],[u.UINT16.toString(),E.BIT16],[u.UINT32.toString(),E.BIT32],[u.UINT64.toString(),E.BIT64],[u.FLOAT32.toString(),E.BIT32],[u.FLOAT64.toString(),E.BIT64],[u.INT8.toString(),E.BIT8],[u.INT16.toString(),E.BIT16],[u.INT32.toString(),E.BIT32],[u.INT64.toString(),E.BIT64],[u.TIMESTAMP.toString(),E.BIT64],[u.STRING.toString(),E.UNKNOWN],[u.JSON.toString(),E.UNKNOWN],[u.UUID.toString(),E.BIT128]])),h(u,"ALL",[u.UNKNOWN,u.FLOAT64,u.FLOAT32,u.INT64,u.INT32,u.INT16,u.INT8,u.UINT64,u.UINT32,u.UINT16,u.UINT8,u.TIMESTAMP,u.UUID,u.STRING,u.JSON]),h(u,"BIG_INT_TYPES",[u.INT64,u.UINT64,u.TIMESTAMP]),h(u,"z",i.z.union([i.z.string().transform(s=>new u(s)),i.z.instanceof(u)]));let v=u;const N=class I extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return I.bytes(this.valueOf()+e.valueOf())}sub(e){return I.bytes(this.valueOf()-e.valueOf())}truncate(e){return new I(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return I.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/I.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/I.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/I.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/I.TERABYTE.valueOf()}toString(){const e=this.truncate(I.TERABYTE),t=this.truncate(I.GIGABYTE),r=this.truncate(I.MEGABYTE),n=this.truncate(I.KILOBYTE),a=this.truncate(I.BYTE),o=e,c=t.sub(e),d=r.sub(t),p=n.sub(r),y=a.sub(n);let l="";return o.isZero||(l+=`${o.terabytes}TB `),c.isZero||(l+=`${c.gigabytes}GB `),d.isZero||(l+=`${d.megabytes}MB `),p.isZero||(l+=`${p.kilobytes}KB `),(!y.isZero||l==="")&&(l+=`${y.valueOf()}B`),l.trim()}static bytes(e=1){return new I(e)}static kilobytes(e=1){return I.bytes(e.valueOf()*1e3)}static megabytes(e=1){return I.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return I.megabytes(e.valueOf()*1e3)}static terabytes(e){return I.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};h(N,"BYTE",new N(1)),h(N,"KILOBYTE",N.kilobytes(1)),h(N,"MEGABYTE",N.megabytes(1)),h(N,"GIGABYTE",N.gigabytes(1)),h(N,"TERABYTE",N.terabytes(1)),h(N,"ZERO",new N(0)),h(N,"z",i.z.union([i.z.number().transform(s=>new N(s)),i.z.instanceof(N)]));let Ee=N;i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const St=s=>{const e=typeof s;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||s instanceof T||s instanceof w||s instanceof Date},cr=(s,e,t,r=0)=>s.usesBigInt&&!e.usesBigInt?Number(t)-Number(r):!s.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(r.valueOf()):te(t,-r).valueOf(),te=(s,e)=>e==0?s:s==0?e:typeof s=="bigint"&&typeof e=="bigint"||typeof s=="number"&&typeof e=="number"?s+e:Number(s)+Number(e),lr=s=>s==null?!1:Array.isArray(s)||s instanceof ArrayBuffer||ArrayBuffer.isView(s)&&!(s instanceof DataView)||s instanceof pr?!0:St(s),L=-1,dr=i.z.string().transform(s=>new Uint8Array(atob(s).split("").map(e=>e.charCodeAt(0))).buffer),fr=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),ze=10,gr=(s,e)=>{if(s==="string"&&!e.isVariable)throw new Error(`cannot convert series of type ${e.toString()} to string`);if(s==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(s==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},se=class ${constructor(e){h(this,"key",""),h(this,"isSynnaxSeries",!0),h(this,"dataType"),h(this,"sampleOffset"),h(this,"gl"),h(this,"_data"),h(this,"timeRange",ie.ZERO),h(this,"alignment",0n),h(this,"_cachedMin"),h(this,"_cachedMax"),h(this,"writePos",L),h(this,"_refCount",0),h(this,"_cachedLength"),h(this,"_cachedIndexes"),lr(e)&&(e={data:e});const{dataType:t,timeRange:r,sampleOffset:n=0,glBufferUsage:a="static",alignment:o=0n,key:c=hr()}=e,d=e.data??[];if(d instanceof $||typeof d=="object"&&"isSynnaxSeries"in d&&d.isSynnaxSeries===!0){const l=d;this.key=l.key,this.dataType=l.dataType,this.sampleOffset=l.sampleOffset,this.gl=l.gl,this._data=l._data,this.timeRange=l.timeRange,this.alignment=l.alignment,this._cachedMin=l._cachedMin,this._cachedMax=l._cachedMax,this.writePos=l.writePos,this._refCount=l._refCount,this._cachedLength=l._cachedLength;return}const p=St(d),y=Array.isArray(d);if(t!=null)this.dataType=new v(t);else{if(d instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||p){let l=d;if(!p){if(d.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");l=d[0]}if(typeof l=="string")this.dataType=v.STRING;else if(typeof l=="number")this.dataType=v.FLOAT64;else if(typeof l=="bigint")this.dataType=v.INT64;else if(typeof l=="boolean")this.dataType=v.BOOLEAN;else if(l instanceof T||l instanceof Date||l instanceof T)this.dataType=v.TIMESTAMP;else if(typeof l=="object")this.dataType=v.JSON;else throw new Error(`cannot infer data type of ${typeof l} when constructing a Series from a JS array`)}else this.dataType=new v(d)}if(!y&&!p)this._data=d;else{let l=p?[d]:d;const U=l[0];(U instanceof T||U instanceof Date||U instanceof w)&&(l=l.map(A=>new T(A).valueOf())),this.dataType.equals(v.STRING)?(this._cachedLength=l.length,this._data=new TextEncoder().encode(`${l.join(`
|
|
4
4
|
`)}
|
|
5
|
-
`).buffer):this.dataType.equals(
|
|
5
|
+
`).buffer):this.dataType.equals(v.JSON)?(this._cachedLength=l.length,this._data=new TextEncoder().encode(`${l.map(A=>de.encodeString(A)).join(`
|
|
6
6
|
`)}
|
|
7
|
-
`).buffer):this.dataType.usesBigInt&&typeof
|
|
7
|
+
`).buffer):this.dataType.usesBigInt&&typeof U=="number"?this._data=new this.dataType.Array(l.map(A=>BigInt(Math.round(A)))).buffer:!this.dataType.usesBigInt&&typeof U=="bigint"?this._data=new this.dataType.Array(l.map(A=>Number(A))).buffer:this._data=new this.dataType.Array(l).buffer}this.key=c,this.alignment=o,this.sampleOffset=n??0,this.timeRange=r??ie.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...r}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const n=new new v(t).Array(e),a=new $({data:n.buffer,dataType:t,...r});return a.writePos=0,a}static createTimestamps(e,t,r){const n=r.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(r.add(t.span(o)).valueOf());return new $({data:a,dataType:v.TIMESTAMP,timeRange:n})}get refCount(){return this._refCount}static fromStrings(e,t){const r=new TextEncoder().encode(`${e.join(`
|
|
8
8
|
`)}
|
|
9
|
-
`);return new
|
|
9
|
+
`);return new $({data:r,dataType:v.STRING,timeRange:t})}static fromJSON(e,t){const r=new TextEncoder().encode(`${e.map(n=>de.encodeString(n)).join(`
|
|
10
10
|
`)}
|
|
11
|
-
`);return new
|
|
12
|
-
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(
|
|
13
|
-
`).slice(0,-1).map(t=>e.parse(re.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new me(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===k?this.byteCapacity:this.dataType.isVariable?new me(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===k?this.data.length: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,s)=>{n===we&&(e++,t.push(s+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 s=0;s<this.length;s++)n[s]=or(this.dataType,e,this.data[s],t);return new U({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(w.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(){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._cachedMax=this.calcRawMax()),J(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(w.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(){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._cachedMin=this.calcRawMin()),J(this._cachedMin,this.sampleOffset))}get bounds(){return j(Number(this.min),Number(this.max))}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)}}enrich(){this.max,this.min}get range(){return J(this.max,-this.min)}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){if(this.dataType.isVariable)return this.atVariable(e,t??!1);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 J(n,this.sampleOffset)}atVariable(e,t){let n=0,s=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let c=0;c<this.data.length;c++)if(this.data[c]===we){if(e===0){s=c;break}n=c+1,e--}if(s===0&&(s=this.data.length),n>=s||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,s);return this.dataType.equals(w.STRING)?new TextDecoder().decode(a):Ze(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const s=It(e);for(;t<=n;){const a=Math.floor((t+n)/2),c=s(this.at(a,!0),e);if(c===0)return a;c<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(w.FLOAT32)&&!this.dataType.equals(w.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:s}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==k){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).valueOf(),c=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,c.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=k}as(e){if(e==="string"){if(!this.dataType.equals(w.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(w.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:je(this.alignmentBounds.lower),upper:je(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return j(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 dr(this);return this.dataType.equals(w.JSON)?new fr(e):e}return new gr(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new De(this,e,t??this.length)}subAlignmentIterator(e,t){return new De(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 U({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 s;return e?s=this.data.subarray(t,n):s=this.data.slice(t,n),new U({data:s,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new U({data:this.buffer,dataType:this.dataType,timeRange:Se.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};u(H,"crudeZ",i.z.object({timeRange:Se.z.optional(),dataType:w.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([cr,lr,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:ar.optional().default("static").optional()})),u(H,"z",H.crudeZ.transform(r=>new H(r)));let hr=H;class De{constructor(e,t,n){u(this,"series"),u(this,"end"),u(this,"index"),this.series=e;const s=j(0,e.length);this.end=Me(s,n),this.index=Me(s,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}}class dr{constructor(e){if(u(this,"series"),u(this,"index"),u(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==we;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var Pe,Le;class fr{constructor(e){u(this,"wrapped"),u(this,Pe,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:re.decodeString(e.value)}}[(Le=Symbol.iterator,Pe=Symbol.toStringTag,Le)](){return this}}var Ye,ke;class gr{constructor(e){u(this,"series"),u(this,"index"),u(this,Ye,"SeriesIterator"),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)}}[(ke=Symbol.iterator,Ye=Symbol.toStringTag,ke)](){return this}}const je=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};i.z.object({key:i.z.string(),value:i.z.string()});i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const st=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",pr=st(),it=["macOS","Windows","Linux"],yr=["macos","windows","linux"],mr={macos:"macOS",windows:"Windows",linux:"Linux"},wr=i.z.enum(it).or(i.z.enum(yr).transform(r=>mr[r])),br=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"macOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"};let ge;const Tr=(r={})=>{const{force:e,default:t}=r;return e??ge??(ge=br(),ge??t)},at=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:it,RUNTIME:pr,detect:st,getOS:Tr,osZ:wr},Symbol.toStringTag,{value:"Module"}));var Or=Object.defineProperty,vr=(r,e,t)=>e in r?Or(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,X=(r,e,t)=>vr(r,typeof e!="symbol"?e+"":e,t);const Sr=(...r)=>r.map(ot).join(""),ot=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Ir=r=>r.endsWith("/")?r.slice(0,-1):r,Nr=(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("&")}`,be=class Te{constructor({host:e,port:t,protocol:n="",pathPrefix:s=""}){X(this,"protocol"),X(this,"host"),X(this,"port"),X(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=ot(s)}replace(e){return new Te({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Te({...this,pathPrefix:Sr(this.path,e)})}toString(){return Ir(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};X(be,"UNKNOWN",new be({host:"unknown",port:0}));let Er=be;const Ar=-128,xr=127;i.z.number().int().min(Ar).max(xr);const zr=-32768,Mr=32767;i.z.number().int().min(zr).max(Mr);const $r=-2147483648,Ur=2147483647;i.z.number().int().min($r).max(Ur);const Br=-9223372036854775808n,Rr=9223372036854775807n;i.z.bigint().min(Br).max(Rr);const Cr=255;i.z.number().int().min(0).max(Cr);const Dr=65535;i.z.number().int().min(0).max(Dr);const Pr=4294967295;i.z.number().int().min(0).max(Pr);const Lr=18446744073709551615n;i.z.bigint().min(0n).max(Lr);var Yr=Object.defineProperty,kr=(r,e,t)=>e in r?Yr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,K=(r,e,t)=>kr(r,typeof e!="symbol"?e+"":e,t);const jr=async r=>await new Promise(e=>setTimeout(e,O.fromMilliseconds(r).milliseconds)),qr=i.z.object({interval:O.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Fr=(r={})=>{const e=r.sleepFn||jr,t=r.maxRetries??5,n=r.scale??1;let s=0,a=new O(r.interval??O.milliseconds(1));return async()=>s>=t?!1:(await e(a),a=a.mult(n),s++,!0)},Gr=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:qr,create:Fr},Symbol.toStringTag,{value:"Module"})),R=class extends Number{};K(R,"ABSOLUTE",255),K(R,"MINIMUM",0),K(R,"BOUNDS",{lower:R.MINIMUM,upper:R.ABSOLUTE+1}),K(R,"z",i.z.union([i.z.instanceof(R),i.z.number().int().min(0).max(255).transform(r=>new R(r)),i.z.instanceof(Number).transform(r=>new R(r))]));i.z.object({name:i.z.string(),key:i.z.string()});const ut=class Q extends Error{constructor(){super(Q.MESSAGE)}matches(e){return typeof e=="string"?e.includes(Q.MESSAGE):e instanceof Q||e.message.includes(Q.MESSAGE)}};K(ut,"MESSAGE","canceled");let Wr=ut;new Wr;i.z.string().regex(/^\d+\.\d+\.\d+$/);const ce=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(r):e instanceof Error?e.message.includes(r):typeof e!="string"?!1:e.includes(r);class ee extends Error{constructor(){super(...arguments);y(this,"discriminator","FreighterError");y(this,"type","")}}const Vr=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},qe="unknown",Fe="nil",Zr="freighter",Ie=i.z.object({type:i.z.string(),data:i.z.string()});class Jr{constructor(){y(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Fe,data:""};if(Vr(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:qe,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===Fe)return null;if(e.type===qe)return new Ge(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Ge(e.data)}}const Ne=new Jr,ct=({encode:r,decode:e})=>Ne.register({encode:r,decode:e}),Hr=r=>Ne.encode(r),ae=r=>Ne.decode(r);class Ge extends ee{constructor(){super(...arguments);y(this,"type","unknown")}}const le="freighter.",F=class F extends ee{constructor(){super("EOF");y(this,"type",F.TYPE)}};y(F,"TYPE",`${le}eof`),y(F,"matches",ce(F.TYPE));let P=F;const G=class G extends ee{constructor(){super("StreamClosed");y(this,"type",G.TYPE)}};y(G,"TYPE",`${le}stream_closed`),y(G,"matches",ce(G.TYPE));let L=G;const W=class W extends ee{constructor(t={}){const{message:n="Unreachable",url:s=Er.UNKNOWN}=t;super(n);y(this,"type",W.TYPE);y(this,"url");this.url=s}};y(W,"TYPE",`${le}unreachable`),y(W,"matches",ce(W.TYPE));let Y=W;const Xr=r=>{if(!r.type.startsWith(Zr))return null;if(P.matches(r))return{type:P.TYPE,data:"EOF"};if(L.matches(r))return{type:L.TYPE,data:"StreamClosed"};if(Y.matches(r))return{type:Y.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Kr=r=>{if(!r.type.startsWith(le))return null;switch(r.type){case P.TYPE:return new P;case L.TYPE:return new L;case Y.TYPE:return new Y;default:throw new Error(`Unknown error type: ${r.data}`)}};ct({encode:Xr,decode:Kr});class lt{constructor(){y(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const s=async a=>{if(n===this.middleware.length)return await t(a);const c=this.middleware[n];return n++,await c(a,s)};return await s(e)}}const ht="Content-Type",We=r=>{if(at.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),n=new t.Agent({rejectUnauthorized:!1});return async(s,a)=>await e(s,{...a,agent:n})};class Qr extends lt{constructor(t,n,s=!1){super();y(this,"endpoint");y(this,"encoder");y(this,"fetch");return this.endpoint=t.replace({protocol:s?"https":"http"}),this.encoder=n,this.fetch=We(this.endpoint.protocol),new Proxy(this,{get:(a,c,d)=>c==="endpoint"?this.endpoint:Reflect.get(a,c,d)})}get headers(){return{[ht]:this.encoder.contentType}}async send(t,n,s,a){n=s==null?void 0:s.parse(n);let c=null;const d=this.endpoint.child(t),f={};f.method="POST",f.body=this.encoder.encode(n??{});const[,p]=await this.executeMiddleware({target:d.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async m=>{const l={...m,params:{}};f.headers={...this.headers,...m.params};let N;try{N=await We(m.protocol)(m.target,f)}catch(B){let z=B;return z.message==="Load failed"&&(z=new Y({url:d})),[l,z]}const M=await N.arrayBuffer();if(N!=null&&N.ok)return a!=null&&(c=this.encoder.decode(M,a)),[l,null];try{if(N.status!==400)return[l,new Error(N.statusText)];const B=this.encoder.decode(M,Ie),z=ae(B);return[l,z]}catch(B){return[l,new Error(`[freighter] - failed to decode error: ${N.statusText}: ${B.message}`)]}});return[c,p]}}const _r=(r,e)=>{class t{constructor(s){y(this,"wrapped");this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,a,c,d){const f=Gr.create(e);do{const[p,m]=await this.wrapped.send(s,a,c,d);if(m==null||!Y.matches(m))return[p,m];if(!await f())return[p,m]}while(!0)}}return new t(r)},en=async(r,e,t,n,s)=>{const[a,c]=await r.send(e,t,n,s);if(c!=null)throw c;return a},tn=()=>at.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),rn=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown().optional(),error:i.z.optional(Ie)});class nn{constructor(e,t,n,s){y(this,"encoder");y(this,"reqSchema");y(this,"resSchema");y(this,"ws");y(this,"serverClosed");y(this,"sendClosed");y(this,"receiveDataQueue",[]);y(this,"receiveCallbacksQueue",[]);this.encoder=t,this.reqSchema=n,this.resSchema=s,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 ae(e.error)}return null}send(e){if(this.serverClosed!=null)return new P;if(this.sendClosed)throw new L;return this.ws.send(this.encoder.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");return this.serverClosed=ae(e.error),[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.encoder.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){const e=this.receiveDataQueue.shift();return e??await new Promise((t,n)=>this.receiveCallbacksQueue.push({resolve:t,reject:n}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=e=>this.addMessage(this.encoder.decode(e.data,rn)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:cn(e)?P.TYPE:L.TYPE,data:""}})}}const sn="freighterctx",an=1e3,on=1001,un=[an,on],cn=r=>un.includes(r.code),oe=class oe extends lt{constructor(t,n,s=!1){super();y(this,"baseUrl");y(this,"encoder");this.baseUrl=t.replace({protocol:s?"wss":"ws"}),this.encoder=n}async stream(t,n,s){const a=tn();let c;const[,d]=await this.executeMiddleware({target:t,protocol:"websocket",params:{},role:"client"},async f=>{const p=a(this.buildURL(t,f)),m={...f,params:{}};p.binaryType=oe.MESSAGE_TYPE;const l=await this.wrapSocket(p,n,s);return l instanceof Error?[m,l]:(c=l,[m,null])});if(d!=null)throw d;return c}buildURL(t,n){const s=Nr({[ht]:this.encoder.contentType,...n.params},sn);return this.baseUrl.child(t).toString()+s}async wrapSocket(t,n,s){return await new Promise(a=>{t.onopen=()=>{const c=new nn(t,this.encoder,n,s);c.receiveOpenAck().then(d=>{d!=null?a(d):a(c)}).catch(d=>a(d))},t.onerror=c=>{const d=c;a(new Error(d.message))}})}};y(oe,"MESSAGE_TYPE","arraybuffer");let Oe=oe;exports.BaseTypedError=ee;exports.EOF=P;exports.HTTPClient=Qr;exports.StreamClosed=L;exports.Unreachable=Y;exports.WebSocketClient=Oe;exports.decodeError=ae;exports.encodeError=Hr;exports.errorMatcher=ce;exports.errorZ=Ie;exports.registerError=ct;exports.sendRequired=en;exports.unaryWithBreaker=_r;
|
|
11
|
+
`);return new $({data:r,dataType:v.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount<=0){console.warn("attempted to release a series with a negative reference count");return}this._refCount--,this._refCount===0&&this.gl.control!=null&&this.maybeGarbageCollectGLBuffer(this.gl.control)}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===L)return 0;const t=this.byteCapacity.valueOf()-this.writePos,r=e.subBytes(0,t);return this.writeToUnderlyingData(r),this.writePos+=r.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=r.length,this.calculateCachedLength()),r.length}writeFixed(e){if(this.writePos===L)return 0;const t=this.capacity-this.writePos,r=e.sub(0,t);return this.writeToUnderlyingData(r),this._cachedLength=void 0,this.maybeRecomputeMinMax(r),this.writePos+=r.length,r.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===L?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(v.STRING,v.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
|
|
12
|
+
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(v.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=v.UUID.density.valueOf(),t=Array(this.length);for(let r=0;r<this.length;r++){const n=this.underlyingData.slice(r*e,(r+1)*e),a=Array.from(new Uint8Array(n.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[r]=a}return t}parseJSON(e){if(!this.dataType.equals(v.JSON))throw new Error("cannot parse non-JSON series as JSON");return new TextDecoder().decode(this.underlyingData).split(`
|
|
13
|
+
`).slice(0,-1).map(t=>e.parse(de.decodeString(t)))}get byteCapacity(){return new Ee(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===L?this.byteCapacity:this.dataType.isVariable?new Ee(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===L?this.data.length: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((r,n)=>{r===ze&&(e++,t.push(n+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let n=0;n<this.length;n++)r[n]=cr(this.dataType,e,this.data[n],t);return new $({data:r.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(v.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,r)=>t>r?t:r)}else{const e=this.data;this._cachedMax=e.reduce((t,r)=>t>r?t:r)}return this._cachedMax}get max(){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._cachedMax=this.calcRawMax()),te(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(v.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,r)=>t<r?t:r)}else{const e=this.data;this._cachedMin=e.reduce((t,r)=>t<r?t:r)}return this._cachedMin}get min(){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._cachedMin=this.calcRawMin()),te(this._cachedMin,this.sampleOffset))}get bounds(){return F(Number(this.min),Number(this.max))}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)}}enrich(){this.max,this.min}get range(){return te(this.max,-this.min)}atAlignment(e,t){const r=Number(e-this.alignment);if(r<0||r>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return te(r,this.sampleOffset)}atVariable(e,t){let r=0,n=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],n=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]===ze){if(e===0){n=o;break}r=o+1,e--}if(n===0&&(n=this.data.length),r>=n||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,n);return this.dataType.equals(v.STRING)?new TextDecoder().decode(a):Re(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,r=this.length-1;const n=Ns(e);for(;t<=r;){const a=Math.floor((t+r)/2),o=n(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:r=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(v.FLOAT32)&&!this.dataType.equals(v.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:r,prevBuffer:n}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==n)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==L){n===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(n).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=L}as(e){return gr(e,this.dataType),this}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:nt(this.alignmentBounds.lower),upper:nt(this.alignmentBounds.upper)},timeRange:(e=this.timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return F(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 yr(this);return this.dataType.equals(v.JSON)?new wr(e):e}return new mr(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new _e(this,e,t??this.length)}subAlignmentIterator(e,t){return new _e(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,t);return new $({data:r,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,r){if(t<=0&&(r==null||r>=this.length))return this;let n;return e?n=this.data.subarray(t,r):n=this.data.slice(t,r),new $({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new $({data:this.buffer,dataType:this.dataType,timeRange:ie.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){var e,t;let r=`${this.dataType.toString()} ${this.length} [`;if(this.length<=10)r+=Array.from(this).map(n=>n.toString());else{for(let n=0;n<5;n++)r+=`${(e=this.at(n))==null?void 0:e.toString()}`,n<4&&(r+=",");r+="...";for(let n=-5;n<0;n++)r+=(t=this.at(n))==null?void 0:t.toString(),n<-1&&(r+=",")}return r+="]",r}};h(se,"crudeZ",i.z.object({timeRange:ie.z.optional(),dataType:v.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([dr,fr,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:ur.optional().default("static").optional()})),h(se,"z",se.crudeZ.transform(s=>new se(s)));let pr=se,_e=class{constructor(e,t,r){h(this,"series"),h(this,"end"),h(this,"index"),this.series=e;const n=F(0,e.length);this.end=Ze(n,r),this.index=Ze(n,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}};class yr{constructor(e){if(h(this,"series"),h(this,"index"),h(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==ze;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}[Symbol.iterator](){return this}}var et,tt;const It=class Ut{constructor(e){h(this,"wrapped"),h(this,et,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:de.decodeString(e.value,Ut.SCHEMA)}}[(tt=Symbol.iterator,et=Symbol.toStringTag,tt)](){return this}};h(It,"SCHEMA",i.z.record(i.z.string(),i.z.unknown()));let wr=It;var st,rt;class mr{constructor(e){h(this,"series"),h(this,"index"),h(this,st,"SeriesIterator"),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)}}[(rt=Symbol.iterator,st=Symbol.toStringTag,rt)](){return this}}const nt=s=>{const e=s>>32n,t=s&0xffffffffn;return{domain:e,sample:t}};i.z.object({key:i.z.string(),value:i.z.string()});i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const xt=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",br=xt(),Nt=["macOS","Windows","Linux"],vr=["macos","windows","linux"],Tr={macos:"macOS",windows:"Windows",linux:"Linux"},Or=i.z.enum(Nt).or(i.z.enum(vr).transform(s=>Tr[s])),Sr=()=>{if(typeof window>"u")return;const s=window.navigator.userAgent.toLowerCase();if(s.includes("mac"))return"macOS";if(s.includes("win"))return"Windows";if(s.includes("linux"))return"Linux"};let Oe;const Ir=(s={})=>{const{force:e,default:t}=s;return e??Oe??(Oe=Sr(),Oe??t)},Et=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Nt,RUNTIME:br,detect:xt,getOS:Ir,osZ:Or},Symbol.toStringTag,{value:"Module"}));var Ur=Object.defineProperty,xr=(s,e,t)=>e in s?Ur(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,re=(s,e,t)=>xr(s,typeof e!="symbol"?e+"":e,t);const Nr=(...s)=>s.map(zt).join(""),zt=s=>(s.endsWith("/")||(s+="/"),s.startsWith("/")&&(s=s.slice(1)),s),Er=s=>s.endsWith("/")?s.slice(0,-1):s,zr=(s,e="")=>s===null?"":`?${Object.entries(s).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,r])=>`${e}${t}=${r}`).join("&")}`,Ae=class Be{constructor({host:e,port:t,protocol:r="",pathPrefix:n=""}){re(this,"protocol"),re(this,"host"),re(this,"port"),re(this,"path"),this.protocol=r,this.host=e,this.port=t,this.path=zt(n)}replace(e){return new Be({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Be({...this,pathPrefix:Nr(this.path,e)})}toString(){return Er(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};re(Ae,"UNKNOWN",new Ae({host:"unknown",port:0}));let Ar=Ae;const Br=-128,$r=127;i.z.number().int().min(Br).max($r);const Mr=-32768,Cr=32767;i.z.number().int().min(Mr).max(Cr);const Rr=-2147483648,Dr=2147483647;i.z.number().int().min(Rr).max(Dr);const kr=-9223372036854775808n,Lr=9223372036854775807n;i.z.bigint().min(kr).max(Lr);const Pr=255;i.z.number().int().min(0).max(Pr);const jr=65535;i.z.number().int().min(0).max(jr);const Fr=4294967295;i.z.number().int().min(0).max(Fr);const Wr=18446744073709551615n;i.z.bigint().min(0n).max(Wr);var Yr=Object.defineProperty,qr=(s,e,t)=>e in s?Yr(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,C=(s,e,t)=>qr(s,typeof e!="symbol"?e+"":e,t);const Vr=async s=>await new Promise(e=>setTimeout(e,w.fromMilliseconds(s).milliseconds));class Hr{constructor(e){C(this,"config"),C(this,"retries"),C(this,"interval"),this.config={baseInterval:new w((e==null?void 0:e.baseInterval)??w.seconds(1)),maxRetries:(e==null?void 0:e.maxRetries)??5,scale:(e==null?void 0:e.scale)??1,sleepFn:(e==null?void 0:e.sleepFn)??Vr},this.retries=0,this.interval=new w(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:t,sleepFn:r}=this.config;return this.retries>=e?!1:(await r(this.interval),this.interval=this.interval.mult(t),this.retries++,!0)}reset(){this.retries=0,this.interval=this.config.baseInterval}}const Zr=i.z.object({baseInterval:w.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Gr=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Hr,breakerConfig:Zr},Symbol.toStringTag,{value:"Module"})),Kr=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Pe=i.z.string().regex(Kr),G=i.z.number().min(0).max(255),Jr=i.z.number().min(0).max(1),At=i.z.tuple([G,G,G,Jr]),Bt=i.z.tuple([G,G,G]),je=(s,e=1)=>{if(typeof s=="string")return Qr(s,e);if(Array.isArray(s)){if(s.length<3||s.length>4)throw new Error(`Invalid color: [${s.join(", ")}]`);return s.length===3?[...s,e]:s}throw new Error(`Invalid color: ${JSON.stringify(s)}`)},Xr=i.z.union([Pe,At,Bt]).transform(s=>je(s)),Qr=(s,e=1)=>{if(!Pe.safeParse(s).success)throw new Error(`Invalid hex color: ${s}`);return s=_r(s),[le(s,0),le(s,2),le(s,4),s.length===8?le(s,6)/255:e]},le=(s,e)=>parseInt(s.slice(e,e+2),16),_r=s=>s.startsWith("#")?s.slice(1):s,en=i.z.union([Pe,At,i.z.string(),Bt]);je("#000000");je("#ffffff");const tn=i.z.object({key:i.z.string(),color:en,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(tn);const sn=i.z.object({key:i.z.string(),name:i.z.string(),color:Xr});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(sn)});const rn=i.z.number().int().min(0).max(255),nn=i.z.object({name:i.z.string(),key:i.z.string()}),pe=s=>i.z.object({subject:nn,resource:s,authority:rn}),an=i.z.object({from:pe(i.z.any()),to:i.z.null()}),on=i.z.object({from:i.z.null(),to:pe(i.z.any())});i.z.union([an,on,i.z.object({from:pe(i.z.any()),to:pe(i.z.any())})]);const hn=s=>Object.getOwnPropertySymbols(globalThis).includes(s),un=(s,e)=>{const t=Symbol.for(s);if(!hn(t)){const r=e();Object.defineProperty(globalThis,t,{value:r})}return()=>globalThis[t]},cn=s=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(s):e instanceof Error?e.message.startsWith(s):typeof e!="string"?!1:e.startsWith(s),we=s=>{var e;return e=class extends Error{constructor(t,r){super(t,r),C(this,"discriminator",e.discriminator),C(this,"type",e.TYPE),C(this,"matches",e.matches),this.name=e.TYPE}static sub(t){return we(`${s}.${t}`)}},C(e,"discriminator","FreighterError"),C(e,"TYPE",s),C(e,"matches",cn(s)),e},$t=s=>{if(s==null||typeof s!="object")return!1;const e=s;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},H="unknown",$e="nil";class ln{constructor(){C(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:$e,data:""};if($t(e))for(const t of this.providers){const r=t.encode(e);if(r!=null)return r}if(e instanceof Error)return{type:H,data:e.message};if(typeof e=="string")return{type:H,data:e};try{return{type:H,data:JSON.stringify(e)}}catch{return{type:H,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===$e)return null;if(e.type===H)return new Me(e.data);for(const t of this.providers){const r=t.decode(e);if(r!=null)return r}return new Me(e.data)}}const Fe=un("synnax-error-registry",()=>new ln),dn=({encode:s,decode:e})=>Fe().register({encode:s,decode:e}),fn=s=>Fe().encode(s),gn=s=>s==null?null:Fe().decode(s);class Me extends we("unknown"){}const pn=i.z.object({type:i.z.string(),data:i.z.string()});class yn extends we("canceled"){}const j=Object.freeze(Object.defineProperty({__proto__:null,Canceled:yn,NONE:$e,UNKNOWN:H,Unknown:Me,createTyped:we,decode:gn,encode:fn,isTyped:$t,payloadZ:pn,register:dn},Symbol.toStringTag,{value:"Module"}));i.object({jsonrpc:i.string(),id:i.number().optional(),method:i.string().optional(),params:i.unknown().optional(),result:i.unknown().optional()});i.z.string().regex(/^\d+\.\d+\.\d+$/);const wn=["standard","scientific","engineering"];i.z.enum(wn);class he extends j.createTyped("freighter"){}class W extends he.sub("eof"){constructor(){super("EOF")}}class Y extends he.sub("stream_closed"){constructor(){super("StreamClosed")}}class q extends he.sub("unreachable"){constructor(t={}){const{message:r="Unreachable",url:n=Ar.UNKNOWN}=t;super(r);S(this,"url");this.url=n}}const mn=s=>{if(!s.type.startsWith(he.TYPE))return null;if(W.matches(s))return{type:W.TYPE,data:"EOF"};if(Y.matches(s))return{type:Y.TYPE,data:"StreamClosed"};if(q.matches(s))return{type:q.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${s.type}: ${s.message}`)},bn=s=>{if(!s.type.startsWith(he.TYPE))return null;switch(s.type){case W.TYPE:return new W;case Y.TYPE:return new Y;case q.TYPE:return new q;default:throw new j.Unknown(`Unknown error type: ${s.data}`)}};j.register({encode:mn,decode:bn});class Mt{constructor(){S(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let r=0;const n=async a=>{if(r===this.middleware.length)return await t(a);const o=this.middleware[r];return r++,await o(a,n)};return await n(e)}}const Ct="Content-Type",it=s=>{if(Et.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(s==="http")return e;const t=require("https"),r=new t.Agent({rejectUnauthorized:!1});return async(n,a)=>await e(n,{...a,agent:r})},vn=s=>"code"in s&&s.code==="ECONNREFUSED"||s.message.toLowerCase().includes("load failed"),Tn=400;class On extends Mt{constructor(t,r,n=!1){super();S(this,"endpoint");S(this,"encoder");S(this,"fetch");return this.endpoint=t.replace({protocol:n?"https":"http"}),this.encoder=r,this.fetch=it(this.endpoint.protocol),new Proxy(this,{get:(a,o,c)=>o==="endpoint"?this.endpoint:Reflect.get(a,o,c)})}get headers(){return{[Ct]:this.encoder.contentType}}async send(t,r,n,a){r=n==null?void 0:n.parse(r);let o=null;const c=this.endpoint.child(t),d={};d.method="POST",d.body=this.encoder.encode(r??{});const[,p]=await this.executeMiddleware({target:c.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async y=>{const l={...y,params:{}};d.headers={...this.headers,...y.params};let U;try{U=await it(y.protocol)(y.target,d)}catch(R){let z=R;return vn(z)&&(z=new q({url:c})),[l,z]}const A=new Uint8Array(await(await U.blob()).arrayBuffer());if(U!=null&&U.ok)return a!=null&&(o=this.encoder.decode(A,a)),[l,null];try{if(U.status!==Tn)return[l,new Error(U.statusText)];const R=this.encoder.decode(A,j.payloadZ),z=j.decode(R);return[l,z]}catch(R){return[l,new Error(`[freighter] - failed to decode error: ${U.statusText}: ${R.message}`)]}});return p!=null?[null,p]:[o,null]}}const Sn=(s,e)=>{class t{constructor(n){S(this,"wrapped");this.wrapped=n}use(...n){this.wrapped.use(...n)}async send(n,a,o,c){const d=new Gr.Breaker(e);do{const[p,y]=await this.wrapped.send(n,a,o,c);if(y==null)return[p,null];if(!q.matches(y))return[null,y];if(!await d.wait())return[p,y]}while(!0)}}return new t(s)},In=async(s,e,t,r,n)=>{const[a,o]=await s.send(e,t,r,n);if(o!=null)throw o;return a},Un=()=>Et.RUNTIME!=="node"?s=>new WebSocket(s):s=>new(require("ws")).WebSocket(s,{rejectUnauthorized:!1}),xn=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown(),error:i.z.optional(j.payloadZ)});class Nn{constructor(e,t,r,n){S(this,"codec");S(this,"reqSchema");S(this,"resSchema");S(this,"ws");S(this,"serverClosed");S(this,"sendClosed");S(this,"receiveDataQueue",[]);S(this,"receiveCallbacksQueue",[]);this.codec=t,this.reqSchema=r,this.resSchema=n,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 j.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new W;if(this.sendClosed)throw new Y;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");return this.serverClosed=j.decode(e.error),[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(){const e=this.receiveDataQueue.shift();return e??await new Promise((t,r)=>this.receiveCallbacksQueue.push({resolve:t,reject:r}))}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,xn))}onClose(e){this.addMessage({type:"close",error:{type:e.code===zn?W.TYPE:Y.TYPE,data:""}})}}const En="freighterctx",zn=1e3,ae=class ae extends Mt{constructor(t,r,n=!1){super();S(this,"baseUrl");S(this,"encoder");S(this,"secure");this.secure=n,this.baseUrl=t.replace({protocol:n?"wss":"ws"}),this.encoder=r}withCodec(t){const r=new ae(this.baseUrl,t,this.secure);return r.use(...this.middleware),r}async stream(t,r,n){const a=Un();let o;const[,c]=await this.executeMiddleware({target:t,protocol:"websocket",params:{},role:"client"},async d=>{const p=a(this.buildURL(t,d)),y={...d,params:{}};p.binaryType=ae.MESSAGE_TYPE;const l=await this.wrapSocket(p,r,n);return l instanceof Error?[y,l]:(o=l,[y,null])});if(c!=null)throw c;return o}buildURL(t,r){const n=zr({[Ct]:this.encoder.contentType,...r.params},En);return this.baseUrl.child(t).toString()+n}async wrapSocket(t,r,n){return await new Promise(a=>{t.onopen=()=>{const o=new Nn(t,this.encoder,r,n);o.receiveOpenAck().then(c=>{c!=null?a(c):a(o)}).catch(c=>a(c))},t.onerror=o=>{const c=o;a(new Error(c.message))}})}};S(ae,"MESSAGE_TYPE","arraybuffer");let Ce=ae;exports.EOF=W;exports.HTTPClient=On;exports.StreamClosed=Y;exports.Unreachable=q;exports.WebSocketClient=Ce;exports.sendRequired=In;exports.unaryWithBreaker=Sn;
|