@kymoscope/sdk 0.1.1 → 0.2.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.
@@ -203,7 +203,7 @@ export declare function createEngine(options?: EngineOptions): {
203
203
  remove(id: string): void;
204
204
  reorder(from: number, to: number): void;
205
205
  activate(id: string): void;
206
- /** Change the shared X column. Drops series on it and clears zoom, offsets and colours. */
206
+ /** Change the shared X column. Drops series on it and clears zoom and offsets (in X units); colours stay. */
207
207
  setXKey(id: string, key: string): void;
208
208
  };
209
209
  charts: {
@@ -133,6 +133,8 @@ export interface LiveConnectionInfo {
133
133
  selected: boolean;
134
134
  /** Trace colour when several sources are plotted together. */
135
135
  color: string;
136
+ /** True when the colour was set with `datasets.setColor` (not the palette default). */
137
+ customColor: boolean;
136
138
  /** When a recording is running: its start time (ms since epoch), else null. */
137
139
  recordingSince: number | null;
138
140
  }
@@ -23,6 +23,7 @@ export type { ChartView, ChartViewEvents, MountOptions, ChartStyle } from './cha
23
23
  export type { ChartWindow, ChartWindowOptions } from './charts/chartWindow';
24
24
  export type { ChartStatus, ContextMenuEvent } from './charts/ChartBody';
25
25
  export * from './lib/panelChartSettings';
26
+ export { chartChannelCount } from './lib/chartChannels';
26
27
  export { ANNOTATION_KINDS, DEFAULT_ANNOTATION_WIDTH, type AnnotationKind, type AnnotationTool, type ChartAnnotation } from './lib/annotations';
27
28
  export { ANNOTATION_CONTROLS_ATTR } from './charts/AnnotationLayer';
28
29
  export { colorAt, colorsCss, presetStops, type GaugeColorMode, type GaugeColorStop, type GaugePreset } from './lib/gaugeColors';
@@ -0,0 +1,3 @@
1
+ import type { PanelChartSettings } from './panelChartSettings';
2
+ /** Channels a chart holds in its open-ended lists; fixed slots (X, Y, color, group…) don't count. */
3
+ export declare function chartChannelCount(s: PanelChartSettings): number;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Wire v2: KIND_BLOCK_SCHEMA carries the channel table once (the relay keeps the latest for viewers who join and
3
+ * puts it first in every recording chunk); KIND_BLOCK rows refer to it by id, with µs time deltas and byte-split
4
+ * values, deflate-compressed before sealing. Normative format: docs/superpowers/plans/2026-10-23-historian-phase1.md;
5
+ * pinned by tests/vectors/block-v2.json; byte-compatible with packages/python/src/kymoscope/wire.py.
6
+ */
7
+ import type { LiveColumnsBlock } from './buffer';
8
+ export interface BlockChannel {
9
+ name: string;
10
+ unit: string;
11
+ size: 4 | 8;
12
+ }
13
+ export interface BlockSchema {
14
+ id: number;
15
+ channels: BlockChannel[];
16
+ }
17
+ /** The channel table of a decrypted KIND_BLOCK_SCHEMA plaintext. Throws RangeError if malformed. */
18
+ export declare function decodeBlockSchema(p: Uint8Array): BlockSchema;
19
+ /** KIND_BLOCK_SCHEMA plaintext with a given id (tests and local publishers; senders use the CRC-32 of the table). */
20
+ export declare function encodeBlockSchema(id: number, channels: BlockChannel[]): Uint8Array;
21
+ /** A decrypted KIND_BLOCK plaintext's rows; null until its schema has arrived. Throws RangeError if malformed. */
22
+ export declare function decodeBlock(p: Uint8Array, schemas: ReadonlyMap<number, BlockSchema>): Promise<{
23
+ block: LiveColumnsBlock;
24
+ historical: boolean;
25
+ } | null>;
26
+ /** KIND_BLOCK plaintext of `block` under `schema` (tests and local publishers). Little-endian hosts only. */
27
+ export declare function encodeBlock(block: {
28
+ t: ArrayLike<number>;
29
+ columns: Record<string, ArrayLike<number>>;
30
+ }, schema: BlockSchema, o?: {
31
+ historical?: boolean;
32
+ compress?: boolean;
33
+ }): Promise<Uint8Array>;
@@ -62,6 +62,8 @@ export declare class LiveBuffer {
62
62
  private lastPushT;
63
63
  /** Cached bucket map for the incremental live pull; see {@link decimateColumns}. */
64
64
  private decCache;
65
+ /** Where the newest pass of a wrapping X starts (see {@link passStart}). */
66
+ private passTrack;
65
67
  /** The previous cycle's points (see decimateCyclePoints). */
66
68
  private prevCyclePts;
67
69
  /** The current cycle's buckets, kept across pulls (see decimateCyclePoints). */
@@ -185,6 +187,15 @@ export declare class LiveBuffer {
185
187
  * full scan clipped to the visible samples — bounded, just not cached.
186
188
  */
187
189
  decimateColumns(xKey: string, columns: string[], x0: number, x1: number, maxPoints: number): MultiSeriesResult;
190
+ /**
191
+ * Absolute index where the newest pass on `xKey` starts. A wrapping X (lap
192
+ * distance) restarts at the finish line: a single-sample drop of more than half
193
+ * the buffered X range starts a new pass. A non-wrapping channel (e.g. speed)
194
+ * never drops that much between two samples, so it stays one pass. Only the
195
+ * samples since the last call are read; the drops they make are kept as
196
+ * candidates and re-checked against the range as it is now.
197
+ */
198
+ private passStart;
188
199
  /** Logical index (0 = oldest) of the first sample whose time is ≥ `t` (time ascending). */
189
200
  private timeIndex;
190
201
  /** Fold the samples at logical indices [from, to) into `store` (time ascending). */
@@ -245,7 +256,6 @@ export declare class LiveBuffer {
245
256
  x0: number;
246
257
  x1: number;
247
258
  };
248
- private scanBounds;
249
259
  /**
250
260
  * Snapshot of the buffer as a Dataset, rows ordered oldest → newest.
251
261
  *
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * NaN marks a missing value. Every array starts 8-byte aligned, so a reader
17
17
  * views them in place (no copy). Byte-compatible with
18
- * examples/kymoscope_live/wire.py (encode_columns / decode_columns).
18
+ * packages/python/src/kymoscope/wire.py (encode_columns / decode_columns).
19
19
  */
20
20
  import type { LiveColumnsBlock } from './buffer';
21
21
  /** The block in a decrypted KIND_COLUMNS plaintext; arrays are views of it. Throws RangeError if malformed. */
@@ -2,6 +2,10 @@ export declare const KIND_SCHEMA = 1;
2
2
  export declare const KIND_FRAMES = 2;
3
3
  /** A block of samples by column (see columnsWire.ts): what high-rate publishers send. */
4
4
  export declare const KIND_COLUMNS = 3;
5
+ /** Rows referring to a channel table by id, compressed before sealing (see blockWire.ts). */
6
+ export declare const KIND_BLOCK = 4;
7
+ /** The channel table KIND_BLOCK messages refer to (see blockWire.ts). */
8
+ export declare const KIND_BLOCK_SCHEMA = 5;
5
9
  export declare const KEY_ID_FLAG = 128;
6
10
  export interface SealedMessage {
7
11
  kind: number;
@@ -11,7 +11,7 @@ export interface Worksheet {
11
11
  panelChartBackgrounds: Record<string, string | null>;
12
12
  xKey: string;
13
13
  }
14
- export interface TyresPlotSavedLayout {
14
+ export interface KymoscopeSavedLayout {
15
15
  version: typeof SAVED_LAYOUT_VERSION;
16
16
  worksheets: Worksheet[];
17
17
  activeWorksheetId?: string;
@@ -40,6 +40,6 @@ export interface TyresPlotSavedLayout {
40
40
  panelChartSettings: Record<string, PanelChartSettings>;
41
41
  }
42
42
  /** Accept v2–v9; normalize to current shape + panel settings. */
43
- export declare function parseSavedLayoutFile(v: unknown): TyresPlotSavedLayout | null;
43
+ export declare function parseSavedLayoutFile(v: unknown): KymoscopeSavedLayout | null;
44
44
  /** @deprecated use parseSavedLayoutFile */
45
- export declare function isTyresPlotSavedLayout(v: unknown): v is TyresPlotSavedLayout;
45
+ export declare function isKymoscopeSavedLayout(v: unknown): v is KymoscopeSavedLayout;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kymoscope/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "The Kymoscope data engine and charts for the browser: import large measurement files, plot them, stream live data end-to-end encrypted.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "homepage": "https://kymoscope.com/docs/introduction",
@@ -1,5 +0,0 @@
1
- /*! @kymoscope/sdk (c) 2026 Kymoscope. Proprietary software: use requires a license. See LICENSE.md. */
2
- import{Ct as e,Et as t,St as n,Tt as r,_t as i,at as a,bt as o,d as s,ft as c,gt as l,ht as u,i as d,mt as f,n as p,ot as m,pt as h,r as g,s as _,st as v,u as y,vt as b,wt as x,xt as S,yt as ee}from"./krc-CbE28CjD.js";function C(e,t){return e.selection.find(e=>e.group===t)?.channels??[]}var w=4096,te={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,exp:Math.exp,ln:Math.log,log:Math.log,log10:Math.log10,sqrt:Math.sqrt,abs:Math.abs,pow:Math.pow,min:Math.min,max:Math.max};function T(e){if(e.length>w)return null;let t=e.match(/\d+\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|\*\*|[-+*/^(),]|\S/g)??[],n=0,r=()=>t[n],i=()=>{throw Error(`formula`)},a=e=>{t[n++]!==e&&i()},o=()=>{let e=s();for(;r()===`+`||r()===`-`;){let r=t[n++],i=e,a=s();e=r===`+`?e=>i(e)+a(e):e=>i(e)-a(e)}return e},s=()=>{let e=c();for(;r()===`*`||r()===`/`;){let r=t[n++],i=e,a=c();e=r===`*`?e=>i(e)*a(e):e=>i(e)/a(e)}return e},c=()=>{if(r()===`-`){n++;let e=c();return t=>-e(t)}return r()===`+`?(n++,c()):l()},l=()=>{let e=u();if(r()===`^`||r()===`**`){n++;let t=c();return n=>e(n)**t(n)}return e},u=()=>{let e=t[n++];if(e===void 0&&i(),e===`(`){let e=o();return a(`)`),e}if(/^[\d.]/.test(e)){let t=Number(e);return Number.isFinite(t)||i(),()=>t}if(e===`X`||e===`x`||e===`X1`)return e=>e;if(Object.hasOwn(te,e)){let t=te[e];a(`(`);let i=[o()];for(;r()===`,`;)n++,i.push(o());return a(`)`),i.length===1?e=>t(i[0](e)):e=>t(...i.map(t=>t(e)))}return i()};try{let e=o();return n===t.length?e:null}catch{return null}}var E={k:`id`};function ne(e,t){let{keys:n,vals:r}=e,i=n.length;if(i===0)return t;if(t<=n[0])return r[0];if(t>=n[i-1])return r[i-1];let a=0,o=i-1;for(;o-a>1;){let e=a+o>>1;n[e]<=t?a=e:o=e}return e.interp?r[a]+(r[o]-r[a])*(t-n[a])/(n[o]-n[a]):t-n[a]<=n[o]-t?r[a]:r[o]}function re(e,t){let n=t.length;switch(e.k){case`lin`:{let{a:r,b:i}=e;if(r===1&&i===0)return;for(let e=0;e<n;e++)t[e]=r*t[e]+i;return}case`rat`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e];t[e]=(r*n*n+i*n+a)/(o*n*n+s*n+c)}return}case`poly`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e]-s-c;t[e]=(i-o*n)/(a*n-r)}return}case`alg`:{let r=e.f;for(let e=0;e<n;e++)t[e]=r(t[e]);return}case`tab`:for(let r=0;r<n;r++)t[r]=ne(e,t[r]);return;case`rtv`:for(let r=0;r<n;r++){let n=t[r],i=e.def;for(let t=0;t<e.lo.length;t++)if(n>=e.lo[t]&&n<=e.hi[t]){i=e.vals[t];break}t[r]=i}return;default:return}}function ie(e,t){let n=Float64Array.of(t);return re(e,n),n[0]}var D=(e,t)=>e===null||typeof e==`string`?e:String(ie(e,t));function O(e,t){let n=Array(t.length),r=e.ranges.every(e=>e.lo===e.hi)?new Map(e.ranges.map(e=>[e.lo,e.to])):null;for(let i=0;i<t.length;i++){let a=t[i];if(a!==a){n[i]=null;continue}let o=e.def;if(r){let e=r.get(a);e!==void 0&&(o=e)}else for(let t of e.ranges)if(a>=t.lo&&(e.int||t.lo===t.hi?a<=t.hi:a<t.hi)){o=t.to;break}n[i]=D(o,a)}return n}function ae(e,t){let n=(e,t)=>({type:e,bigEndian:t,encoding:`latin1`});switch(e){case 0:return n(`uint`,!t);case 1:return n(`int`,!t);case 2:case 3:return n(`float`,!t);case 7:return n(`string`,!1);case 8:return n(`bytes`,!1);case 9:return n(`uint`,!0);case 10:return n(`int`,!0);case 11:case 12:return n(`float`,!0);case 13:return n(`uint`,!1);case 14:return n(`int`,!1);case 15:case 16:return n(`float`,!1);default:return null}}async function k(e,n,r){let i=t(n).getUint16(24,!0)===0,a=async n=>{let r=t(await e.read(n,4)).getUint16(2,i),a=await e.read(n,r);return{id:o(a.subarray(0,2)),v:t(a),b:a,size:r}},s=(e,t)=>e.getUint32(t,i),c=(e,t)=>e.getUint16(t,i),l=(e,t)=>e.getFloat64(t,i),u=async e=>e?S((await a(e)).b.subarray(4),!0):``,d=[],f=new Set,p=e=>{if(f.has(e))throw Error(`This MDF file is damaged (its blocks link in a loop).`);f.add(e)},m=async(e,t)=>{if(!e)return{conv:E,unit:``};let{v:n,b:r}=await a(e),i=S(r.subarray(22,42),!0),o=c(n,42),d=c(n,44),f=e=>l(n,46+8*e);switch(o){case 0:return{conv:{k:`lin`,a:f(1),b:f(0)},unit:i};case 1:case 2:{let e=new Float64Array(d),t=new Float64Array(d);for(let n=0;n<d;n++)e[n]=f(2*n),t[n]=f(2*n+1);return{conv:{k:`tab`,keys:e,vals:t,interp:o===1},unit:i}}case 6:return{conv:{k:`poly`,p:[0,1,2,3,4,5].map(f)},unit:i};case 9:return{conv:{k:`rat`,p:[0,1,2,3,4,5].map(f)},unit:i};case 10:{let e=S(r.subarray(46,302),!0),t=T(e);return{conv:t?{k:`alg`,f:t}:{k:`unsupported`,what:`the formula "${e}"`},unit:i}}case 11:return{conv:{k:`text`,ranges:Array.from({length:d},(e,t)=>{let i=46+40*t,a=l(n,i);return{lo:a,hi:a,to:S(r.subarray(i+8,i+40),!0)}}),def:null,int:t},unit:i};case 12:{let e=await Promise.all(Array.from({length:d},async(e,t)=>{let r=46+20*t;return{lo:l(n,r),hi:l(n,r+8),to:await u(s(n,r+16))}}));return{conv:{k:`text`,ranges:e.slice(1),def:e[0]?.to??null,int:t},unit:i}}case 65535:return{conv:E,unit:i};default:return{conv:{k:`unsupported`,what:`MDF3 conversion type ${o}`},unit:i}}},h=await a(64),g=null;if(h.size>=172&&(s(h.v,164)||s(h.v,168))){let e=s(h.v,168)*4294967296+s(h.v,164);g=new Date(e/1e6).toISOString()}else{let e=o(h.b.subarray(18,28)),t=o(h.b.subarray(28,36));/^\d\d:\d\d:\d{4}$/.test(e)&&(g=`${e.slice(6)}-${e.slice(3,5)}-${e.slice(0,2)}T${t}`)}let _=[],v=0;for(let e=s(h.v,4),t=0;e;t++){p(e);let n=await a(e),r=c(n.v,22),o=[];for(let e=s(n.v,8);e;){p(e);let n=await a(e),l=[],f=null;for(let e=s(n.v,8);e;){p(e);let t=await a(e),n=S(t.b.subarray(26,58),!0),r=(t.size>=222?await u(s(t.v,218)):``)||n,o=ae(c(t.v,190),i),h=c(t.v,186)+(t.size>=228?8*c(t.v,226):0);if(!o)d.push(`${r}: MDF3 data type ${c(t.v,190)} is not supported; skipped.`);else{let{conv:e,unit:n}=await m(s(t.v,8),o.type!==`float`),i={name:r,unit:n,kind:c(t.v,24)===1?`master`:`value`,...o,conv:e,sd:null,sdRecordId:null,byteOffset:h>>3,bitOffset:h&7,bitCount:c(t.v,188),invalBit:null,allInvalid:!1};i.kind===`master`&&!f?f=i:i.kind===`value`&&l.push(i)}e=s(t.v,4)}v++,o.push({name:await u(s(n.v,12))||`Group ${v}`,dg:t,recordId:c(n.v,16),recordIdSize:+(r>0),idTrailer:+(r===2),dataBytes:c(n.v,20),invalBytes:0,cycles:s(n.v,22),vlsdCg:!1,sorted:!0,master:f,channels:l,stream:[],busType:0,busEvent:!1}),e=s(n.v,4)}let l=o.reduce((e,t)=>e+t.cycles*(t.recordIdSize+t.dataBytes+t.idTrailer),0),f=[{offset:s(n.v,16),length:l,zip:null}];for(let e of o)e.stream=f,e.sorted=o.length===1,_.push(e);e=s(n.v,4)}return{version:`MDF ${r}`,startTime:g,groups:_,notes:d,meta:{}}}var oe=`This MF4 is damaged (its blocks link in a loop).`;function A(e,t){if(e.seen.has(t))throw Error(oe);e.seen.add(t)}async function j(e,n){let r=await e.read(n,24);if(r.length<24)throw Error(`This MF4 is damaged (bad block at byte ${n}).`);let i=t(r),a=o(r.subarray(0,4)),s=x(i,8),c=x(i,16);if(!a.startsWith(`##`)||s<24+8*c||s>1<<26)throw Error(`This MF4 is damaged (bad block at byte ${n}).`);let l=await e.read(n,s);if(l.length<s)throw Error(`This MF4 is damaged (the block at byte ${n} runs past the end of the file).`);let u=t(l),d=[];for(let e=0;e<c;e++)d.push(x(u,24+8*e));let f=l.subarray(24+8*c);return{id:a,links:d,data:t(f),bytes:f}}var M={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`};function se(e){let t=e.indexOf(`<TX>`),n=t<0?-1:e.indexOf(`</TX>`,t+4);return(n>=0?e.slice(t+4,n):e.replace(/<[^<>]*>/g,``)).replace(/&(lt|gt|amp|quot|apos);/g,(e,t)=>M[t]).trim()}function N(e,t){if(!t)return Promise.resolve(``);let n=e.texts.get(t);return n||(n=j(e.io,t).then(e=>{let t=S(e.bytes);return e.id===`##MD`?se(t):t}),e.texts.set(t,n)),n}async function P(e,n,r=0){if(!n)return[];let i=e.io,a=await i.read(n,24),s=o(a.subarray(0,4)),l=a.length<24?0:x(t(a),8);switch(s){case`##DT`:case`##SD`:case`##RD`:return[{offset:n+24,length:l-24,zip:null}];case`##DZ`:{let e=t(await i.read(n+24,24));if(e.byteLength<24)throw Error(`This MF4 is damaged (bad block at byte ${n}).`);let r=e.getUint8(2);if(r===2||r===3)throw Error(`This MF4 uses zstd compression, which isn't supported yet.`);if(r===4||r===5)throw Error(`This MF4 uses LZ4 compression, which isn't supported yet.`);if(r>5)throw Error(`This MF4 is damaged (unknown compression type ${r}).`);let a=e.getUint32(4,!0),o=x(e,8),s=x(e,16);if(o>c(s)||r===1&&a===0)throw Error(`This MF4 is damaged (bad compressed block at byte ${n}).`);if(r===1&&o>268435456)throw Error(`This MF4 has a compressed block over 256 MB, which Kymoscope cannot read.`);return[{offset:n+48,length:s,zip:{type:r,param:a,orgLength:o}}]}case`##DL`:{if(r>1)throw Error(`This MF4 is damaged (unexpected ${s} block in its data).`);let t=[];for(let r=n;r;){A(e,r);let n=await j(i,r);for(let r of n.links.slice(1))t.push(...await P(e,r,2));r=n.links[0]}return t}case`##HL`:if(r>0)throw Error(`This MF4 is damaged (unexpected ${s} block in its data).`);return A(e,n),P(e,(await j(i,n)).links[0],1);case`##DV`:case`##DI`:throw Error(`This MF4 uses column-oriented storage (MDF 4.2 DV/DI blocks), which Kymoscope cannot read yet.`);default:throw Error(`This MF4 is damaged (unexpected ${s} block in its data).`)}}async function ce(e,t,n){return t?o(await e.io.read(t,4))===`##CC`?le(e,t,n+1):N(e,t):null}async function le(e,t,n=0){if(!t||n>4||e.busy.has(t))return E;let r=e.convs.get(t);if(r)return r;e.busy.add(t);try{let r=await ue(e,t,n);return e.convs.set(t,r),r}finally{e.busy.delete(t)}}async function ue(e,t,n){let r=await j(e.io,t),i=r.data,a=i.getUint8(0),o=i.getUint16(4,!0),s=i.getUint16(6,!0),c=new Float64Array(s);for(let e=0;e<s;e++)c[e]=i.getFloat64(24+8*e,!0);let l=r.links.slice(4,4+o),u=()=>Promise.all(l.map(t=>ce(e,t,n)));switch(a){case 0:return E;case 1:return{k:`lin`,b:c[0],a:c[1]};case 2:return{k:`rat`,p:[...c]};case 3:{let t=await N(e,l[0]),n=T(t);return n?{k:`alg`,f:n}:{k:`unsupported`,what:`the formula "${t}"`}}case 4:case 5:{let e=s>>1,t=new Float64Array(e),n=new Float64Array(e);for(let r=0;r<e;r++)t[r]=c[2*r],n[r]=c[2*r+1];return{k:`tab`,keys:t,vals:n,interp:a===4}}case 6:{let e=Math.max(0,Math.floor((s-1)/3)),t=new Float64Array(e),n=new Float64Array(e),r=new Float64Array(e);for(let i=0;i<e;i++)t[i]=c[3*i],n[i]=c[3*i+1],r[i]=c[3*i+2];return{k:`rtv`,lo:t,hi:n,vals:r,def:c[s-1]}}case 7:{let e=await u();return{k:`text`,ranges:[...c].map((t,n)=>({lo:t,hi:t,to:e[n]??null})),def:e[s]??null,int:!0}}case 8:{let e=await u(),t=s>>1;return{k:`text`,ranges:Array.from({length:t},(t,n)=>({lo:c[2*n],hi:c[2*n+1],to:e[n]??null})),def:e[t]??null,int:!0}}default:return{k:`unsupported`,what:`conversion type ${a}`}}}var de={0:{type:`uint`,bigEndian:!1,encoding:`latin1`},1:{type:`uint`,bigEndian:!0,encoding:`latin1`},2:{type:`int`,bigEndian:!1,encoding:`latin1`},3:{type:`int`,bigEndian:!0,encoding:`latin1`},4:{type:`float`,bigEndian:!1,encoding:`latin1`},5:{type:`float`,bigEndian:!0,encoding:`latin1`},6:{type:`string`,bigEndian:!1,encoding:`latin1`},7:{type:`string`,bigEndian:!1,encoding:`utf-8`},8:{type:`string`,bigEndian:!1,encoding:`utf-16le`},9:{type:`string`,bigEndian:!0,encoding:`utf-16be`},10:{type:`bytes`,bigEndian:!1,encoding:`latin1`}};async function fe(e,t){let{io:n,notes:r}=e,i=t.data,a=i.getUint8(0),s=i.getUint8(1),c=i.getUint8(2),l=await N(e,t.links[2]),u=de[c];if(!u)return r.push(`${l}: data type ${c} is not supported; the channel was skipped.`),null;let d;if(a===2||a===3)if(s===1)d=a===2?`master`:`vmaster`;else{if(r.push(`The master channel ${l} is not time (sync type ${s}): samples are numbered instead.`),a===3)return null;d=`value`}else if(a===1)d=`vlsd`;else if(a===0||a===4)d=`value`;else return r.push(`${l}: channel type ${a} is not supported; skipped.`),null;let f=await le(e,t.links[4]),p=f.k===`text`?{...f,int:u.type!==`float`}:f,m=await N(e,t.links[6]);!m&&t.links[4]&&(m=await N(e,(await j(n,t.links[4])).links[1]));let h=null,g=null;d===`vlsd`&&t.links[5]&&(o(await n.read(t.links[5],4))===`##CG`?g=x((await j(n,t.links[5])).data,0):h=await P(e,t.links[5]));let _=i.getUint32(12,!0);return{name:l,unit:m,kind:d,...u,conv:p,sd:h,sdRecordId:g,byteOffset:i.getUint32(4,!0),bitOffset:i.getUint8(3),bitCount:i.getUint32(8,!0),invalBit:_&2?i.getUint32(16,!0):null,allInvalid:(_&1)!=0}}async function pe(e,t,n,r=0){let{io:i,notes:a}=e;for(let s=t;s;){A(e,s);let t=await j(i,s),c=t.links[1];c&&r<4&&(o(await i.read(c,4))===`##CN`?await pe(e,c,n,r+1):a.push(`${await N(e,t.links[2])}: array channels (CA) are not supported yet; skipped.`));let l=await fe(e,t);l&&n.push(l),s=t.links[0]}}async function me(e,t,n,r){let i=t.data,a=i.getUint16(16,!0),o=0;t.links[3]&&(o=(await j(e.io,t.links[3])).data.getUint8(1));let s={name:await N(e,t.links[2]),dg:n,recordId:x(i,0),recordIdSize:r,idTrailer:0,dataBytes:i.getUint32(24,!0),invalBytes:i.getUint32(28,!0),cycles:x(i,8),vlsdCg:(a&1)!=0,sorted:!0,master:null,channels:[],stream:[],busType:o,busEvent:(a&2)!=0};if(s.vlsdCg)return s;let c=[];await pe(e,t.links[1],c);for(let e of c)e.kind===`master`||e.kind===`vmaster`?s.master||=e:s.channels.push(e);return s}async function he(e,t){let n=await j(e,64);if(n.id!==`##HD`)throw Error(`This MF4 is damaged (no header block).`);let r=x(n.data,0),i=(n.data.getUint8(12)&1)!=0,a=new Date(r/1e6).toISOString(),o=r>0?i?a.slice(0,-1):a:null,s={io:e,notes:[],seen:new Set,texts:new Map,convs:new Map,busy:new Set},c=[],l=0;for(let t=n.links[0],r=0;t;r++){A(s,t);let n=await j(e,t),i=n.data.getUint8(0),a=[];for(let t=n.links[1];t;){A(s,t);let n=await j(e,t),o=await me(s,n,r,i);o.vlsdCg||(l++,o.name||=`Group ${l}`),a.push(o),t=n.links[0]}let o=await P(s,n.links[2]),u=a.length===1;for(let e of a)e.stream=o,e.sorted=u,c.push(e);t=n.links[0]}return{version:`MF4 ${t}`,startTime:o,groups:c,notes:s.notes,meta:{}}}function ge(e){let t=e&32768?-1:1,n=e>>10&31,r=e&1023;return n===0?t*2**-14*(r/1024):n===31?r?NaN:t*(1/0):t*2**(n-15)*(1+r/1024)}function F(e,n,r,i,a,o,s=0){let c=t(n),l=!e.bigEndian,u=a+e.byteOffset,d=e.bitCount;if(e.bitOffset===0)if(e.type===`float`){if(d===64){for(let e=0;e<r;e++,u+=i)o[s+e]=c.getFloat64(u,l);return}if(d===32){for(let e=0;e<r;e++,u+=i)o[s+e]=c.getFloat32(u,l);return}if(d===16){for(let e=0;e<r;e++,u+=i)o[s+e]=ge(c.getUint16(u,l));return}}else if(e.type===`int`){if(d===8){for(let e=0;e<r;e++,u+=i)o[s+e]=c.getInt8(u);return}if(d===16){for(let e=0;e<r;e++,u+=i)o[s+e]=c.getInt16(u,l);return}if(d===32){for(let e=0;e<r;e++,u+=i)o[s+e]=c.getInt32(u,l);return}if(d===64){for(let e=0;e<r;e++,u+=i)o[s+e]=c.getInt32(u+(l?4:0),l)*4294967296+c.getUint32(u+(l?0:4),l);return}}else{if(d===8){for(let e=0;e<r;e++,u+=i)o[s+e]=n[u];return}if(d===16){for(let e=0;e<r;e++,u+=i)o[s+e]=c.getUint16(u,l);return}if(d===32){for(let e=0;e<r;e++,u+=i)o[s+e]=c.getUint32(u,l);return}if(d===64){for(let e=0;e<r;e++,u+=i)o[s+e]=c.getUint32(u+(l?4:0),l)*4294967296+c.getUint32(u+(l?0:4),l);return}}let f=e.bitOffset+d+7>>3,p=2**e.bitOffset,m=2**d,h=m/2,g=e.type===`int`;for(let e=0;e<r;e++,u+=i){let t=0;if(l)for(let e=f-1;e>=0;e--)t=t*256+n[u+e];else for(let e=0;e<f;e++)t=t*256+n[u+e];t=Math.floor(t/p)%m,o[s+e]=g&&t>=h?t-m:t}}var _e=new Map,ve=e=>{let t=_e.get(e);return t||_e.set(e,t=new TextDecoder(e)),t};function ye(e){let t=e.indexOf(`\0`);return t<0?e:e.slice(0,t)}function be(e,t,n,r,i){let a=ve(e.encoding),o=e.bitCount>>3,s=Array(n);for(let c=0,l=i+e.byteOffset;c<n;c++,l+=r)s[c]=ye(a.decode(t.subarray(l,l+o)));return s}function xe(e,t,n,r,i,a){let o=a instanceof Float64Array?NaN:null;if(e.allInvalid){for(let e=0;e<n;e++)a[e]=o;return}if(e.invalBit===null)return;let s=1<<(e.invalBit&7);for(let c=0,l=i+(e.invalBit>>3);c<n;c++,l+=r)t[l]&s&&(a[c]=o)}var I=e=>e.recordIdSize+e.dataBytes+e.invalBytes+e.idTrailer,Se=64<<20,Ce=(e,t)=>e.reduce((e,n)=>e+(n.zip?n.zip.orgLength:Math.max(0,Math.min(n.length,t-n.offset))),0),we=e=>e.byteOffset+Math.ceil((e.bitOffset+e.bitCount)/8);function Te(e,t){return e.kind===`vmaster`?!0:(e.kind===`vlsd`||e.type===`uint`||e.type===`int`||e.type===`float`?!(e.bitCount>=1&&e.bitCount<=64):!(e.bitCount>=8))?!1:we(e)<=t.dataBytes}function Ee(e,t){let n=e.notes;for(let r of e.groups){if(![0,1,2,4,8].includes(r.recordIdSize))throw Error(`This MDF file is damaged (bad record id size).`);if(r.vlsdCg)continue;let e=I(r);if(e>Se||e===0){r.cycles>0&&n.push(`${r.name||`A group`}: its records are ${e===0?`empty`:`too large`} (damaged); skipped.`),r.cycles=0;continue}r.cycles=Math.min(r.cycles,Math.floor(Ce(r.stream,t)/e));let i=r.channels.filter(e=>!Te(e,r));for(let e of i)n.push(`${e.name}: its bits lie outside its record (damaged); skipped.`);i.length&&(r.channels=r.channels.filter(e=>!i.includes(e))),r.master&&!Te(r.master,r)&&(n.push(`${r.master.name}: the time channel lies outside its record (damaged): samples are numbered instead.`),r.master=null);for(let e of r.master?[...r.channels,r.master]:r.channels)e.invalBit!==null&&e.invalBit>=8*r.invalBytes&&(e.invalBit=null)}}function De(e,t){let n=0;for(let r of e.master?[...t,e.master]:t){if(r.invalBit!==null)return 1/0;r.kind!==`vmaster`&&(n=Math.max(n,r.byteOffset+(r.bitOffset+r.bitCount+7>>3)))}return e.recordIdSize+n}var L=Uint8Array,R=Uint16Array,Oe=Int32Array,ke=new L([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ae=new L([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),je=new L([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Me=function(e,t){for(var n=new R(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Oe(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Ne=Me(ke,2),Pe=Ne.b,Fe=Ne.r;Pe[28]=258,Fe[258]=28;var Ie=Me(Ae,0),Le=Ie.b;Ie.r;for(var Re=new R(32768),z=0;z<32768;++z){var B=(z&43690)>>1|(z&21845)<<1;B=(B&52428)>>2|(B&13107)<<2,B=(B&61680)>>4|(B&3855)<<4,Re[z]=((B&65280)>>8|(B&255)<<8)>>1}for(var V=(function(e,t,n){for(var r=e.length,i=0,a=new R(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new R(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new R(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Re[d]>>c]=l}else for(s=new R(r),i=0;i<r;++i)e[i]&&(s[i]=Re[o[e[i]-1]++]>>15-e[i]);return s}),H=new L(288),z=0;z<144;++z)H[z]=8;for(var z=144;z<256;++z)H[z]=9;for(var z=256;z<280;++z)H[z]=7;for(var z=280;z<288;++z)H[z]=8;for(var ze=new L(32),z=0;z<32;++z)ze[z]=5;var Be=V(H,9,1),Ve=V(ze,5,1),He=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},U=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Ue=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},We=function(e){return(e+7)/8|0},Ge=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new L(e.subarray(t,n))},Ke=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],W=function(e,t,n){var r=Error(t||Ke[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,W),!n)throw r;return r},qe=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new L(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new L(i*3));var l=function(e){var t=n.length;if(e>t){var r=new L(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=U(e,d,1);var v=U(e,d+1,3);if(d+=3,!v){var y=We(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&W(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}else if(v==1)p=Be,m=Ve,h=9,g=5;else if(v==2){var S=U(e,d,31)+257,ee=U(e,d+10,15)+4,C=S+U(e,d+5,31)+1;d+=14;for(var w=new L(C),te=new L(19),T=0;T<ee;++T)te[je[T]]=U(e,d+T*3,7);d+=ee*3;for(var E=He(te),ne=(1<<E)-1,re=V(te,E,1),T=0;T<C;){var ie=re[U(e,d,ne)];d+=ie&15;var y=ie>>4;if(y<16)w[T++]=y;else{var D=0,O=0;for(y==16?(O=3+U(e,d,3),d+=2,D=w[T-1]):y==17?(O=3+U(e,d,7),d+=3):y==18&&(O=11+U(e,d,127),d+=7);O--;)w[T++]=D}}var ae=w.subarray(0,S),k=w.subarray(S);h=He(ae),g=He(k),p=V(ae,h,1),m=V(k,g,1)}else W(1);if(d>_){c&&W(0);break}}s&&l(f+131072);for(var oe=(1<<h)-1,A=(1<<g)-1,j=d;;j=d){var D=p[Ue(e,d)&oe],M=D>>4;if(d+=D&15,d>_){c&&W(0);break}if(D||W(2),M<256)n[f++]=M;else if(M==256){j=d,p=null;break}else{var se=M-254;if(M>264){var T=M-257,N=ke[T];se=U(e,d,(1<<N)-1)+Pe[T],d+=N}var P=m[Ue(e,d)&A],ce=P>>4;P||W(3),d+=P&15;var k=Le[ce];if(ce>3){var N=Ae[ce];k+=Ue(e,d)&(1<<N)-1,d+=N}if(d>_){c&&W(0);break}s&&l(f+131072);var le=f+se;if(f<k){var ue=a-k,de=Math.min(k,le);for(ue+f<0&&W(3);f<de;++f)n[f]=r[ue+f]}for(;f<le;++f)n[f]=n[f-k]}}t.l=p,t.p=j,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?Ge(n,0,f):n.subarray(0,f)},Je=new L(0),Ye=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&W(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&W(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2},Xe=function(){function e(e,t){typeof e==`function`&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new L(32768),this.p=new L(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||W(5),this.d&&W(4),!this.p.length)this.p=e;else if(e.length){var t=new L(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=qe(this.p,this.s,this.o);this.ondata(Ge(n,t,this.s.b),this.d),this.o=Ge(n,this.s.b-32768),this.s.b=this.o.length,this.p=Ge(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),Ze=function(){function e(e,t){Xe.call(this,e,t),this.v=e&&e.dictionary?2:1}return e.prototype.push=function(e,t){if(Xe.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(Ye(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&W(6,`invalid zlib data`),this.p=this.p.subarray(0,-4)),Xe.prototype.c.call(this,t)},e}(),Qe=typeof TextDecoder<`u`&&new TextDecoder;try{Qe.decode(Je,{stream:!0})}catch{}var $e=65536,et=`This file's compressed data is damaged.`;async function*tt(e){for(let t=0;t<e.length;t+=$e)yield e.subarray(t,t+$e)}async function*nt(e){if(typeof DecompressionStream!=`function`){let t=[],n=new Ze(e=>{t.push(e)});for await(let r of e)for(n.push(r,!1);t.length;)yield t.shift();for(n.push(new Uint8Array,!0);t.length;)yield t.shift();return}let t=new DecompressionStream(`deflate`),n=t.writable.getWriter();(async()=>{for await(let t of e)await n.write(t);await n.close()})().catch(e=>n.abort(e).catch(()=>{}));let r=t.readable.getReader();try{for(;;){let{done:e,value:t}=await r.read().catch(e=>{throw e instanceof TypeError?Error(et):e});if(e)return;yield t}}finally{r.cancel().catch(()=>{})}}async function G(e,t=-1,n=1/0){let r=[],i=Math.min(t,n),a=t>=0?new Uint8Array(i):null,o=0;for await(let s of nt(tt(e))){if(a){if(o+s.length>t&&n>t)throw Error(`Compressed data is longer than its header says.`);a.set(o+s.length>i?s.subarray(0,i-o):s,o)}else r.push(s);if(o+=s.length,o>=n)break}if(a)return o>=i?a:a.subarray(0,o);let s=r.length===1?r[0]:new Uint8Array(o);return r.length>1&&r.reduce((e,t)=>(s.set(t,e),e+t.length),0),o>n?s.subarray(0,n):s}var rt=new Uint8Array(Uint32Array.of(1).buffer)[0]===1;function it(e,t,n,r=t){let i=Math.floor(n/t),a=new Uint8Array(r<t?i*r:n),o=r%4==0&&rt?new Uint32Array(a.buffer,0,i*r>>2):null,s=r>>2;for(let t=0;t<i;t+=512){let n=Math.min(i,t+512);if(o)for(let a=0;a<r;a+=4){let r=a*i,c=r+i,l=c+i,u=l+i;for(let i=t,d=t*s+(a>>2);i<n;i++,d+=s)o[d]=e[r+i]|e[c+i]<<8|e[l+i]<<16|e[u+i]<<24}else for(let o=0;o<r;o++){let s=o*i;for(let i=t,c=t*r+o;i<n;i++,c+=r)a[c]=e[s+i]}}let c=i*t;return r===t&&a.set(e.subarray(c,n),c),a}function at(e,t,n){if(!(n<t)||e.length===0)return t;let r=Math.min(t,n+3&-4);return r===t?t:e.every(e=>e.zip?.type===1&&e.zip.param===t&&e.zip.orgLength%t===0)?r:t}async function ot(e,t,n=1/0,r=1/0){let i=await e.slice(t.offset,t.length),{type:a,param:o,orgLength:s}=t.zip;if(a===0)return G(i,s,r);let c=Math.min(n,o);return it(await G(i,s,c<o?s/o*c:1/0),o,s,c)}async function*st(e,t,n,r=1/0){let i=e=>!!e?.zip&&!(e.zip.type===0&&(e.length>16777216||e.zip.orgLength>268435456)),a=null;for(let o=0;o<t.length;o++){let s=t[o];if(n?.throwIfAborted(),!s.zip)for await(let t of e.windows(s.offset,s.length))yield t.bytes;else if(i(s)){let n=a??ot(e,s,r);a=i(t[o+1])?ot(e,t[o+1],r):null,a?.catch(()=>{}),yield await n}else{let t=s.zip.orgLength;for await(let n of nt((async function*(){for await(let t of e.windows(s.offset,s.length))yield t.bytes})()))if(yield n.length>t?n.subarray(0,t):n,(t-=n.length)<=0)break}}}async function*ct(e,t,n,r){if(r<=0||t<=0)return;let i=Math.min(n,r),a=null,o=0,s=0;for await(let n of e){let e=0;for(;e<n.length&&s<r;){if(o===0){let a=Math.min(i,r-s,Math.floor((n.length-e)/t));if(a>0){yield{buf:n.subarray(e,e+a*t),n:a},s+=a,e+=a*t;continue}}a??=new Uint8Array(t*i);let c=Math.min(a.length,(r-s)*t),l=Math.min(n.length-e,c-o);if(a.set(n.subarray(e,e+l),o),o+=l,e+=l,o===c){let e=o/t;yield{buf:a,n:e},s+=e,o=0}}if(s>=r)return}a&&o>=t&&(yield{buf:a,n:Math.floor(o/t)})}async function lt(e,t,n,r){let i=n*r,a=0;for(let n of t){let t=n.zip?n.zip.orgLength:n.length;if(i<a)return null;if(i+r<=a+t)return n.zip?null:e.read(n.offset+i-a,r);a+=t}return null}var ut=(e,t)=>(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0,dt=class{#e;#t;#n;#r;#i=new Uint8Array;#a=0;#o;#s=0;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n,this.#r=st(e,t,n),this.#o=t.reduce((e,t)=>e+(t.zip?t.zip.orgLength:t.length),0)}peek(e){let t=e-this.#a;if(t<0||t+4>this.#i.length)return null;let n=ut(this.#i,t);return t+4+n>this.#i.length?null:this.#i.subarray(t+4,t+4+n)}async get(e){for(;;){let t=this.peek(e);if(t)return t;let n=e-this.#a;if(e+4>this.#o||n>=0&&n+4<=this.#i.length&&e+4+ut(this.#i,n)>this.#o)throw Error(`This MF4 is damaged (string data ends early).`);e<this.#a&&(this.#r=st(this.#e,this.#t,this.#n),this.#i=new Uint8Array,this.#a=0);let r=await this.#r.next();if(r.done)throw Error(`This MF4 is damaged (string data ends early).`);if((this.#s+=r.value.length)>4*this.#o+16777216)throw Error(`This MF4 is damaged (its string offsets jump back and forth).`);let i=Math.max(0,Math.min(e-this.#a,this.#i.length)),a=this.#i.subarray(i),o=new Uint8Array(a.length+r.value.length);o.set(a),o.set(r.value,a.length),this.#a+=i,this.#i=o}}},ft=e=>Math.max(1,Math.min(65536,Math.floor((8<<20)/Math.max(1,e)))),pt=64<<20,mt=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t){this.#e=e,this.#t=t}want(e){this.#r.has(e)||this.#r.set(e,new Map)}wanted(e){return this.#r.has(e)}put(e,t,n){this.#r.get(e).set(t,n)}async bytes(e,t){let n=Array(t.length);if(e.sdRecordId!==null){let r=this.#r.get(e.sdRecordId);for(let e=0;e<t.length;e++)n[e]=r?.get(t[e])??null,r?.delete(t[e]);return n}if(!e.sd)return n.fill(null);let r=this.#n.get(e);r||this.#n.set(e,r=new dt(this.#e,e.sd,this.#t));for(let e=0;e<t.length;e++)n[e]=r.peek(t[e])??await r.get(t[e]);return n}async strings(e,t){let n=ve(e.encoding);return(await this.bytes(e,t)).map(e=>e?ye(n.decode(e)):null)}};function ht(e,t,n,r,i=I(e),a=new Float64Array(n)){let o=e.master;if(!o)return null;if(o.kind===`vmaster`)for(let e=0;e<n;e++)a[e]=r+e;else F(o,t,n,i,e.recordIdSize,a);return re(o.conv,a),a}function gt(e,t,n){return n===1?e[t]:n===2?e[t]|e[t+1]<<8:n===4?(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0:((e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0)+4294967296*((e[t+4]|e[t+5]<<8|e[t+6]<<16|e[t+7]<<24)>>>0)}function _t(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async function*vt(e,t,n,r,i,a=1/0){let o=t.groups[n[0]];if(o.sorted){let t=at(o.stream,I(o),a),r=0;for await(let{buf:a,n:s}of ct(st(e,o.stream,i,t),t,ft(t),o.cycles))yield{g:n[0],buf:a,n:s,start:r,size:t},r+=s;return}let s=t.groups.map((e,t)=>({g:e,k:t})).filter(({g:e})=>e.dg===o.dg),c=o.recordIdSize,l=new Map;for(let e of n){let n=t.groups[e],r=I(n);l.set(n.recordId,{k:e,size:r,buf:new Uint8Array(r*Math.min(ft(r),Math.max(1,n.cycles))),fill:0,start:0})}let u=new Map(s.map(({g:e})=>[e.recordId,e.vlsdCg?-1:I(e)])),d=new Map,f=new Uint8Array;for await(let t of st(e,o.stream,i)){let e=f.length?_t(f,t):t,n=0;for(;!(n+c>e.length);){let t=gt(e,n,c),i=u.get(t);if(i===void 0)throw Error(`This MF4 is damaged (unknown record id ${t}).`);if(i<0){if(n+c+4>e.length)break;let i=(e[n+c]|e[n+c+1]<<8|e[n+c+2]<<16|e[n+c+3]<<24)>>>0;if(i>pt)throw Error(`This MF4 is damaged (a string record of ${i} bytes).`);let a=n+c+4+i;if(a>e.length)break;let o=d.get(t)??0;r.wanted(t)&&r.put(t,o,e.slice(n+c+4,a)),d.set(t,o+4+i),n=a;continue}if(n+i>e.length)break;let a=l.get(t);if(a&&(a.buf.set(e.subarray(n,n+i),a.fill),a.fill+=i,a.fill===a.buf.length)){let e=a.fill/a.size;yield{g:a.k,buf:a.buf,n:e,start:a.start,size:a.size},a.start+=e,a.fill=0}n+=i}f=e.slice(n)}for(let e of l.values())e.fill&&(yield{g:e.k,buf:e.buf,n:e.fill/e.size,start:e.start,size:e.size})}var yt=(e,t)=>t?e+2147483648:e,bt=/^BO_\s+(\d+)\s+(\w+)\s*:\s*(\d+)/,xt=/^SG_\s+(\w+)\s*(?:(M|m\d+M?)\s*)?:\s*(\d+)\|(\d+)@([01])([+-])\s*\(([^,)]*),([^)]*)\)\s*\[[^\]]*\]\s*"([^"]*)"/,St=/^VAL_\s+(\d+)\s+(\w+)\s+(.*);/,Ct=/^SIG_VALTYPE_\s+(\d+)\s+(\w+)\s*:\s*([12])\s*;/,wt=/^-?\d+(?:\.\d+)?$/;function Tt(e){let t=e.split(`"`),n=new Map;for(let e=0;e+1<t.length;e+=2){let r=t[e].trim();wt.test(r)&&n.set(Number(r),t[e+1])}return n}var Et=(e,t)=>e<=511&&t>=1&&t<=64;function Dt(e){let t=new Map,n=new Map,r=new Map,i=(e,t)=>{let i=n.get(Number(e));return i?r.get(i)?.get(t):void 0},a=null;for(let o of e.split(/\r?\n/)){let e=o.trim(),s;if(s=bt.exec(e)){let e=Number(s[1]),r=e>=2147483648,i=r?e-2147483648:e;a={id:i,extended:r,name:s[2],size:Number(s[3]),signals:[]},t.set(yt(i,r),a),n.set(e,a)}else if((s=xt.exec(e))&&a){let e=s[2],t=Number(s[3]),n=Number(s[4]);if(!Et(t,n)||!s[7].trim()||!s[8].trim())continue;let i={name:s[1],start:t,length:n,littleEndian:s[5]===`1`,signed:s[6]===`-`,factor:Number(s[7]),offset:Number(s[8]),unit:s[9],mux:e?e===`M`?`switch`:parseInt(e.slice(1),10):null,float:0,values:null};a.signals.push(i);let o=r.get(a);o||r.set(a,o=new Map),o.has(i.name)||o.set(i.name,i)}else if(s=St.exec(e)){let e=i(s[1],s[2]);e&&(e.values=Tt(s[3]))}else if(s=Ct.exec(e)){let e=i(s[1],s[2]);e&&(e.float=s[3]===`1`?32:64)}else (e.startsWith(`BO_`)||e===``)&&e===``&&(a=null)}return t}function Ot(e){if(e.float){let t=e.float/8,n=e.start>>3,r=e.littleEndian,i=new DataView(new ArrayBuffer(8));return(e,a)=>{for(let r=0;r<t;r++)i.setUint8(r,e[a+n+r]??0);return t===4?i.getFloat32(0,r):i.getFloat64(0,r)}}let t=e.length,n=2**t,r=n/2,i=e.signed;if(e.littleEndian){let a=e.start>>3,o=e.start&7;if(o+t<=32){let e=t===32?-1:(1<<t)-1;return(t,s)=>{let c=s+a,l=((t[c]|t[c+1]<<8|t[c+2]<<16|t[c+3]<<24)>>>o&e)>>>0;return i&&l>=r?l-n:l}}let s=o+t+7>>3,c=2**(t-(32-o)),l=2**(32-o);return(e,t)=>{let u=t+a,d=(e[u]|e[u+1]<<8|e[u+2]<<16|e[u+3]<<24)>>>o,f=0;for(let t=s-1;t>=4;t--)f=f*256+(e[u+t]??0);let p=d+f%c*l;return i&&p>=r?p-n:p}}let a=e.start>>3,o=e.start&7;if(7-o+t<=32){let e=32-(7-o)-t,s=t===32?-1:(1<<t)-1;return(t,o)=>{let c=o+a,l=((t[c]<<24|t[c+1]<<16|t[c+2]<<8|t[c+3])>>>e&s)>>>0;return i&&l>=r?l-n:l}}let s=(1<<o+1)-1,c=t-(o+1)>>3,l=t-(o+1)&7,u=2**l;return(e,t)=>{let o=(e[t+a]??0)&s,d=t+a+1;for(let t=0;t<c;t++)o=o*256+(e[d++]??0);return l>0&&(o=o*u+((e[d]??0)>>8-l)),i&&o>=r?o-n:o}}function kt(e){let t=e.length,n=2**t,r=n/2,i=e.signed,a=t===32?-1:(1<<t)-1;if(!e.float&&e.littleEndian&&(e.start&7)+t<=32){let t=e.start>>3,o=e.start&7;return(e,s,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=s[c[p]]+t,m=((e[l]|e[l+1]<<8|e[l+2]<<16|e[l+3]<<24)>>>o&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}if(!e.float&&!e.littleEndian&&7-(e.start&7)+t<=32){let o=e.start>>3,s=32-(7-(e.start&7))-t;return(e,t,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=t[c[p]]+o,m=((e[l]<<24|e[l+1]<<16|e[l+2]<<8|e[l+3])>>>s&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}let o=Ot(e);return(e,t,n,r,i,a,s)=>{for(let c=0;c<r;c++)i[c]=o(e,t[n[c]])*a+s}}function At(e){if(!e.busEvent||e.busType!==2)return null;let t=t=>e.channels.find(e=>e.name.endsWith(t))??null,n=t(`DataFrame.ID`),r=t(`DataFrame.DataBytes`);return!n||!r?null:{id:n,ide:t(`DataFrame.IDE`),data:r}}var jt=()=>({n:0,time:new Float64Array,key:new Float64Array,id:new Float64Array,ide:new Float64Array,bytes:null,buf:new Uint8Array,dataAt:new Int32Array});async function Mt(e,t,n,r,i,a,o,s){s.key.length<r&&Object.assign(s,{time:new Float64Array(r),key:new Float64Array(r),id:new Float64Array(r),ide:new Float64Array(r),dataAt:new Int32Array(r)});let c=e.recordIdSize,{id:l,ide:u,key:d,dataAt:f}=s;F(t.id,n,r,a,c,l),t.ide&&F(t.ide,n,r,a,c,u);for(let e=0;e<r;e++){let n=l[e],r=n&536870911;d[e]=yt(r,t.ide?u[e]!==0:n>=2147483648||r>2047)}if(s.bytes=null,t.data.kind===`vlsd`){let e=new Float64Array(r);F({...t.data,type:`uint`},n,r,a,c,e),s.bytes=await o.bytes(t.data,e)}else for(let e=0,n=c+t.data.byteOffset;e<r;e++,n+=a)f[e]=n;if(!ht(e,n,r,i,a,s.time.subarray(0,r)))for(let e=0;e<r;e++)s.time[e]=i+e;return s.n=r,s.buf=n,s}var Nt=new Uint8Array;function Pt(e){return e.float?(e.start>>3)+e.float/8:e.littleEndian?(e.start>>3)+((e.start&7)+e.length+7>>3):(e.start>>3)+1+(Math.max(0,e.length-((e.start&7)+1))+7>>3)}function Ft(e,t,n){let r=0;for(let e of n.values())for(let t of e.signals)r=Math.max(r,Pt(t));let i=t.data.kind===`vlsd`?t.data:{...t.data,bitCount:Math.min(t.data.bitCount,r*8)};return De(e,t.ide?[t.id,t.ide,i]:[t.id,i])}function It(e,t){let n=t.map(t=>e.signals[e.channels[t].s]);return{route:e,col:n.map(kt),read:n.map(Ot),factor:n.map(e=>e.factor),offset:n.map(e=>e.offset),table:t.map((t,r)=>e.channels[t].text?n[r].values:null),idx:new Int32Array,cnt:0,n:0,t0:NaN,t1:NaN}}function Lt(e,t,n,r,i,a=1,o=0){let s=new Float64Array(i);if(n.bytes)for(let e=0;e<i;e++)s[e]=t(n.bytes[r[e]]??Nt,0)*a+o;else e(n.buf,n.dataAt,r,i,s,a,o);return s}function Rt(e,t){let{idx:n,cnt:r}=e,i=new Float64Array(r);for(let e=0;e<r;e++)i[e]=t.time[n[e]];return e.n===0&&(e.t0=i[0]),e.t1=i[r-1],e.n+=r,e.cnt=0,{time:i,cols:e.col.map((i,a)=>{let o=e.table[a];return o?Array.from(Lt(i,e.read[a],t,n,r),e=>o.get(e)??null):Lt(i,e.read[a],t,n,r,e.factor[a],e.offset[a])})}}var zt=e=>({key:e,skip:!0,frames:0,all:null,sw:null,byMux:new Map,idx:new Int32Array,cnt:0});function Bt(e,t){let n=e.signals.find(e=>e.mux===`switch`);return{key:yt(e.id,e.extended),skip:!1,frames:0,all:t,sw:n?{col:kt(n),read:Ot(n)}:null,byMux:new Map,idx:new Int32Array,cnt:0}}var Vt=class{#e=Array(2048);#t=new Map;#n;constructor(e){this.#n=e}get(e){let t=e<2048?this.#e[e]:this.#t.get(e);return t||(t=this.#n(e),e<2048?this.#e[e]=t:this.#t.set(e,t)),t}};function Ht(e,t,n){let r=[];for(let n=0;n<e.n;n++){let i=t.get(e.key[n]);if(i.skip){i.frames++;continue}i.cnt===0&&(r.push(i),i.idx.length<e.n&&(i.idx=new Int32Array(e.n))),i.idx[i.cnt++]=n}let i=[];for(let t of r){if(t.all&&(t.all.idx=t.idx,t.all.cnt=t.cnt,i.push(t.all)),t.sw){let r=Lt(t.sw.col,t.sw.read,e,t.idx,t.cnt);for(let e=0;e<t.cnt;e++){let a=t.byMux.get(r[e]);a===void 0&&((a=n(t,r[e]))||t.byMux.size<4096)&&t.byMux.set(r[e],a),a&&(a.cnt===0&&(i.push(a),a.idx.length<t.cnt&&(a.idx=new Int32Array(t.cnt))),a.idx[a.cnt++]=t.idx[e])}}t.cnt=0}return i}var Ut=48e6;async function Wt(e,t,n,i){let a=new Map;if(t.groups.forEach((e,t)=>{let n=At(e);n&&e.cycles>0&&a.set(t,n)}),a.size===0)return null;if(n.length===0)return{dbc:new Map,layouts:a,routes:[],notes:[],cache:new Map};let o=Dt(r(new Uint8Array(await n[0].arrayBuffer()))),s=[],c=new Map,l=new Map,u=0,d=new mt(e,i);for(let[n,r]of a){let a=t.groups[n],f=(e,t)=>{let n=e.signals.filter(e=>t===null?typeof e.mux!=`number`:e.mux===t),r=[];return n.forEach((e,t)=>{r.push({s:t,text:!1}),e.values&&r.push({s:t,text:!0})}),It({key:yt(e.id,e.extended),mux:t,signals:n,channels:r},r.map((e,t)=>t))},p=new Vt(e=>{let t=o.get(e);if(!t){let t=zt(e);return c.set(e,t),t}let r=Bt(t,f(t,null));return s.push({model:n,m:r}),r});r.data.sdRecordId!==null&&d.want(r.data.sdRecordId);let m=jt();for await(let s of vt(e,t,[n],d,i,Ft(a,r,o))){let e=await Mt(a,r,s.buf,s.n,s.start,s.size,d,m),t=(e,t)=>{let n=o.get(e.key);return n.signals.some(e=>e.mux===t)?f(n,t):null};for(let n of Ht(e,p,t)){let t=Rt(n,e);if(u<0)continue;if((u+=t.time.length*(1+t.cols.length))>Ut){u=-1,l.clear();continue}let r=l.get(n);r||l.set(n,r=[]),r.push(t)}}}let f=[],p=new Map;for(let{model:e,m:t}of s)for(let n of[t.all,...t.byMux.values()]){if(!n)continue;let{route:t,n:r,t0:i,t1:a}=n;if(t.signals.length===0)continue;let s=o.get(t.key);u>=0&&p.set(t,l.get(n)??[]),f.push({model:e,route:t,group:{name:t.mux===null?s.name:`${s.name} [m=${t.mux}]`,channels:t.channels.map(e=>({name:e.text?`${t.signals[e.s].name} (text)`:t.signals[e.s].name,unit:e.text?``:t.signals[e.s].unit,text:e.text})),samples:r,time:{kind:`timestamps`},rateHz:r>1&&a>i?Math.round((r-1)/(a-i)*1e6)/1e6:null}})}let m=[];if(c.size){let e=[...c.values()].reduce((e,t)=>e+t.frames,0),t=[...c.keys()].map(e=>`0x${(e%2147483648).toString(16).toUpperCase()}`).join(`, `);m.push(`${e} frame${e===1?``:`s`} with ${c.size} id${c.size===1?``:`s`} not in the DBC ${e===1?`was`:`were`} skipped (${t}).`)}return{dbc:o,layouts:a,routes:f,notes:m,cache:p}}async function*Gt(e,t,n,r,i,a){let o=[];for(let e of i){let t=r.cache.get(e.route);if(!t){o.push(e);continue}r.cache.delete(e.route);let n=0;for(let r of t)yield{group:e.group,start:n,length:r.time.length,time:r.time,columns:e.sel.map(e=>r.cols[e])},n+=r.time.length}if(!o.length)return;let s=r.layouts.get(n),c=t.groups[n],l=new Map,u=new Map;for(let e of o){let t=It(e.route,e.sel);l.set(t,e.group);let n=u.get(e.route.key);n||u.set(e.route.key,n={all:null,byMux:new Map}),e.route.mux===null?n.all=t:n.byMux.set(e.route.mux,t)}let d=new Vt(e=>{let t=u.get(e);if(!t)return zt(e);let n=Bt(r.dbc.get(e),t.all);return t.byMux.size||(n.sw=null),n}),f=new mt(e,a);s.data.sdRecordId!==null&&f.want(s.data.sdRecordId);let p=jt();for await(let i of vt(e,t,[n],f,a,Ft(c,s,r.dbc))){let e=await Mt(c,s,i.buf,i.n,i.start,i.size,f,p);for(let t of Ht(e,d,(e,t)=>u.get(e.key).byMux.get(t)??null)){let n=t.n,r=Rt(t,e);yield{group:l.get(t),start:n,length:r.time.length,time:r.time,columns:r.cols}}}}var Kt=e=>Math.round(e*1e6)/1e6,qt=e=>e.kind===`value`?e.type!==`bytes`:e.kind===`vlsd`&&e.type===`string`,Jt=e=>({name:e.name,unit:e.unit,text:e.type===`string`||e.kind===`vlsd`||e.conv.k===`text`});async function Yt(e,t){let n=t.master;if(!n||t.cycles<2)return null;if(n.kind===`vmaster`)return n.conv.k===`lin`&&n.conv.a>0?Kt(1/n.conv.a):null;if(!t.sorted)return null;let r=I(t),i=t.cycles,a,o;if(t.stream[0]?.zip){let n=at(t.stream.slice(0,1),r,De(t,[])),s=await ot(e,t.stream[0],n,4096*r);if(i=Math.min(t.cycles,Math.floor(s.length/n)),i<2)return null;a=s.subarray(0,n),o=s.subarray((i-1)*n,i*n)}else a=await lt(e,t.stream,0,r),o=await lt(e,t.stream,t.cycles-1,r);if(!a||!o)return null;let s=new Float64Array(2);return F(n,a,1,r,t.recordIdSize,s,0),F(n,o,1,r,t.recordIdSize,s,1),re(n.conv,s),s[1]>s[0]?Kt((i-1)/(s[1]-s[0])):null}async function Xt(e,t,n,r,i,a,o){let s;if(e.kind===`vlsd`){let a=new Float64Array(n);F({...e,type:`uint`},t,n,r,i,a),s=await o.strings(e,a)}else if(e.type===`string`)s=be(e,t,n,r,i);else{let a=new Float64Array(n);F(e,t,n,r,i,a),e.conv.k===`text`?s=O(e.conv,a):(re(e.conv,a),s=a)}return xe(e,t,n,r,a,s),s}async function Zt(e,t,n,r,i,a,o,s){let c=e.recordIdSize,l=[];for(let i of t)l.push(await Xt(e.channels[i],n,r,a,c,c+e.dataBytes,s));return{group:o,time:ht(e,n,r,i,a),start:i,length:r,columns:l}}async function*Qt(e,t){let n=e.plan.state,r=t.filter(e=>n.groups[e].route),i=t.filter(e=>!n.groups[e].route);if(r.length){let t=r.map(t=>({group:t,route:n.groups[t].route,sel:C(e,t)}));yield*Gt(e.io,n.model,n.groups[r[0]].model,n.bus,t,e.signal)}if(!i.length)return;let a=new mt(e.io,e.signal),o=new Map;for(let t of i){let r=n.groups[t],i=C(e,t).map(e=>r.channels[e]);for(let e of i){let t=n.model.groups[r.model].channels[e].sdRecordId;t!==null&&a.want(t)}o.set(r.model,{pg:t,cols:i})}let[s,{cols:c}]=o.entries().next().value,l=n.model.groups[s],u=o.size===1?De(l,c.map(e=>l.channels[e])):1/0;for await(let t of vt(e.io,n.model,[...o.keys()],a,e.signal,u)){let{pg:e,cols:r}=o.get(t.g);yield await Zt(n.model.groups[t.g],r,t.buf,t.n,t.start,t.size,e,a)}}function $t(e){let t=e.plan.state,n=new Map;for(let r of e.selection){let e=t.model.groups[t.groups[r.group].model].dg;n.set(e,[...n.get(e)??[],r.group])}return[...n].sort((e,t)=>e[0]-t[0]).map(([,e])=>e)}var en={...ee,async plan(t,n){let r=await n.read(0,64);if(e(r,`UnFinMF`))throw Error(`This MF4 was not finalized by its logger (it starts with UnFinMF). Finalize it with the logger software or asammdf, then open it again.`);let i=o(r.subarray(8,16)).replace(/\0/g,``).trim(),a=Number(i.replace(`.`,``).slice(0,3))>=400?await he(n,i):await k(n,r,i);Ee(a,n.size);let s=await Wt(n,a,t.companions.filter(e=>e.name.toLowerCase().endsWith(`.dbc`))),c=new Set(s?.layouts.keys()??[]),l=[],u=[],d=[...a.notes],f=0;for(let e=0;e<a.groups.length;e++){let t=a.groups[e];if(t.vlsdCg||t.cycles===0||c.has(e))continue;let r=[];if(t.channels.forEach((e,t)=>{qt(e)?r.push(t):f++}),r.length!==0){for(let e of r){let n=t.channels[e].conv;n.k===`unsupported`&&d.push(`${t.channels[e].name}: ${n.what} is not supported; raw values are shown.`)}u.push({model:e,channels:r}),l.push({name:t.name,channels:r.map(e=>Jt(t.channels[e])),samples:t.cycles,time:t.master?{kind:`timestamps`}:{kind:`index`},rateHz:await Yt(n,t)})}}if(f&&d.push(`${f} byte-array channel${f===1?` was`:`s were`} skipped.`),s){if(s.routes.length===0&&s.dbc.size===0){if(l.length===0)throw Error(`This MF4 has raw CAN frames. Drop its .dbc file together with it to decode signals.`);d.push(`This MF4 also has raw CAN frames. Drop its .dbc file together with it to decode signals.`)}for(let e of s.routes)u.push({model:e.model,route:e.route}),l.push(e.group);d.push(...s.notes)}if(l.length===0)throw Error(`This MDF file has no channels with samples.`);let p={model:a,groups:u,bus:s};return{format:a.version,startTime:a.startTime,groups:l,meta:a.meta,events:[],notes:d,interleaved:!!s?.routes.length||a.groups.some(e=>!e.sorted&&!e.vlsdCg),state:p}},async*stream(e){for(let t of $t(e))yield*Qt(e,t)},streamGroup(e,t){return Qt(e,[t])}};function tn(e){let t=[];for(let n of r(e).split(`\0`)){if(!n)continue;let e=n.split(``),r=parseFloat(e[0].split(``)[0]);Number.isFinite(r)&&t.push({onset:r,texts:e.slice(1).filter(e=>e.length>0)})}return t}function nn(e,t){let n=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(e),r=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(t);if(!n||!r)return null;let i=Number(n[3]);return`${i>=85?1900+i:2e3+i}-${n[2]}-${n[1]}T${r[1]}:${r[2]}:${r[3]}`}var rn=e=>`${+e.toFixed(6)} Hz`;function an(e,t,n,r,i,a,o,s){let{bit:c,off:l}=e;if(a===2)for(let e=0;e<i;e++)o[s+e]=c*(l+t.getInt16(r+2*e,!0));else for(let e=0,t=r;e<i;e++,t+=3)o[s+e]=c*(l+((n[t]|n[t+1]<<8|n[t+2]<<16)<<8>>8))}var on={...b,async plan(e,t){let n=await t.read(0,256),r=(e,t)=>o(n.subarray(e,e+t)).trim(),i=n[0]===255,a=parseInt(r(252,4),10),s=parseInt(r(184,8),10),c=r(192,44),l=/^(EDF|BDF)\+/.test(c),u=/^(EDF|BDF)\+D/.test(c),d=parseFloat(r(244,8));if(!(a>0)||s!==256*(a+1)||!(d>0))throw Error(`This EDF/BDF header is damaged.`);let f=await t.read(256,a*256),p=(e,t,n)=>o(f.subarray(e*a+t*n,e*a+t*(n+1))).trim(),m=i?3:2,h=[],g=0;for(let e=0;e<a;e++){let t=parseFloat(p(104,8,e)),n=parseFloat(p(112,8,e)),r=parseFloat(p(120,8,e)),i=parseFloat(p(128,8,e)),a=Number(p(216,8,e));if(!(Number.isInteger(a)&&a>=0))throw Error(`This EDF/BDF header is damaged (samples per record).`);let o=(n-t)/(i-r);h.push({label:p(0,16,e),unit:p(96,8,e),spr:a,offset:g,bit:o,off:n/o-i}),g+=a*m}let _=g;if(!(_>0&&s+_<=t.size))throw Error(`This EDF/BDF file is damaged (its data records do not fit in it).`);let v=Math.floor((t.size-s)/_),y=parseInt(r(236,8),10),b=[];y>=0?y>v&&(b.push(`The file is shorter than its header says: ${v} of ${y} data records were read.`),y=v):y=v;let x=l?h.flatMap((e,t)=>/^(EDF|BDF) Annotations$/.test(e.label)?[t]:[]):[],S=new Map;h.forEach((e,t)=>{!x.includes(t)&&e.spr>0&&S.set(e.spr,[...S.get(e.spr)??[],t])});let ee=[...S.values()],C=ee.map(e=>{let t=h[e[0]].spr/d;return{name:rn(t),channels:e.map(e=>({name:h[e].label,unit:h[e].unit})),samples:y*h[e[0]].spr,rateHz:t,time:u?{kind:`timestamps`}:{kind:`rate`,rate:t,start:0}}}),w={headerBytes:s,records:y,duration:d,recordBytes:_,bps:m,signals:h,groups:ee,annotations:x,discontinuous:u};return{format:`${i?`BDF`:`EDF`}${l?u?`+D`:`+`:``}`,startTime:nn(r(168,8),r(176,8)),groups:C,meta:{patient:r(8,80),recording:r(88,80)},events:[],notes:u?[`Discontinuous recording: each gap shows as a break in the traces.`,...b]:b,state:w}},async*stream(e){let n=e.plan.state,r=Math.max(1,Math.floor(m/n.recordBytes)),i=e.selection.map(e=>({g:e.group,chans:e.channels.map(t=>n.signals[n.groups[e.group][t]]),spr:n.signals[n.groups[e.group][0]].spr})),a=i.map(()=>0),o=0,s=NaN;for await(let c of e.io.windows(n.headerBytes,n.records*n.recordBytes,r*n.recordBytes)){e.signal?.throwIfAborted();let r=Math.floor(c.bytes.length/n.recordBytes);if(r===0)break;let l=t(c.bytes),u=new Float64Array(r),d=[];for(let e=0;e<r;e++)u[e]=(o+e)*n.duration,n.annotations.forEach((t,r)=>{let i=n.signals[t],a=e*n.recordBytes+i.offset,o=tn(c.bytes.subarray(a,a+i.spr*n.bps));r===0&&o.length&&(u[e]=o[0].onset);for(let e of o)for(let t of e.texts)d.push({time:e.onset,text:t})});let f=new Uint8Array(r),p=0;if(n.discontinuous)for(let e=0;e<r;e++){let t=e?u[e-1]+n.duration:s;t===t&&u[e]>t+1e-9&&(f[e]=1,p++)}for(let e=0;e<i.length;e++){let t=i[e],o=t.spr/n.duration,m=r*t.spr+p,h=n.discontinuous?new Float64Array(m):null,g=t.chans.map(()=>new Float64Array(m)),_=0;for(let e=0;e<r;e++){if(f[e]){h[_]=e?u[e-1]+n.duration:s;for(let e of g)e[_]=NaN;_++}if(h)for(let n=0;n<t.spr;n++)h[_+n]=u[e]+n/o;let r=e*n.recordBytes;t.chans.forEach((e,i)=>an(e,l,c.bytes,r+e.offset,t.spr,n.bps,g[i],_)),_+=t.spr}let v={group:t.g,time:h,start:a[e],length:m,columns:g};e===0&&d.length&&(v.events=d),a[e]+=m,yield v}s=u[r-1]+n.duration,o+=r}}},K={float32:4,double64:8,int8:1,int16:2,int32:4,int64:8};function q(e,t,n=0){let r=e.indexOf(`<${t}>`,n);if(r<0)return``;let i=e.indexOf(`</${t}>`,r);return i<0?``:e.slice(r+t.length+2,i).trim()}function sn(e,t){let n=[];for(let r=e.indexOf(`<${t}>`);r>=0;){let i=e.indexOf(`</${t}>`,r);if(i<0)break;n.push(e.slice(r,i+t.length+3)),r=e.indexOf(`<${t}>`,i)}return n}var cn=1e5,ln=e=>e.fmt===`string`||K[e.fmt]!==void 0;function J(e,t,n){let r=e[n];if((r===1||r===4||r===8)&&n+1+r<=e.length)return r===1?[e[n+1],2]:r===4?[t.getUint32(n+1,!0),5]:[x(t,n+1),9];throw Error(`This XDF file is damaged (bad length field).`)}function un(e,t,n,r){if(n>=e.length)return-1;if(e[n++]===8&&(n+=8),r.fmt!==`string`)return n+K[r.fmt]*r.nch<=e.length?n+K[r.fmt]*r.nch:-1;for(let i=0;i<r.nch;i++){if(n>=e.length)return-1;let[r,i]=J(e,t,n);n+=i+r}return n<=e.length?n:-1}async function*dn(e,n){let r=new Uint8Array;for await(let i of e.windows(4,e.size-4)){n?.throwIfAborted();let a=i.bytes,o=i.offset-r.length;if(r.length){let e=new Uint8Array(r.length+a.length);e.set(r),e.set(a,r.length),a=e}let s=t(a),c=0;for(;!(c+1>a.length);){let t=a[c];if(c+1+t>a.length)break;let[n,r]=J(a,s,c),i=c+r+n;if(o+i>e.size)return;if(i>a.length)break;yield{tag:a[c+r]|a[c+r+1]<<8,body:a.subarray(c+r+2,i)},c=i}r=a.slice(c)}}function fn(e,t,n){let r=t-e.i0,i=n-e.t0;e.n++,e.si+=r,e.st+=i,e.sii+=r*r,e.sit+=r*i}function pn(e){let t=e.n*e.sii-e.si*e.si;e.b=t>0?(e.n*e.sit-e.si*e.st)/t:0,e.a=(e.st-e.b*e.si)/Math.max(1,e.n)}function mn(e){if(e.length===0)return[0,0];if(e.length===1)return[e[0][1],0];let t={i0:e[0][0],t0:0,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0};for(let[n,r]of e)fn(t,n,r);return pn(t),[t.a-t.b*t.i0,t.b]}function hn(e,t,n){let r=t.t0+t.a+t.b*(n-t.i0);return r+e.c0+e.c1*r}var gn={...i,async plan(e,n){let i=new Map,a=``;for await(let e of dn(n)){let n=t(e.body);if(e.tag===1)a=r(e.body);else if(e.tag===2){let t=n.getUint32(0,!0),a=r(e.body.subarray(4)),o=parseInt(q(a,`channel_count`),10)||1;if(!(o>=1&&o<=cn))throw Error(`This XDF file is damaged (a stream with ${o} channels).`);let s=sn(a,`channel`);i.set(t,{id:t,name:q(a,`name`)||`Stream ${t}`,nch:o,srate:parseFloat(q(a,`nominal_srate`))||0,fmt:q(a,`channel_format`)||`float32`,labels:Array.from({length:o},(e,t)=>q(s[t]??``,`label`)||`Ch${t+1}`),units:Array.from({length:o},(e,t)=>q(s[t]??``,`unit`)),count:0,segs:[],clock:[],c0:0,c1:0,lastTs:NaN})}else if(e.tag===3){let t=i.get(n.getUint32(0,!0));if(!t||!ln(t))continue;let[r,a]=J(e.body,n,4),o=4+a,s=K[t.fmt],c=t.srate>0?Math.max(1,500/t.srate):1/0;for(let i=0;i<r&&!(un(e.body,n,o,t)<0);i++){let r;if(e.body[o++]===8?(r=n.getFloat64(o,!0),o+=8):r=t.lastTs+(t.srate>0?1/t.srate:0),t.fmt===`string`)for(let r=0;r<t.nch;r++){let[t,r]=J(e.body,n,o);o+=r+t}else o+=s*t.nch;if(t.srate>0){let e=t.segs[t.segs.length-1];(!e||r-t.lastTs>c)&&t.segs.push(e={i0:t.count,t0:r,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0}),fn(e,t.count,r)}else t.count===0&&t.segs.push({i0:0,t0:r,n:1,si:0,st:0,sii:0,sit:0,a:0,b:0});t.lastTs=r,t.count++}}else if(e.tag===4){let e=i.get(n.getUint32(0,!0));e&&e.clock.push([n.getFloat64(4,!0),n.getFloat64(12,!0)])}}let o=[],s=[...i.values()].sort((e,t)=>e.id-t.id).filter(e=>(ln(e)||o.push(`${e.name}: channel format ${e.fmt} is not supported; skipped.`),ln(e))),c=1/0;for(let e of s){[e.c0,e.c1]=mn(e.clock);for(let t of e.segs)pn(t);if(e.count===0)continue;let t=e.srate>0?hn(e,e.segs[0],0):e.segs[0].t0+e.c0+e.c1*e.segs[0].t0;c=Math.min(c,t)}let l=v(s.map(e=>e.name),[]),u=s.map((e,t)=>({name:l[t],channels:e.labels.map((t,n)=>({name:t,unit:e.units[n],...e.fmt===`string`?{text:!0,sparse:!0}:{}})),samples:e.count,time:{kind:`timestamps`},rateHz:e.srate>0?e.srate:null,irregular:e.srate===0})),d=q(a,`version`);return{format:`XDF ${d||`1.0`}`,startTime:null,groups:u,meta:{header:d},events:[],notes:o,state:{streams:s,origin:Number.isFinite(c)?c:0}}},async*stream(e){let n=e.plan.state,i=8192,a=new Map,o=e=>e.sel.map(()=>e.s.fmt===`string`?Array(i):new Float64Array(i));for(let t of e.selection){let r=n.streams[t.group],s={g:t.group,s:r,sel:C(e,t.group),time:new Float64Array(i),cols:[],n:0,start:0,seg:0,i:0,raw:NaN};s.cols=o(s),a.set(r.id,s)}let s=e=>{let t={group:e.g,time:e.time.slice(0,e.n),start:e.start,length:e.n,columns:e.cols.map(t=>t.slice(0,e.n))};return e.start+=e.n,e.n=0,e.time=new Float64Array(i),e.cols=o(e),t};for await(let o of dn(e.io,e.signal)){if(o.tag!==3)continue;let e=t(o.body),c=a.get(e.getUint32(0,!0));if(!c)continue;let l=c.s,[u,d]=J(o.body,e,4),f=4+d,p=K[l.fmt],m=[];for(let t=0;t<u&&!(un(o.body,e,f,l)<0);t++){let t;o.body[f++]===8?(t=e.getFloat64(f,!0),f+=8):t=c.raw+(l.srate>0?1/l.srate:0),c.raw=t;let a;if(l.srate>0){for(;c.seg+1<l.segs.length&&l.segs[c.seg+1].i0<=c.i;)c.seg++;a=hn(l,l.segs[c.seg],c.i)}else a=t+l.c0+l.c1*t;if(c.time[c.n]=a-n.origin,l.fmt===`string`){let t=[];for(let n=0;n<l.nch;n++){let[n,i]=J(o.body,e,f);t.push(r(o.body.subarray(f+i,f+i+n))),f+=i+n}c.sel.forEach((e,n)=>{c.cols[n][c.n]=t[e]}),m.push({time:a-n.origin,text:t.join(` `)})}else c.sel.forEach((t,n)=>{let r=f+t*p,i=c.cols[n];switch(l.fmt){case`float32`:i[c.n]=e.getFloat32(r,!0);break;case`double64`:i[c.n]=e.getFloat64(r,!0);break;case`int8`:i[c.n]=e.getInt8(r);break;case`int16`:i[c.n]=e.getInt16(r,!0);break;case`int32`:i[c.n]=e.getInt32(r,!0);break;default:i[c.n]=e.getInt32(r+4,!0)*4294967296+e.getUint32(r,!0)}}),f+=p*l.nch;c.i++,++c.n===i&&(yield s(c))}m.length&&(yield{group:c.g,time:new Float64Array,start:c.start,length:0,columns:c.sel.map(()=>new Float64Array),events:m})}for(let e of a.values())e.n&&(yield s(e))}},_n=2,vn=8,yn=4,bn=32,xn=64,Sn=4713,Cn=4714,Y=32,wn=68,X={1:1,2:2,3:4,4:8,5:1,6:2,7:4,8:8,9:4,10:8,25:4,26:8,33:1,68:16},Tn={0:5,1:1,2:6,3:2,4:7,5:3,6:8,7:4,8:9,9:10,4294967295:wn},En=65536,Dn=65536,On=(e,t,r)=>r?n(e,t+8,r)+x(e,t,r)/2**64:n(e,t,r)+x(e,t+8,r)/2**64;function kn(e,t,i,a,o){switch(a){case Y:{let n=e.getUint32(i,o);return[r(t.subarray(i+4,i+4+n)),4+n]}case 1:return[e.getInt8(i),1];case 2:return[e.getInt16(i,o),2];case 3:return[e.getInt32(i,o),4];case 4:return[n(e,i,o),8];case 5:return[e.getUint8(i),1];case 6:return[e.getUint16(i,o),2];case 7:return[e.getUint32(i,o),4];case 8:return[x(e,i,o),8];case 9:case 25:return[e.getFloat32(i,o),4];case 10:case 26:return[e.getFloat64(i,o),8];case 33:return[e.getUint8(i)!==0,1];case wn:return[On(e,i,o),16];default:throw Error(`This TDMS file has a property of type ${a}, which Kymoscope cannot read.`)}}function An(e){let t=/^\/'((?:[^']|'')*)'(?:\/'((?:[^']|'')*)')?$/.exec(e);return t?[t[1].replace(/''/g,`'`),(t[2]??``).replace(/''/g,`'`)]:null}var jn=4294967295;function Mn(e){if(e.has(`NI_Number_Of_Scales`))return Number(e.get(`NI_Number_Of_Scales`));let t=0;for(let n of e.keys()){let e=/^NI_Scale\[(\d+)\]_Scale_Type$/.exec(n);e&&(t=Math.max(t,Number(e[1])+1))}return t}function Nn(e,t,n){let r=e.find(e=>Mn(e)>0);if(!r||r.get(`NI_Scaling_Status`)===`scaled`)return null;let i=(e,a)=>{if(e===jn||e<0||a>8)return e=>e;let o=r.get(`NI_Scale[${e}]_Scale_Type`);if(o===void 0)return e=>e;if(o===`Linear`){let t=Number(r.get(`NI_Scale[${e}]_Linear_Slope`)),n=Number(r.get(`NI_Scale[${e}]_Linear_Y_Intercept`)??0),o=i(Number(r.get(`NI_Scale[${e}]_Linear_Input_Source`)??jn),a+1);return o&&(e=>t*o(e)+n)}if(o===`Polynomial`){let o=Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients_Size`)??4);if(!(Number.isInteger(o)&&o>=0&&o<=64))return t.push(`${n}: an NI polynomial scale with ${o} coefficients is not supported; raw values are shown.`),null;let s=Array.from({length:o},(t,n)=>Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients[${n}]`))),c=i(Number(r.get(`NI_Scale[${e}]_Polynomial_Input_Source`)??jn),a+1);return c&&(e=>{let t=c(e),n=0;for(let e=o-1;e>=0;e--)n=n*t+s[e];return n})}return t.push(`${n}: NI scale type ${String(o)} is not supported; raw values are shown.`),null};return i(Mn(r)-1,0)}var Pn={1:Int8Array,2:Int16Array,3:Int32Array,5:Uint8Array,6:Uint16Array,7:Uint32Array,9:Float32Array,10:Float64Array,25:Float32Array,26:Float64Array,33:Uint8Array};function Fn(e,t,r,i,a,o,s,c){let l=Pn[e];if(l&&o&&i===X[e]&&(t.byteOffset+r)%i===0){s.set(new l(t.buffer,t.byteOffset+r,a),c);return}switch(e){case 1:for(let e=0;e<a;e++,r+=i)s[c+e]=t.getInt8(r);return;case 2:for(let e=0;e<a;e++,r+=i)s[c+e]=t.getInt16(r,o);return;case 3:for(let e=0;e<a;e++,r+=i)s[c+e]=t.getInt32(r,o);return;case 4:for(let e=0;e<a;e++,r+=i)s[c+e]=n(t,r,o);return;case 5:case 33:for(let e=0;e<a;e++,r+=i)s[c+e]=t.getUint8(r);return;case 6:for(let e=0;e<a;e++,r+=i)s[c+e]=t.getUint16(r,o);return;case 7:for(let e=0;e<a;e++,r+=i)s[c+e]=t.getUint32(r,o);return;case 8:for(let e=0;e<a;e++,r+=i)s[c+e]=x(t,r,o);return;case 9:case 25:for(let e=0;e<a;e++,r+=i)s[c+e]=t.getFloat32(r,o);return;case 10:case 26:for(let e=0;e<a;e++,r+=i)s[c+e]=t.getFloat64(r,o);return;case wn:for(let e=0;e<a;e++,r+=i)s[c+e]=On(t,r,o);return;default:s.fill(NaN,c,c+a)}}async function In(e,n,i){let a=new Map,o=[],s=[],c=new Map,l=new Map,u=n??e,d=0,f=0;for(;d+28<=e.size&&f+28<=u.size;){let p=n?f:d,m=await u.read(p,28),h=t(m);if(!(m[0]===84&&m[1]===68&&m[2]===83&&(m[3]===109||m[3]===104)))throw Error(`This TDMS file is damaged (no segment lead-in where one should be).`);let g=h.getUint32(4,!0),_=!(g&xn),v=x(h,12,_),y=x(h,20,_),b=v>=2**53?e.size:Math.min(e.size,d+28+v);if(y>b-d-28)throw Error(`This TDMS file is damaged (segment metadata longer than its segment).`);if(g&_n){let e=await u.read(p+28,y),n=t(e);g&yn&&(s=[],c=new Map);let o=0,d=n.getUint32(o,_);o+=4;for(let t=0;t<d;t++){let t=n.getUint32(o,_),u=r(e.subarray(o+4,o+4+t));o+=4+t;let d=An(u),f=a.get(u);f||a.set(u,f={path:u,group:d?.[0]??``,name:d?.[1]??``,type:0,props:new Map,pieces:[],total:0});let p=n.getUint32(o,_);o+=4;let m=null;if(p===4294967295)m=null;else if(p===0)m=l.get(f)??null;else if(p===Sn||p===Cn){let e=x(n,o+8,_),t=n.getUint32(o+16,_),r=p===Sn?20:17,a=o+20,s=Tn[n.getUint32(a,_)]??0,c=n.getUint32(a+8,_);o=a+t*r;let l=n.getUint32(o,_);o+=4;let u=0;for(let e=0;e<l;e++)u+=n.getUint32(o+4*e,_);o+=4*l,p===Cn?i.push(`${f.name}: DAQmx digital line data is not supported; skipped.`):(t>1&&i.push(`${f.name}: only the first of its ${t} DAQmx scalers is read.`),m={type:s,count:e,bytes:0,daqmx:{byteOffset:c,stride:u}})}else{let e=n.getUint32(o,_),t=x(n,o+8,_),r=e===Y?x(n,o+16,_):t*(X[e]??0);o+=p-4,m={type:e,count:t,bytes:r,daqmx:null}}m&&(f.type=m.type,l.set(f,m));let h=n.getUint32(o,_);o+=4;for(let t=0;t<h;t++){let t=n.getUint32(o,_),i=r(e.subarray(o+4,o+4+t));o+=4+t;let a=n.getUint32(o,_);o+=4;let[s,c]=kn(n,e,o,a,_);f.props.set(i,s),o+=c}let g=c.get(f);g===void 0?c.set(f,s.push({obj:f,idx:m})-1):s[g].idx=m}}if(g&vn){let e=d+28+y,t=s.filter(e=>e.idx&&e.idx.count>0),n=t.filter(e=>e.idx.daqmx),r=(g&bn)!==0,i=0,a=0;n.length?(a=n[0].idx.daqmx.stride,i=n[0].idx.count*a):r?(a=t.reduce((e,t)=>e+(X[t.idx.type]??0),0),i=(t[0]?.idx.count??0)*a):i=t.reduce((e,t)=>e+t.idx.bytes,0);let c=i>0?Math.floor((b-e)/i):0,l=o.push({rawStart:e,chunkSize:i,chunks:c,le:_})-1,u=0;for(let e of t){let t=e.idx,n=X[t.type]??0,o=t.daqmx?{seg:l,count:t.count,offset:t.daqmx.byteOffset,bytes:0,stride:a,type:t.type}:{seg:l,count:t.count,offset:u,bytes:t.bytes,stride:r?a:n,type:t.type};t.daqmx||(u+=r?n:t.bytes),o.type===Y?o.count=Math.min(o.count,Math.floor(o.bytes/4)):n>0&&(o.count=Math.min(o.count,o.stride>0?Math.max(0,Math.floor((i-o.offset-n)/o.stride)+1):0)),e.obj.pieces.push(o),c&&(e.obj.total+=o.count*c)}}if(d=b,f+=28+y,b>=e.size)break}return{objs:[...a.values()],segments:o}}var Ln={...l,async plan(e,n){let r=e.companions.find(e=>e.name.toLowerCase().endsWith(`.tdms_index`)),i=[],{objs:o,segments:s}=await In(n,r?new a(r):null,i),c=o.find(e=>e.path===`/`)?.props,l=o.filter(e=>e.name&&e.total>0&&(e.type===Y||X[e.type])),u=new Set(l);for(let e of o)e.name&&e.total>0&&!u.has(e)&&i.push(`${e.name}: TDMS data type ${e.type} is not supported; skipped.`);let d=l.map(e=>e.props.get(`wf_start_time`)).filter(e=>typeof e==`number`),f=d.reduce((e,t)=>Math.min(e,t),d.length?1/0:0),p=new Map;for(let e of l){let t=`${e.total}|${e.props.get(`wf_increment`)??``}`,n=p.get(e.group)??new Map,r=n.get(t);r?r.push(e):n.set(t,[e]),p.set(e.group,n)}let m=[],h=[];for(let[e,t]of p)for(let n of t.values()){let r=n[0].props.get(`wf_increment`),i=typeof r==`number`&&r>0?1/r:null,a=i?null:n.find(e=>e.type===wn)??n.find(e=>e.type!==Y&&/^(time|timestamp|t)$/i.test(e.name))??null,o=n.filter(e=>e!==a),s=n[0].props.get(`wf_start_time`),c=i?Number(n[0].props.get(`wf_start_offset`)??0)+(typeof s==`number`?s-f:0):0;m.push({name:t.size===1?e:`${e} (${i?+i.toFixed(6):n[0].total} ${i?`Hz`:`samples`})`,channels:o.map(e=>({name:e.name,unit:String(e.props.get(`unit_string`)??``),text:e.type===Y})),samples:n[0].total,time:i?{kind:`rate`,rate:i,start:c}:a?{kind:`timestamps`}:{kind:`index`},rateHz:i}),h.push({channels:o,time:a,origin:0})}if(m.length===0)throw Error(`This TDMS file has no channels with data.`);let g=[];for(let e of h){if(!e.time)continue;let r=e.time.pieces[0],i=s[r.seg],a=await n.read(i.rawStart+r.offset,X[r.type]??8),o=new Float64Array(1);Fn(r.type,t(a),0,0,1,i.le,o,0),g.push(o[0])}let _=g.reduce((e,t)=>Math.min(e,t),g.length?1/0:0);for(let e of h)e.origin=_;let v=new Date(Date.UTC(1904,0,1)+f*1e3),y=f&&Number.isFinite(v.getTime())?v.toISOString():null,b={objs:o,segments:s,groups:h},x={};for(let[e,t]of c??[])typeof t==`string`&&(x[e]=t);return{format:`TDMS`,startTime:y,groups:m,meta:x,events:[],notes:i,state:b}},async*stream(e){for(let t of e.selection)yield*zn(e,t.group)},streamGroup:(e,t)=>zn(e,t)};function Rn(e,t,n,r,i,a){let o=0;for(;o<i&&r.pi<t.pieces.length;){let s=t.pieces[r.pi],c=e.segments[s.seg];if(r.chunk>=c.chunks){r.pi++,r.chunk=0,r.row=0;continue}let l=Math.min(i-o,s.count-r.row),u=c.rawStart+r.chunk*c.chunkSize+s.offset;if(s.type===Y)a.push({ch:n,at:u,end:u+s.bytes,rows:l,first:r.row,out:o,piece:s,le:c.le,range:0});else{let e=u+r.row*s.stride;a.push({ch:n,at:e,end:e+(l-1)*s.stride+X[s.type],rows:l,first:r.row,out:o,piece:s,le:c.le,range:0})}o+=l,r.row+=l,r.row>=s.count&&(r.chunk++,r.row=0)}}async function*zn(e,n){let i=e.plan.state,a=i.groups[n],o=C(e,n).map(e=>a.channels[e]),s=a.time?[a.time,...o]:o;if(!s.length)return;let c=new Map(i.objs.map(e=>[e.path,e.props])),l=e=>c.get(e)??new Map,u=l(`/`),d=s.map(e=>Nn([e.props,l(`/'${e.group.replace(/'/g,`''`)}'`),u],[],e.name)),f=s.map(()=>({pi:0,chunk:0,row:0})),p=s.reduce((e,t)=>Math.min(e,t.total),1/0);for(let o=0;o<p;){e.signal?.throwIfAborted();let c=Math.min(En,p-o),l=[];s.forEach((e,t)=>Rn(i,e,t,f[t],c,l));let u=l.slice().sort((e,t)=>e.at-t.at),m=[];for(let e of u){let t=m[m.length-1];t&&e.at<=t.end+Dn&&Math.max(t.end,e.end)-t.at<=16777216?t.end=Math.max(t.end,e.end):m.push({at:e.at,end:e.end}),e.range=m.length-1}let h=[];for(let t of m)h.push(await e.io.slice(t.at,t.end-t.at));let g=h.map(t),_=s.map(e=>e.type===Y?Array(c).fill(null):new Float64Array(c).fill(NaN));for(let e of l){let t=e.at-m[e.range].at,n=e.piece;if(n.type===Y){let i=h[e.range],a=g[e.range],o=t+4*n.count,s=_[e.ch];for(let n=0;n<e.rows;n++){let c=e.first+n,l=c===0?0:a.getUint32(t+4*(c-1),e.le),u=a.getUint32(t+4*c,e.le);s[e.out+n]=r(i.subarray(o+l,o+u))}}else Fn(n.type,g[e.range],t,n.stride,e.rows,e.le,_[e.ch],e.out)}for(let e=0;e<s.length;e++){let t=d[e],n=_[e];if(t&&n instanceof Float64Array)for(let e=0;e<c;e++)n[e]=t(n[e])}let v=null;if(a.time){v=_.shift();for(let e=0;e<c;e++)v[e]-=a.origin}yield{group:n,time:v,start:o,length:c,columns:_},o+=c}}var Bn=e=>!!e&&typeof e.keys==`function`,Vn=1e5;function Hn(){let e=new Set,t=0,n=!1;return{enter(t){let r=null;try{r=t.create_reference?Array.prototype.join.call(t.create_reference().ref_data,`,`):null}catch{r=null}return r===null?!0:e.has(r)?(n=!0,!1):(e.add(r),!0)},count:()=>++t<=Vn,note:()=>t>1e5?`This file has more than ${Vn.toLocaleString(`en-US`)} objects (or links that repeat its groups); only the first were read.`:n?`Some groups of this file link back to a group already read; each was read once.`:null}}function Un(e,t,n,r){return t.reduce((e,t)=>e*t,1)*Math.max(1,e.metadata.size||1)>(r?n*1032+1024:n)}var Wn=e=>!!e&&typeof e.slice==`function`,Gn=null,Z=null,Kn=new WeakMap;function qn(){!Gn||Z||(Z=Gn(),Z.catch(()=>{Z=null}))}function Jn(e){if(!Gn)return Promise.reject(Error(`HDF5 and MAT 7.3 files are read in the import worker, and this environment has no workers.`));qn();let t=Kn.get(e);return t||(t=Z.then(t=>t(e)).then(e=>({root:e.root,close:()=>{}})),Kn.set(e,t),t.catch(()=>Kn.delete(e))),t}var Yn=new WeakMap;function Xn(e,t,n){let r=Yn.get(e);r||Yn.set(e,r=new Map);let i=r.get(t);return i||r.set(t,i=n??e.get(t)),i}function Q(e){return e instanceof Float64Array?e:e instanceof BigInt64Array||e instanceof BigUint64Array?Float64Array.from(e,e=>Number(e)):ArrayBuffer.isView(e)?new Float64Array(e):Float64Array.from(e)}var Zn={s:1,sec:1,second:1,seconds:1,ms:.001,msec:.001,us:1e-6,µs:1e-6,ns:1e-9};function Qn(e,...t){for(let n of t){let t=e[n]?.value;if(typeof t==`string`)return t;if(Array.isArray(t)&&typeof t[0]==`string`)return t[0]}return``}function $n(e,...t){for(let n of t){let t=e[n]?.value,r=typeof t==`number`?t:ArrayBuffer.isView(t)?Number(t[0]):NaN;if(Number.isFinite(r))return r}return null}var er=0,tr=1,nr=3,rr=6,ir=new Set([1,2,3,4,5,6]),ar=/^(time|t|timestamps?|.*[_ ]time|time[_ ].*)$/i,or=[`sampling_rate`,`sample_rate`,`samplerate`,`sampleRate`,`fs`,`Fs`,`rate`];function sr(e,t,n,r,i,a,o=0){i.set(n,t.attrs);for(let s of t.keys()){if(!a.count())return;let c=n===`/`?`/${s}`:`${n}/${s}`,l=t.get(s);if(Bn(l))o<16&&a.enter(l)&&sr(e,l,c,r,i,a,o+1);else if(Wn(l)){let t=Xn(e,c,l);r.push({path:c,parent:n,name:s,ds:t,attrs:t.attrs})}}}var cr=e=>e===`/`?`root`:e.slice(1),lr=e=>Math.max(4096,Math.min(1<<20,Math.floor((8<<20)/(8*Math.max(1,e)))));async function ur(e,t){let n=Xn(e,t.path);if(t.col===null)return Q(n.slice([[0,1]]))[0]*t.factor;let r=n.slice([[0,1]]);return Number(r[0][t.col])*t.factor}var dr={...f,async plan(e){let t=await Jn(e.main);try{let n=[],r=new Map,i=Hn();i.enter(t.root),sr(t.root,t.root,`/`,n,r,i);let a=[],o=i.note();o&&a.push(o);let s=new Map,c=[],l=0;for(let t of n){let n=t.ds.metadata.shape??[],r=t.ds.metadata.type,i=t.ds.metadata.chunks?t.ds.filters??[]:[],o=i.find(e=>!ir.has(e.id)),u=!o;if(u&&i.length>0&&n.length>0&&n.every(e=>e>0))try{t.ds.slice(n.map(()=>[0,1]))}catch{u=!1}if(!u){a.push(`${t.path}: compressed with a filter Kymoscope cannot read${o?` (${o.name||o.id})`:``}; skipped.`);continue}if(Un(t.ds,n,e.main.size,i.length>0)){a.push(`${t.path}: larger than the file can hold (never written, or damaged); skipped.`);continue}if(n.length===1&&n[0]>1&&(r===er||r===tr||r===nr)){let e=`${t.parent}|${n[0]}`,r=s.get(e)??{parent:t.parent,n:n[0],leaves:[]};r.leaves.push(t),s.set(e,r)}else if(n.length===2&&n[0]>1&&n[1]<=4096&&(r===er||r===tr)){let e=$n(t.attrs,...or);c.push({name:cr(t.path),kind:`matrix`,rows:n[0],rate:e,time:null,origin:0,cols:Array.from({length:n[1]},(e,n)=>({path:t.path,col:n,text:!1,factor:1}))})}else if(n.length===1&&r===rr){let e=(t.ds.metadata.compound_type?.members??[]).flatMap((e,n)=>e.type===er||e.type===tr?[{path:t.path,col:n,text:!1,factor:1,name:e.name}]:[]),r=e.find(e=>ar.test(e.name));c.push({name:cr(t.path),kind:`compound`,rows:n[0],rate:null,origin:0,time:r??null,cols:e.filter(e=>e!==r)})}else l++}for(let e of s.values()){let t=[...s.values()].filter(t=>t.parent===e.parent).length>1,n=e.leaves.find(e=>Qn(e.attrs,`CLASS`)===`DIMENSION_SCALE`)??e.leaves.find(e=>ar.test(e.name)&&e.ds.metadata.type!==nr),i=n?Zn[Qn(n.attrs,`units`,`unit`,`Units`)]??1:1,a=n?null:$n(r.get(e.parent)??{},...or);c.push({name:t?`${cr(e.parent)} (${e.n} rows)`:cr(e.parent),kind:`vectors`,rows:e.n,rate:a,origin:0,time:n?{path:n.path,col:null,text:!1,factor:i}:null,cols:e.leaves.filter(e=>e!==n).map(e=>({path:e.path,col:null,text:e.ds.metadata.type===nr,factor:1}))})}l&&a.push(`${l} dataset${l===1?``:`s`} with other shapes or types (images, references, 3-D) skipped.`),c.sort((e,t)=>e.name.localeCompare(t.name));let u=c.map((e,t)=>e.time||e.rate?t:-1).filter(e=>e>=0),d=1/0;for(let e of c)e.time&&(d=Math.min(d,await ur(t.root,e.time)));for(let e of c)e.origin=Number.isFinite(d)?d:0;let f=new Map(n.map(e=>[e.path,e]));for(let e of c)e.chunk=[...e.cols,...e.time?[e.time]:[]].reduce((e,t)=>Math.max(e,f.get(t.path).ds.metadata.chunks?.[0]??0),0);let p=e=>Qn(f.get(e.path).attrs,`units`,`unit`,`Units`,`UNITS`),m=(e,t)=>e.kind===`matrix`?`${e.name.split(`/`).pop()}[${t.col+1}]`:e.kind===`compound`?f.get(t.path).ds.metadata.compound_type.members[t.col].name:t.path.split(`/`).pop(),h=c.map(e=>({name:e.name,channels:e.cols.map(t=>({name:m(e,t),unit:e.kind===`vectors`?p(t):``,text:t.text})),samples:e.rows,time:e.time?{kind:`timestamps`}:e.rate?{kind:`rate`,rate:e.rate,start:0}:{kind:`index`},rateHz:e.rate}));if(h.length===0)throw Error(`This HDF5 file has no datasets Kymoscope can plot.`);let g=h.length>20||h.length>1&&u.length<h.length,_=g?u.length?u:[c.reduce((e,t,n)=>t.rows*t.cols.length>c[e].rows*c[e].cols.length?n:e,0)]:void 0;return g&&a.push(`Only the groups with a time base are read unless you choose others in the channel picker.`),{format:`HDF5`,startTime:null,groups:h,meta:{},events:[],notes:a,pick:g,defaultGroups:_,state:{groups:c}}}finally{t.close()}},async*stream(e){for(let t of e.selection)yield*fr(e,t.group)},streamGroup:(e,t)=>fr(e,t)};async function*fr(e,t){let n=e.plan.state.groups[t],r=C(e,t).map(e=>n.cols[e]),i=await Jn(e.files.main);try{let a=n.chunk??0,o=a>0?Math.max(1,Math.min(Math.floor((1<<20)/a),Math.ceil(lr(r.length+1)/a)))*a:lr(r.length+1);for(let a=0;a<n.rows;a+=o){e.signal?.throwIfAborted();let s=Math.min(n.rows,a+o),c=s-a,l=null,u=e=>{let t=Xn(i.root,e.path);if(n.kind===`vectors`){let n=t.slice([[a,s]]);if(e.text)return Array.from(n,e=>e==null?null:String(e));let r=Q(n);if(e.factor!==1)for(let t=0;t<c;t++)r[t]*=e.factor;return r}let r=new Float64Array(c);if(n.kind===`matrix`){let n=(t.shape??[0,1])[1],i=l??=t.slice([[a,s],[0,n]]);for(let t=0;t<c;t++)r[t]=Number(i[t*n+e.col])}else{let n=l??=t.slice([[a,s]]);for(let t=0;t<c;t++)r[t]=Number(n[t][e.col])*e.factor}return r},d=null;if(n.time){d=u(n.time);for(let e=0;e<c;e++)d[e]-=n.origin}yield{group:t,time:d,start:a,length:c,columns:r.map(u)}}}finally{i.close()}}var pr=/^(time|t|tout|timestamps?)$/i,mr=/^(fs|sample_?rate|sampling_?rate|rate|samplerate)$/i,hr=e=>e.slice(e.lastIndexOf(`.`)+1),gr=e=>e.includes(`.`)?e.slice(0,e.lastIndexOf(`.`)):``;function _r(e,t){let n=/^(.*)\.values(\[\d+\])?$/.exec(e.name),r=n&&(t.get(`${n[1]}.label`)||t.get(`${n[1]}.blockName`));return r?{...e,name:`${r}${n[2]??``}`}:e}function vr(e,t,n){let r=new Map;for(let t of e){if(!(t.length>1))continue;let e=r.get(t.length);e?e.push(t):r.set(t.length,[t])}let i=[...n].filter(([e])=>mr.test(hr(e))),a=i.length===1?i[0][1]:null,o=[];for(let[e,n]of r){let r=n.find(e=>pr.test(hr(e.name))||/(_time|\.Time)$/.test(e.name))??null;o.push({name:r?gr(r.name)||r.name:`${e} samples`,channels:n.filter(e=>e!==r).map(e=>_r(e,t)),time:r,rate:r?null:a,origin:0})}return o}function yr(e){return e.map(e=>({name:e.name,channels:e.channels.map(e=>({name:e.name,unit:``})),samples:e.channels[0]?.length??e.time?.length??0,time:e.time?{kind:`timestamps`}:e.rate?{kind:`rate`,rate:e.rate,start:0}:{kind:`index`},rateHz:e.rate}))}async function br(e){let t=1/0;for(let n of e)n.time&&(t=Math.min(t,(await n.time.read(0,1))[0]));for(let n of e)n.origin=Number.isFinite(t)?t:0}var xr=class{#e;size;constructor(e){this.#e=e,this.size=e.size}read(e,t){return t>=65536?this.#e.slice(e,t):this.#e.read(e,t)}release(){}},Sr=class{#e;#t;#n;#r=null;keep=!0;size;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.size=r.length}async read(e,t){return this.#r??=await G(await this.#e.slice(this.#t,this.#n),this.size,this.size),this.#r.subarray(e,e+t)}release(){this.keep||(this.#r=null)}},Cr={1:1,2:1,3:2,4:2,5:4,6:4,7:4,9:8,12:8,13:8};function wr(e,n,r,i,a=1){let o=t(n),s=i.length,c=Cr[e]*a;if(e===9&&a===1&&r){i.set(n.byteOffset%8==0?new Float64Array(n.buffer,n.byteOffset,s):new Float64Array(n.slice(0,s*8).buffer));return}switch(e){case 1:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getInt8(t);return;case 2:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getUint8(t);return;case 3:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getInt16(t,r);return;case 4:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getUint16(t,r);return;case 5:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getInt32(t,r);return;case 6:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getUint32(t,r);return;case 7:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getFloat32(t,r);return;case 9:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getFloat64(t,r);return;case 12:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getInt32(t+(r?4:0),r)*4294967296+o.getUint32(t+(r?0:4),r);return;case 13:for(let e=0,t=0;e<s;e++,t+=c)i[e]=o.getUint32(t+(r?4:0),r)*4294967296+o.getUint32(t+(r?0:4),r);return;default:i.fill(NaN)}}async function $(e,n,r){let i=t(await e.read(n,8)),a=i.getUint32(0,r);if(a>>>16)return{type:a&65535,bytes:a>>>16,data:n+4,next:n+8};let o=i.getUint32(4,r);return{type:a,bytes:o,data:n+8,next:a===15?n+8+o:n+8+o+(8-o%8)%8}}function Tr(e,t,n,r,i){let[a,o]=t,s=Cr[r.type];if(!s)return[];let c=(e,t)=>async(a,o)=>{let c=new Float64Array(o-a);return t===1?wr(r.type,await n.read(r.data+(e+a)*s,(o-a)*s),i,c):wr(r.type,await n.read(r.data+(e+a*t)*s,((o-a-1)*t+1)*s),i,c,t),c};return a===1||o===1?[{name:e,length:a*o,read:c(0,1)}]:a>=o?Array.from({length:o},(t,n)=>({name:`${e}[${n+1}]`,length:a,read:c(n*a,1)})):Array.from({length:a},(t,n)=>({name:`${e}[${n+1}]`,length:o,read:c(n,a)}))}async function Er(e,n,i,a,s,c,l){let u=n,d=await $(e,u,i),f=t(await e.read(d.data,8)).getUint32(0,i),p=f&255;u=d.next;let m=await $(e,u,i);if(m.bytes>128){c.notes.push(`A MAT variable with more than 32 dimensions was skipped (damaged).`);return}let h=t(await e.read(m.data,m.bytes)),g=Array.from({length:m.bytes/4},(e,t)=>h.getInt32(4*t,i));u=m.next;let _=await $(e,u,i),v=o(await e.read(_.data,_.bytes));u=_.next;let y=s??v,b=a?`${a}.${y}`:y,x=g.reduce((e,t)=>e*t,1);if(p>=6&&p<=15){if(x===0)return;let t=await $(e,u,i);if(f&2048&&c.notes.push(`${b}: the imaginary part was skipped.`),g.length>2){c.notes.push(`${b}: arrays with more than two dimensions are skipped.`);return}if(!Cr[t.type])return;if(!(x>0)||x*Cr[t.type]>t.bytes||t.data+t.bytes>e.size){c.notes.push(`${b}: its data is shorter than its dimensions (damaged); skipped.`);return}if(x===1){let n=new Float64Array(1);wr(t.type,await e.read(t.data,Cr[t.type]??8),i,n),c.scalars.set(b,n[0]);return}c.channels.push(...Tr(b,g,e,t,i));return}if(p===4){let t=await $(e,u,i);if(t.bytes>Dr)return;let n=await e.read(t.data,t.bytes),a=t.type===3||t.type===4||t.type===17?new TextDecoder(i?`utf-16le`:`utf-16be`).decode(n.subarray(0,n.length&-2)):r(n);g[0]<=1&&c.strings.set(b,a);return}if(p===2){let n=await $(e,u,i),r=t(await e.read(n.data,4)).getInt32(0,i);u=n.next;let a=await $(e,u,i);if(!(r>0))return;let o=await e.read(a.data,a.bytes),s=Array.from({length:Math.floor(o.length/r)},(e,t)=>S(o.subarray(t*r,(t+1)*r)));if(u=a.next,s.length===0||x*s.length*8>e.size-u){x>0&&s.length>0&&c.notes.push(`${b}: its fields are longer than the file (damaged); skipped.`);return}for(let t=0;t<x;t++){let n=x>1?`${b}(${t+1})`:b;for(let t of s){let r=await $(e,u,i);r.type===14&&r.bytes>0&&l<16&&await Er(e,r.data,i,n,t,c,l+1),u=r.next}}return}p===1?c.notes.push(`${b}: cell arrays are skipped.`):p===5?c.notes.push(`${b}: sparse arrays are skipped.`):c.notes.includes(Or)||c.notes.push(Or)}var Dr=1<<17,Or=`MATLAB objects (timeseries, SimulationOutput) were skipped: save them as 'Structure with time' or as structs.`,kr=512<<20;async function Ar(e){let n=o((await e.read(0,128)).subarray(126,128))===`IM`,r={channels:[],strings:new Map,scalars:new Map,notes:[],sources:[]},i=new xr(e),a=0;for(let o=128;o+8<=e.size;){let s=await $(i,o,n);if(s.type===15){if(s.bytes>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let i=await e.slice(s.data,s.bytes),o=await G(i,-1,8),l=o.length<8?0:8+t(o).getUint32(4,n);if(l>c(s.bytes))throw Error(`A compressed variable in this MAT file is damaged.`);if(l>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let u=await G(i,l,l),d=new Sr(e,s.data,s.bytes,u);r.sources.push(d),a+=u.length;let f=await $(d,0,n);if(f.type===14&&await Er(d,f.data,n,``,null,r,0),a>kr)for(let e of r.sources)e.keep=!1,e.release()}else s.type===14&&await Er(i,s.data,n,``,null,r,0);o=s.next}return r}var jr=65536,Mr=new Set([`double`,`single`,`int8`,`uint8`,`int16`,`uint16`,`int32`,`uint32`,`int64`,`uint64`,`logical`]);function Nr(e,t){let n={channels:[],strings:new Map,scalars:new Map,notes:[]},r=Hn();r.enter(e);let i=t=>Xn(e,t),a=(e,t,n)=>{let r=null;return(a,o)=>((r?.s!==a||r.e!==o)&&(r={s:a,e:o,v:Q(t?i(e).slice([[0,n],[a,o]]):i(e).slice([[a,o],[0,n]]))}),r.v)},o=(e,s,c,l)=>{for(let u of e.keys()){if(!r.count())return;if(u.startsWith(`#`))continue;let d=e.get(u);if(!d)continue;let f=`${s}/${u}`,p=c?`${c}.${u}`:u,m=d.attrs,h=Qn(m,`MATLAB_class`);if(m.MATLAB_empty)continue;if(Bn(d)){h===`struct`&&l<16&&r.enter(d)&&o(d,f,p,l+1);continue}if(!Wn(d))continue;let g=d.shape??[];if(h===`char`){if(g.reduce((e,t)=>e*t,1)>jr)continue;let e=Q(d.slice(g.map(e=>[0,e])));n.strings.set(p,new TextDecoder(`utf-16le`).decode(Uint16Array.from(e)))}else if(Mr.has(h)&&g.length===2&&Un(d,g,t,!!d.metadata.chunks))n.notes.push(`${p}: larger than the file can hold (never written, or damaged); skipped.`);else if(Mr.has(h)&&g.length===2){let[e,t]=g;if(e*t===1){n.scalars.set(p,Q(i(f).slice([[0,1],[0,1]]))[0]);continue}if(e===1||t===1){let r=e*t;n.channels.push({name:p,length:r,read:async(t,n)=>Q(e===1?i(f).slice([[0,1],[t,n]]):i(f).slice([[t,n],[0,1]]))})}else if(t>=e){let r=a(f,!0,e);for(let i=0;i<e;i++)n.channels.push({name:`${p}[${i+1}]`,length:t,read:async(e,t)=>r(e,t).slice(i*(t-e),(i+1)*(t-e))})}else{let r=a(f,!1,t);for(let i=0;i<t;i++)n.channels.push({name:`${p}[${i+1}]`,length:e,read:async(e,n)=>{let a=r(e,n),o=new Float64Array(n-e);for(let e=0;e<o.length;e++)o[e]=a[e*t+i];return o}})}}else h===`cell`?n.notes.push(`${p}: cell arrays are skipped.`):h&&n.notes.push(`${p}: MATLAB class ${h} is skipped.`)}};o(e,``,``,0);let s=r.note();return s&&n.notes.push(s),n}var Pr=e=>Math.max(4096,Math.min(1<<18,Math.floor((16<<20)/(8*Math.max(1,e))))),Fr={...u,async plan(t,n){let r=e(await n.read(0,20),`MATLAB 7.3`),i,a=[];if(r)i=Nr((await Jn(t.main)).root,t.main.size);else{let e=await Ar(n);a=e.sources,i=e}let o=vr(i.channels,i.strings,i.scalars).filter(e=>e.channels.length>0);await br(o);let s=yr(o);if(s.length===0)throw Error(`This MAT file has no numeric vectors or matrices to plot.`);let c=s.flatMap((e,t)=>e.time.kind===`index`?[]:[t]),l=s.length>1&&c.length<s.length,u=Object.fromEntries(i.strings);for(let[e,t]of i.scalars)u[e]=String(t);return{format:r?`MAT 7.3`:`MAT 5`,startTime:null,groups:s,meta:u,events:[],notes:i.notes,pick:l,defaultGroups:l&&c.length?c:void 0,state:{groups:o,sources:a}}},async*stream(e){for(let t of e.selection)yield*Ir(e,t.group)},streamGroup:(e,t)=>Ir(e,t)};async function*Ir(e,t){let n=e.plan.state,r=n.groups[t],i=C(e,t).map(e=>r.channels[e]),a=r.channels[0].length,o=Pr(i.length+1);try{for(let n=0;n<a;n+=o){e.signal?.throwIfAborted();let s=Math.min(a,n+o),c=null;if(r.time){c=await r.time.read(n,s);for(let e=0;e<c.length;e++)c[e]-=r.origin}let l=[];for(let e of i)l.push(await e.read(n,s));yield{group:t,time:c,start:n,length:s-n,columns:l}}}finally{for(let e of n.sources)e.release()}}function Lr(e,t){let n=/^\s*(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s*,\s*(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))?/.exec(e??``);if(!n)return[null,0,!1];let[r,i]=t===1991?[n[2],n[1]]:[n[1],n[2]],a=n[3].length===2?2e3+Number(n[3]):Number(n[3]),o=Number(`${n[6]}.${n[7]??`0`}`);return[`${a}-${i.padStart(2,`0`)}-${r.padStart(2,`0`)}T${n[4].padStart(2,`0`)}:${n[5]}:${o.toFixed(3).padStart(6,`0`)}`,Date.UTC(a,Number(i)-1,Number(r),Number(n[4]),Number(n[5]))/1e3+o,(n[7]??``).length>6]}function Rr(e){let t=e.split(/\r?\n/).map(e=>e.trim()),[n,,r]=t[0].split(`,`),i=Number(r)||1991,a=/(\d+)A\s*,\s*(\d+)D/i.exec(t[1]??``);if(!a)throw Error(`This COMTRADE .cfg is damaged (second line).`);let o=Number(a[1]),s=Number(a[2]);if(o+s>t.length)throw Error(`This COMTRADE .cfg is damaged (more channels than lines).`);let c=2,l=[];for(let e=0;e<o;e++,c++){let e=(t[c]??``).split(`,`);l.push({name:(e[1]??``).trim(),unit:(e[4]??``).trim(),a:Number(e[5]),b:Number(e[6]??0)||0})}let u=[];for(let e=0;e<s;e++,c++)u.push(((t[c]??``).split(`,`)[1]??``).trim());c++;let d=Number(t[c++]);if(!(Number.isInteger(d)&&d>=0&&d<=t.length-c))throw Error(`This COMTRADE .cfg is damaged (sample rates).`);let f=[];for(let e=0;e<Math.max(1,d);e++,c++){let[e,n]=(t[c]??``).split(`,`).map(Number);f.push([d===0?0:e,n])}let[p,m,h]=Lr(t[c++],i),[g,_,v]=Lr(t[c++],i),y=(t[c++]||`ASCII`).toUpperCase(),b=Number(t[c++])||1;return{station:n.trim(),rev:i,analog:l,digital:u,rates:f,start:p,trigger:g,startSec:m,triggerSec:_,ft:y,timemult:b,timebase:h||v?1e-9:1e-6}}var zr={BINARY:2,BINARY32:4,FLOAT32:4},Br=16<<20;async function Vr(e){let t=o(await e.read(0,Math.min(e.size,1<<20))),n=t.search(/---\s*file type:\s*CFG\s*---\r?\n/i),r=/---\s*file type:\s*DAT\s+(ASCII|BINARY32|BINARY|FLOAT32)(?:\s*:\s*(\d+))?\s*---\r?\n/i.exec(t);if(n<0||!r)throw Error(`This COMTRADE .cff is damaged (no CFG or DAT section in its first megabyte).`);let i=t.indexOf(`
3
- `,n)+1,a=t.slice(i).search(/---\s*file type:\s*(INF|HDR|DAT)/i),s=t.slice(i,a<0?void 0:i+a),c=r.index+r[0].length;return{cfg:s,offset:c,length:r[2]?Number(r[2]):e.size-c}}function Hr(e,t,n,r){let i=0,a=0,o=t,s=0;for(let[t,c]of e){for(;o<c&&s<n;)r[s++]=a+(o-i)/t,o++;if(a+=(c-i)/t,i=c,s>=n)return}let c=e[e.length-1];for(;s<n;s++,o++)r[s]=a+(o-i)/c[0]}var Ur=e=>e.companions.find(e=>e.name.toLowerCase().endsWith(`.dat`)),Wr={...h,async plan(e,t){let n=e.main.name.toLowerCase().endsWith(`.cff`),r,i;if(n){let e=await Vr(t);r=e.cfg,i={data:`self`,offset:e.offset,length:e.length}}else{let n=Ur(e);if(!n)throw Error(`This COMTRADE .cfg needs its .dat file: drop both together.`);if(t.size>Br)throw Error(`This .cfg is too large to be a COMTRADE configuration file.`);r=o(await t.read(0,t.size)),i={data:`companion`,offset:0,length:n.size}}let a=Rr(r);if(a.ft!==`ASCII`&&!zr[a.ft])throw Error(`This COMTRADE file has data file type ${a.ft}, which Kymoscope cannot read.`);let s=Math.ceil(a.digital.length/16),c=a.ft===`ASCII`?0:8+a.analog.length*zr[a.ft]+2*s,l=c?Math.floor(i.length/c):i.length,u=Math.min(a.rates[a.rates.length-1][1]||(c?l:-1),l),d=a.rates.length===1&&a.rates[0][0]>0?a.rates[0][0]:null,f=[`Analog values are shown as recorded (primary or secondary, per the CFG).`];return{format:`COMTRADE ${a.rev} (${a.ft})`,startTime:a.start,meta:{station:a.station,trigger:a.trigger??``},groups:[{name:a.station||`COMTRADE`,channels:[...a.analog.map(e=>({name:e.name,unit:e.unit})),...a.digital.map(e=>({name:e,unit:``}))],samples:u,time:{kind:`timestamps`},rateHz:d}],events:a.start&&a.trigger?[{time:Math.round((a.triggerSec-a.startSec)*1e6)/1e6,text:`Trigger`}]:[],notes:f,state:{...i,cfg:a,samples:u,recordSize:c}}},stream:e=>Gr(e)};async function*Gr(e){let n=e.plan.state,{cfg:r}=n,i=n.data===`self`?e.io:new a(Ur(e.files)),o=C(e,0),s=r.analog.length,c=r.rates[0][0]>0,l=r.timemult*r.timebase,u=65536,d=0,f=(e,t,n)=>{let i=new Float64Array(e);if(c)Hr(r.rates,d,e,i);else for(let n=0;n<e;n++)i[n]=t[n]*l;let a={group:0,time:i,start:d,length:e,columns:n};return d+=e,a};if(r.ft===`ASCII`){let t=r.rev>=1999?`99999`:``,a=o.map(e=>e<s?r.analog[e]:null),c=new Float64Array(u),l=o.map(()=>new Float64Array(u)),d=0,p=(e,n,r)=>{let i=e.slice(n,r).split(`,`);if(!(i.length<2)){c[d]=Number(i[1]);for(let e=0;e<o.length;e++){let n=(i[2+o[e]]??``).trim(),r=a[e];l[e][d]=n===``||r&&n===t?NaN:r?r.a*Number(n)+r.b:Number(n)}d++}},m=``,h=new TextDecoder(`latin1`);for await(let t of i.windows(n.offset,n.length)){e.signal?.throwIfAborted();let n=m+h.decode(t.bytes),r=0;for(let e=n.indexOf(`
4
- `,r);e>=0;e=n.indexOf(`
5
- `,r))p(n,r,e),r=e+1,d===u&&(yield f(d,c,l),c=new Float64Array(u),l=o.map(()=>new Float64Array(u)),d=0);m=n.slice(r)}m.trim()&&p(m,0,m.length),d&&(yield f(d,c.slice(0,d),l.map(e=>e.slice(0,d))));return}let p=n.recordSize,h=zr[r.ft],g=Math.max(1,Math.floor(Math.min(m,u*p)/p)),_=n.samples;for await(let a of i.windows(n.offset,Math.min(n.length,n.samples*p),g*p)){e.signal?.throwIfAborted();let n=Math.min(_,Math.floor(a.bytes.length/p));if(n<=0)break;let i=t(a.bytes),l=new Float64Array(n);if(!c)for(let e=0;e<n;e++)l[e]=i.getUint32(e*p+4,!0);yield f(n,l,o.map(e=>{let t=new Float64Array(n);if(e<s){let{a,b:o}=r.analog[e],s=8+e*h;if(r.ft===`BINARY`)for(let e=0,r=s;e<n;e++,r+=p){let n=i.getInt16(r,!0);t[e]=n===-32768?NaN:a*n+o}else if(r.ft===`BINARY32`)for(let e=0,r=s;e<n;e++,r+=p){let n=i.getInt32(r,!0);t[e]=n===-2147483648?NaN:a*n+o}else for(let e=0,r=s;e<n;e++,r+=p)t[e]=a*i.getFloat32(r,!0)+o}else{let r=e-s,a=8+s*h+2*(r>>4),o=1<<(r&15);for(let e=0,r=a;e<n;e++,r+=p)t[e]=i.getUint16(r,!0)&o?1:0}return t})),_-=n}}var Kr=8192;async function*qr(e){let t=0;for(;t+56<=e.size;){let n=g(await e.read(t,56));if(yield await e.slice(t,n.bytes),n.bytes<=56)return;t+=n.bytes}}function Jr(e){let t=e.filter(e=>e&&typeof e.t==`number`&&Array.isArray(e.signals)),n={},r={};return t.forEach((e,i)=>{for(let a of e.signals){if(!a||typeof a.name!=`string`)continue;let e=n[a.name]??=new Float64Array(t.length).fill(NaN);e[i]=typeof a.value==`number`?a.value:NaN,a.unit&&!r[a.name]&&(r[a.name]=a.unit)}}),{t:t.map(e=>e.t),columns:n,units:r}}async function*Yr(e,t,n){let r=d(e.keys??[]);for await(let e of qr(t)){let{header:t,messages:i}=p(e);n.t0??=t.t0;for(let e of i){let t=await r(e.bytes);if(!t){n.lost++;continue}try{if(t.kind===3){let n=_(t.plaintext);yield{at:e.at,t:n.t,columns:n.columns,units:n.units??{}}}else if(t.kind===2){let n=y(t.plaintext);yield{at:e.at,...Jr(Array.isArray(n?.frames)?n.frames:[])}}}catch{n.lost++}}}}var Xr={mdf:en,edf:on,xdf:gn,tdms:Ln,hdf5:dr,mat:Fr,comtrade:Wr,krc:{id:`krc`,label:`Kymoscope recording`,extensions:[],sniff:()=>!1,async plan(e,t){let n=[s],r=new Map([[s,`s`]]),i={lost:0,t0:null},a=0;for await(let o of Yr(e,t,i)){a+=o.t.length;for(let e of Object.keys(o.columns))e!==`ElapsedTime`&&(r.has(e)?!r.get(e)&&o.units[e]&&r.set(e,o.units[e]):(n.push(e),r.set(e,o.units[e]??``)))}let o=n.map(e=>({name:e,unit:r.get(e)??``})),c=i.lost?[`${i.lost} ${i.lost===1?`message`:`messages`} couldn't be opened with the keys this browser has.`]:[];return{format:`Kymoscope recording`,startTime:i.t0===null?null:new Date(i.t0).toISOString(),groups:[{name:`Recording`,channels:o,samples:a,time:{kind:`timestamps`},rateHz:null}],meta:{},events:[],notes:c,state:{names:n}}},async*stream(e){let{names:t}=e.plan.state,n=e.selection.find(e=>e.group===0)?.channels??[],r=new Map(n.map((e,n)=>[t[e],n])),i=r.get(s),a=()=>n.map(()=>new Float64Array(Kr).fill(NaN)),o=new Float64Array(Kr),c=a(),l=0,u=0,d=0,f=-1/0,p=0,m=null,h=()=>{let e={group:0,time:o.slice(0,l),start:u,length:l,columns:c.map(e=>e.slice(0,l))};return u+=l,l=0,o=new Float64Array(Kr),c=a(),e};for await(let t of Yr(e.files,e.io,{lost:0,t0:null})){if(e.signal?.aborted)return;let n=t.t.length;if(n!==0){+t.t[0]+d<f&&(d=f+Math.max(0,(t.at-p)/1e3)-+t.t[0]),p=t.at;for(let e=0;e<n;){let a=Math.min(n-e,Kr-l);for(let n=0;n<a;n++){let r=+t.t[e+n]+d;m??=r,o[l+n]=r-m,f=r}if(i!==void 0)for(let n=0;n<a;n++)c[i][l+n]=+t.t[e+n];for(let[n,i]of Object.entries(t.columns)){let t=n===`ElapsedTime`?void 0:r.get(n);if(t===void 0)continue;let o=c[t];if(i instanceof Float64Array||i instanceof Float32Array)o.set(i.subarray(e,e+a),l);else for(let t=0;t<a;t++)o[l+t]=+i[e+t]}l+=a,e+=a,l===Kr&&(yield h())}}}l>0&&(yield h())}}};function Zr(e){let t=Xr[e];if(!t)throw Error(`No importer for format ${e}.`);return t}export{Zr as importerFor};
@@ -1,9 +0,0 @@
1
- /*! @kymoscope/sdk (c) 2026 Kymoscope. Proprietary software: use requires a license. See LICENSE.md. */
2
- var e=Symbol(`row`),t=new WeakMap;function n(e){return t.get(e)}function r(e,t){let n=e.keys.lastIndexOf(t);return n<0?void 0:e.values[n]}var i=new WeakMap;function a(n,r){let a=n.keys.join(`
3
- `),o=r&&i.get(r);if(o&&o.keys===a&&r.length===n.length){o.t=n;let e=new Proxy(o.base,{});return i.set(e,o),t.set(e,n),t.set(r,n),e}let s=Array(n.length),c={t:n,keys:a,base:s},l={};n.keys.forEach((t,n)=>{Object.defineProperty(l,t,{enumerable:!0,configurable:!0,get(){let t=this[e],{values:r,text:i}=c.t,a=r[n][t],o=i[n];return a===a?a:o?o[t]??null:null},set(e){Object.defineProperty(this,t,{value:e,writable:!0,enumerable:!0,configurable:!0})}})});for(let t=0;t<n.length;t++){let n=Object.create(l);n[e]=t,s[t]=n}return i.set(s,c),t.set(s,n),s}function o(e){let t=Array(e.length);for(let n=0;n<e.length;n++){let r={};for(let t=0;t<e.keys.length;t++){let i=e.values[t][n];r[e.keys[t]]=i===i?i:e.text[t]?.[n]??null}t[n]=r}return t}function s(e,t){let n=Number(t?e.replace(`,`,`.`):e);return Number.isFinite(n)?n:null}function c(e,t){let n=e.trim();if(n===``)return null;let r=s(n,t);return r===null?n:r}function l(e,t){if(t===`,`)return!1;let n=0,r=0;for(let i of e)for(let e of d(i,t)){let t=e.trim();/^-?\d+,\d+$/.test(t)?n++:/^-?\d+\.\d+$/.test(t)&&r++}return n>r}function u(e){let t=(e.match(/\t/g)??[]).length,n=(e.match(/;/g)??[]).length,r=0,i=!1;for(let t=0;t<e.length;t++){let n=e[t];n===`"`?i=!i:!i&&n===`,`&&r++}return t>0&&t>=r&&t>=n?` `:n>r?`;`:r>0?`,`:` `}function d(e,t){if(t===` `)return e.split(` `);let n=[],r=``,i=!1;for(let a=0;a<e.length;a++){let o=e[a];i?o===`"`?e[a+1]===`"`?(r+=`"`,a++):i=!1:r+=o:o===`"`?i=!0:o===t?(n.push(r),r=``):r+=o}return n.push(r),n}function f(e,t){let n=0,r=0;for(let i of e){let e=i.trim();e!==``&&(n++,s(e,t)!==null&&r++)}return n>0&&r/n>=.5}function p(e,t){if(t===void 0)return!1;let n=e=>/[\t,;]/.test(e);return!n(e)&&n(t)}function m(e){let t=[];for(let n of e.split(/\r\n|\r|\n/)){let e=n.replace(/\uFEFF/g,``).trimEnd();e.length>0&&t.push(e)}return t}function h(e,t){return e.headerRow===t.headerRow&&e.unitsRow===t.unitsRow&&e.dataStartRow===t.dataStartRow}function g(e){let t=[` `,`;`,`,`],n={delim:` `,cols:1,agree:0};for(let r of t){let t=new Map;for(let n of e){let e=d(n,r).length;e>1&&t.set(e,(t.get(e)??0)+1)}for(let[e,i]of t)(i>n.agree||i===n.agree&&e>n.cols)&&(n={delim:r,cols:e,agree:i})}return{delim:n.delim,cols:n.cols}}function _(e){let t=m(e);if(t.length===0)return{headerRow:0,unitsRow:null,dataStartRow:1};let n=t.slice(0,10),{delim:r,cols:i}=g(n),a=e=>d(e,r).length===i,o=e=>d(e,r).every(e=>e.trim()!==``),s=n.findIndex(e=>a(e)&&o(e));s<0&&(s=n.findIndex(a)),(s<0||i<=1)&&(s=0);let c=null,u=s+1;if(t.length>s+1){let e=l(t.slice(s+1,s+11),r);f(d(t[s+1],r),e)||(c=s+1,u=s+2)}return{headerRow:s,unitsRow:c,dataStartRow:u}}function v(e,t){let n=e[t]??``,r=d(n,u(n)).map(e=>e.trim());if(r.length===0||r.every(e=>e===``))throw Error(`No column names were found.`);return r}function y(e,t){let{table:n,...r}=b(e,t);return{...r,rows:o(n)}}function b(e,t){let{headerRow:n,unitsRow:r,dataStartRow:i}=t,a=[],o=-1,s=0;for(;s<=e.length&&a.length<i+10;){a.length===i&&o<0&&(o=s);let n=e.indexOf(`
4
- `,s);n<0&&(n=e.length);let r=e.slice(s,n);if(/\r(?!$)/.test(r))return te(e,t);let c=r.replace(/\uFEFF/g,``).trimEnd();c.length>0&&a.push(c),s=n+1}if(a.length===i&&o<0&&(o=s),o<0)return te(e,t);let f=u(a[n]??``),m=v(a,n),h=[];r!==null&&a[r]!==void 0&&(h=d(a[r],f).map(e=>e.trim())),h.length===0&&(h=m.map(()=>``));let g=l(a.slice(i,i+10),f),_=m.map((e,t)=>e||`col_${t}`),y=_.length,b=1;for(let t=e.indexOf(`
5
- `,o);t>=0;t=e.indexOf(`
6
- `,t+1))b++;let x=0;for(let t=e.indexOf(`\r`,o);t>=0;t=e.indexOf(`\r`,t+1))e.charCodeAt(t+1)!==10&&x++;b+=x;let C=_.map(()=>new Float64Array(b)),ne=_.map(()=>null),w=0,T=(e,t)=>{typeof t==`number`?C[e][w]=t:(C[e][w]=NaN,t!==null&&((ne[e]??=[])[w]=t))},E=e=>{let t=d(e,f);if(!(t.length===1&&t[0].trim()===``)){for(let e=0;e<y;e++)T(e,t[e]===void 0?null:c(t[e],g));w++}},D=f.charCodeAt(0),O=D!==9&&e.indexOf(`"`,o)>=0||e.indexOf(``,o)>=0||x>0;for(s=o;s<e.length;){let t=e.indexOf(`
7
- `,s);t<0&&(t=e.length);let n=t;n>s&&e.charCodeAt(n-1)===13&&n--;let r=n>s;if(r){let t=e.charCodeAt(n-1);r=t>32&&t<127}if(r&&O)for(let t=s;t<n;t++){let n=e.charCodeAt(t);if(n===13||n===65279||n===34&&D!==9){r=!1;break}}if(r){let t=s;for(let r=0;r<y;r++){if(t>n){T(r,null);continue}let i=ee(e,t,n,D,g);if(i===i){C[r][w]=i,t=S+1;continue}let a=e.indexOf(f,t);(a<0||a>n)&&(a=n),T(r,c(e.slice(t,a),g)),t=a+1}w++}else{let n=e.slice(s,t);for(let e of n.split(/\r\n|\r|\n/)){let t=e.replace(/\uFEFF/g,``).trimEnd();t.length>0&&E(t)}}s=t+1}let re=C.map(e=>b-w>b/100?e.slice(0,w):e.subarray(0,w));return{meta:a.length>0&&p(a[0],a[1])?a[0]:``,columnNames:m,units:h,table:{keys:_,length:w,values:re,text:ne}}}var x=Array.from({length:23},(e,t)=>10**t),S=0;function ee(e,t,n,r,i){let a=t,o=e.charCodeAt(a),s=o===45;(s||o===43)&&a++;let c=0,l=0,u=0,d=!1,f=!1;for(;a<n;a++)if(o=e.charCodeAt(a),o>=48&&o<=57){if(d=!0,c===0&&o===48){f&&u++;continue}if(++l>15)return NaN;c=c*10+(o-48),f&&u++}else if((o===46||i&&o===44&&r!==44)&&!f)f=!0;else break;if(!d)return NaN;let p=0;if(a<n&&o!==r){if(o!==101&&o!==69)return NaN;a++,o=e.charCodeAt(a);let t=o===45;(t||o===43)&&a++;let i=a;for(;a<n&&(o=e.charCodeAt(a),o!==r);a++){if(o<48||o>57||p>400)return NaN;p=p*10+(o-48)}if(a===i)return NaN;t&&(p=-p)}let m=p-u,h;if(c===0)h=0;else if(m>=0&&m<=22)h=c*x[m];else if(m<0&&m>=-22)h=c/x[-m];else return NaN;return S=a,s?-h:h}function te(e,t){let n=m(e),{headerRow:r,unitsRow:i,dataStartRow:a}=t,o=u(n[r]??``),s=v(n,r),f=[];i!==null&&n[i]!==void 0&&(f=d(n[i],o).map(e=>e.trim())),f.length===0&&(f=s.map(()=>``));let h=n.slice(a),g=l(h.slice(0,10),o),_=s.map((e,t)=>e||`col_${t}`),y=h.length,b=_.map(()=>new Float64Array(y)),x=_.map(()=>null),S=0;for(let e of h){let t=d(e,o);if(!(t.length===1&&t[0].trim()===``)){for(let e=0;e<_.length;e++){let n=t[e]===void 0?null:c(t[e],g);typeof n==`number`?b[e][S]=n:(b[e][S]=NaN,n!==null&&((x[e]??=[])[S]=n))}S++}}return S<y&&(b=b.map(e=>e.slice(0,S))),{meta:n.length>0&&p(n[0],n[1])?n[0]:``,columnNames:s,units:f,table:{keys:_,length:S,values:b,text:x}}}var C=5e3;function ne(e,t){let n=w.get(e);n||w.set(e,n=new Map);let r=n.get(t);return r===void 0&&n.set(t,r=T(e,t)),r}var w=new WeakMap;function T(e,t){let r=n(e),i=r?r.keys.lastIndexOf(t):-1;if(r&&i>=0&&!r.text[i]){let e=r.values[i];for(let t=0;t<e.length;t++)if(e[t]===e[t])return!0;return!1}let a=e.length,o=0,s=0,c=Math.max(1,Math.floor(a/C));for(let n=0;n<a;n+=c){let r=e[n][t];r!=null&&(o++,typeof r==`number`&&s++)}if(o===0&&c>1)for(let n=0;n<a&&o<C;n++){let r=e[n][t];r!=null&&(o++,typeof r==`number`&&s++)}return o>0&&s/o>.95}function E(e,t){if(e<=t)return Array.from({length:e},(e,t)=>t);let n=[],r=e/t,i=0;for(let a=0;a<t;a++)n.push(Math.min(e-1,Math.floor(i))),i+=r;return n}var D=[];function O(e){return D.push(e),e}function re(e){for(let t of D)t.delete(e)}function ie(e,t,n,r,i,a){let o=(i-r)/a;if(!(i>r)||a<1)return{x0:r,bucket:0,rows:[],columns:n};let s=Math.floor(a);if(oe(e))return{x0:r,bucket:o,rows:se(e,t,r,i,o,s),columns:n};let c=new Uint8Array(s),l=t.map(()=>new Float64Array(s).fill(1/0)),u=t.map(()=>new Float64Array(s).fill(-1/0));for(let n=0;n<e.length;n++){let a=e[n];if(!(a>=r&&a<=i))continue;let d=Math.floor((a-r)/o);d>=s&&(d=s-1),c[d]=1;for(let e=0;e<t.length;e++){let r=t[e][n];r===r&&(r<l[e][d]&&(l[e][d]=r),r>u[e][d]&&(u[e][d]=r))}}let d=[];for(let e=0;e<s;e++){if(!c[e])continue;let n={b:e};for(let r=0;r<t.length;r++)l[r][e]!==1/0&&(n[`y${r}lo`]=l[r][e],n[`y${r}hi`]=u[r][e]);d.push(n)}return{x0:r,bucket:o,rows:d,columns:n}}var ae=O(new WeakMap);function oe(e){let t=ae.get(e);if(t===void 0){t=!0;for(let n=0;n<e.length;n++)if(!(e[n]>=(n>0?e[n-1]:-1/0))){t=!1;break}ae.set(e,t)}return t}function se(e,t,n,r,i,a){let o=t=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;t(e[i])?n=i+1:r=i}return n},s=o(e=>e<n),c=o(e=>e<=r),l=e=>Math.min(a-1,Math.floor((e-n)/i)),u=t.map((e,t)=>`y${t}lo`),d=t.map((e,t)=>`y${t}hi`),f=[],p=s;for(;p<c;){let n=l(e[p]),r=p,i=1;for(;p+i<c&&l(e[p+i])===n;)r=p+i,i*=2;let a=r+1,o=Math.min(p+i,c);for(;a<o;){let t=a+o>>>1;l(e[t])===n?a=t+1:o=t}let s=a,m={b:n};for(let e=0;e<t.length;e++){let n=t[e],r=1/0,i=-1/0;for(let e=p;e<s;e++){let t=n[e];t<r&&(r=t),t>i&&(i=t)}r!==1/0&&(m[u[e]]=r,m[d[e]]=i)}f.push(m),p=s}return f}function ce(e,t,n,r,i){let a=(r-n)/i,o=new Map;for(let s=0;s<e.length;s++){let c=e[s],l=t[s];if(c<n||c>r||Number.isNaN(l))continue;let u=Math.floor((c-n)/a);u===i&&(u=i-1);let d=o.get(u);d?(l<d.min&&(d.min=l),l>d.max&&(d.max=l),c<d.firstX&&(d.firstX=c,d.firstY=l),c>d.lastX&&(d.lastX=c,d.lastY=l)):(d={min:l,max:l,firstX:c,firstY:l,lastX:c,lastY:l},o.set(u,d))}let s=[...o.keys()].sort((e,t)=>e-t),c=s.length,l={x:new Float64Array(c),min:new Float64Array(c),max:new Float64Array(c),first:new Float64Array(c),last:new Float64Array(c)};for(let e=0;e<c;e++){let t=s[e],r=o.get(t);l.x[e]=n+(t+.5)*a,l.min[e]=r.min,l.max[e]=r.max,l.first[e]=r.firstY,l.last[e]=r.lastY}return l}function le(e,t,n,r,i,a){if(!oe(e))return null;let o=t=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;t(e[i])?n=i+1:r=i}return n},s=o(e=>e<r),c=o(e=>e<=i);if(c-s>a)return null;let l=e=>s===0&&c===e.length?e:e.subarray(s,c);return{length:c-s,x:l(e),cols:new Map(n.map((e,n)=>[e,l(t[n])]))}}var ue=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);function de(e,t,n=!0){let r=e.getUint32(n?t:t+4,n);return e.getUint32(n?t+4:t,n)*4294967296+r}function fe(e,t,n=!0){let r=e.getUint32(n?t:t+4,n);return e.getInt32(n?t+4:t,n)*4294967296+r}var pe=new TextDecoder(`utf-8`),me=new TextDecoder(`latin1`);function he(e,t=!1){let n=e.indexOf(0);return(t?me:pe).decode(n<0?e:e.subarray(0,n))}var ge=e=>me.decode(e),_e=e=>pe.decode(e);function k(e,t,n=0){if(e.length<n+t.length)return!1;for(let r=0;r<t.length;r++)if(e[n+r]!==t.charCodeAt(r))return!1;return!0}var ve={id:`mdf`,label:`ASAM MDF (MF4, MDF 3)`,extensions:[`.mf4`,`.mdf`,`.mf3`,`.dat`],companions:[{ext:`.dbc`,anyName:!0}],sniff:e=>k(e,`MDF `)||k(e,`UnFinMF `)},ye={id:`edf`,label:`EDF / BDF (+)`,extensions:[`.edf`,`.bdf`,`.rec`],sniff:e=>k(e,`0 `)||e[0]===255&&k(e,`BIOSEMI`,1)},be={id:`xdf`,label:`XDF (Lab Streaming Layer)`,extensions:[`.xdf`],sniff:e=>k(e,`XDF:`)},xe={id:`tdms`,label:`NI TDMS`,extensions:[`.tdms`],companions:[{ext:`.tdms_index`}],sniff:e=>k(e,`TDSm`)},Se={id:`mat`,label:`MATLAB MAT (v5, v7.3)`,extensions:[`.mat`],sniff:e=>k(e,`MATLAB 5.0 MAT-file`)||k(e,`MATLAB 7.3 MAT-file`)},Ce=`‰HDF\r
8
- 
9
- `,we={id:`hdf5`,label:`HDF5`,extensions:[`.h5`,`.hdf5`,`.hdf`,`.he5`,`.nc`],sniff:e=>[0,512,1024,2048].some(t=>k(e,Ce,t))},Te={id:`comtrade`,label:`COMTRADE (IEEE C37.111)`,extensions:[`.cfg`,`.cff`],companions:[{ext:`.dat`}],sniff:e=>{let t=ge(e.subarray(0,512));if(/^---\s*file type:\s*CFG/i.test(t))return!0;let n=t.split(/\r?\n/);return n.length>2&&/^\s*\d+\s*,\s*\d+A\s*,\s*\d+D\s*$/i.test(n[1])}},Ee=`This file couldn't be read (it may be damaged).`,De=1032,Oe=e=>e*De+1024,ke=128e6,A=256,Ae=64,je=1e3,j=100,Me=200,M=(e,t)=>e.length>t?`${e.slice(0,t-1)}…`:e;function Ne(e){let t=e.notes;for(let n of e.groups){n.name=M(String(n.name),A);for(let e of n.channels)e.name=M(String(e.name),A),e.unit=M(String(e.unit??``),Ae);Number.isInteger(n.samples)&&n.samples>=-1||(n.samples=-1),n.rateHz===null||Number.isFinite(n.rateHz)&&n.rateHz>0||(n.rateHz=null),n.time.kind===`rate`&&!(Number.isFinite(n.time.rate)&&n.time.rate>0&&Number.isFinite(n.time.start))&&(t.push(`${n.name}: its sample rate in the file is not usable; samples are numbered instead.`),n.time={kind:`index`},n.rateHz=null)}t.length>j&&t.splice(j,t.length-j,`${t.length-j} more notes.`),e.notes=t.map(e=>M(String(e),je));let n={};for(let[t,r]of Object.entries(e.meta).slice(0,Me))n[M(t,A)]=M(String(r),je);return e.meta=n,e.events=e.events.filter(e=>Number.isFinite(e.time)).map(e=>({time:e.time,text:M(String(e.text),je)})),e}function Pe(e){return e instanceof Error&&(e.constructor===Error||e.name===`KymoscopeError`||e.name===`AbortError`)?e:Error(Ee)}function Fe(e,t=[`Time`]){let n=new Set(t.map(e=>e.toLowerCase())),r=new Map;return e.map(e=>{let t=e.trim()||`Channel`,i=t.toLowerCase(),a=t,o=r.get(i)??2;if(n.has(i)){for(;n.has(`${i} (${o})`);)o++;a=`${t} (${o++})`}return r.set(i,o),n.add(a.toLowerCase()),a})}var N=1<<20,Ie=64,Le=16<<20,Re=class{size;bytesRead=0;#e;#t=new Map;constructor(e){this.#e=e,this.size=e.size}async read(e,t){let n=Math.min(this.size,e+t);if(n<=e)return new Uint8Array;if(n-e>N)return this.slice(e,n-e);let r=Math.floor(e/N),i=Math.floor((n-1)/N),a=await this.#n(r);if(r===i)return a.subarray(e-r*N,n-r*N);let o=new Uint8Array(n-e),s=a.subarray(e-r*N);return o.set(s),o.set((await this.#n(i)).subarray(0,n-i*N),s.length),o}async slice(e,t){let n=Math.min(this.size,e+t);if(n<=e)return new Uint8Array;let r=new Uint8Array(await this.#e.slice(e,n).arrayBuffer());return this.bytesRead+=r.length,r}async*windows(e,t,n=Le){let r=Math.min(this.size,e+t);for(let t=e;t<r;t+=n)yield{offset:t,bytes:await this.slice(t,Math.min(n,r-t))}}async#n(e){let t=this.#t.get(e);if(t)return this.#t.delete(e),this.#t.set(e,t),t;let n=await this.slice(e*N,N);return this.#t.size>=Ie&&this.#t.delete(this.#t.keys().next().value),this.#t.set(e,n),n}},ze=`kymoscope-live-key-check-v1`,P=6e5;function F(){let e=globalThis.crypto;if(!e?.subtle)throw Error(`WebCrypto SubtleCrypto is not available`);return e.subtle}function I(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function L(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function R(e){return I(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Be(e){return L(e.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function Ve(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function He(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),I(e)}async function z(e,t){let n=new TextEncoder,r=await F().importKey(`raw`,n.encode(e),`PBKDF2`,!1,[`deriveKey`]);return F().deriveKey({name:`PBKDF2`,salt:L(t),iterations:P,hash:`SHA-256`},r,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function Ue(e,t){let n=await F().importKey(`raw`,new TextEncoder().encode(e),`PBKDF2`,!1,[`deriveBits`]),r=await F().deriveBits({name:`PBKDF2`,salt:L(t),iterations:P,hash:`SHA-256`},n,256);return I(new Uint8Array(r))}async function We(e,t){let n=new Uint8Array(12);globalThis.crypto.getRandomValues(n);let r=new TextEncoder().encode(JSON.stringify(t)),i=await F().encrypt({name:`AES-GCM`,iv:n},e,r);return{iv:I(n),ciphertext:I(new Uint8Array(i))}}async function Ge(e,t){let n=L(t.iv),r=L(t.ciphertext),i=await F().decrypt({name:`AES-GCM`,iv:n},e,r);return new Uint8Array(i)}async function Ke(e,t,n,r){let i=await F().decrypt({name:`AES-GCM`,iv:t,additionalData:r},e,n);return new Uint8Array(i)}async function qe(e,t){return JSON.parse(new TextDecoder().decode(await Ge(e,t)))}async function Je(e){return We(e,ze)}async function Ye(e,t){try{return await qe(e,t)===ze}catch{return!1}}async function Xe(e){let t=await F().digest(`SHA-256`,new TextEncoder().encode(e));return Ve(new Uint8Array(t))}function Ze(){let e=e=>{let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),R(t)},t=`kymoscope_${e(24)}.${e(32)}`;return{token:t,prefix:t.slice(0,12)}}var Qe=/^((?:kymoscope|prism)_[A-Za-z0-9_-]+)(?:\.([A-Za-z0-9_-]+))?$/;function $e(e){let t=Qe.exec(e.trim());return t?{auth:t[1],secret:t[2]??null}:{auth:e,secret:null}}var et=new TextEncoder().encode(`kymoscope-device-wrap-v1`);async function tt(){let e=await F().generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveBits`]),t=new Uint8Array(await F().exportKey(`raw`,e.publicKey));return{privateKey:e.privateKey,publicKey:I(t)}}async function nt(e,t){let n=new Uint8Array(e.length+et.length);return n.set(e),n.set(et,e.length),F().importKey(`raw`,await F().digest(`SHA-256`,n),`AES-GCM`,!1,t)}async function rt(e,t,n){let r=await F().importKey(`raw`,L(t.epk),{name:`ECDH`,namedCurve:`P-256`},!1,[]),i=new Uint8Array(await F().deriveBits({name:`ECDH`,public:r},e,256));return new Uint8Array(await F().decrypt({name:`AES-GCM`,iv:L(t.iv),additionalData:new TextEncoder().encode(n)},await nt(i,[`decrypt`]),L(t.ct)))}function it(e,t,n){return at(e,t,n)}async function at(e,t,n,r,i){let a=await F().importKey(`raw`,L(e),{name:`ECDH`,namedCurve:`P-256`},!1,[]),o=r??await F().generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveBits`]),s=new Uint8Array(await F().deriveBits({name:`ECDH`,public:a},o.privateKey,256)),c=i??globalThis.crypto.getRandomValues(new Uint8Array(12)),l=new Uint8Array(await F().encrypt({name:`AES-GCM`,iv:c,additionalData:new TextEncoder().encode(n)},await nt(s,[`encrypt`]),t));return{epk:I(new Uint8Array(await F().exportKey(`raw`,o.publicKey))),iv:I(c),ct:I(l)}}async function ot(e,t,n,r){return ft(await rt(e,t,`${n}|${r}`))}var st=new TextEncoder().encode(`kymoscope-sender-bind-v1`),ct=(e,t,n)=>`project:${e}:${t}|${n}`,lt=(e,t,n)=>`live_stream:${e}|${t}:${n}`,ut=(e,t,n)=>`bind:${e}|${t}:${n}`;function dt(){return globalThis.crypto.getRandomValues(new Uint8Array(32))}function ft(e){return F().importKey(`raw`,e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}function pt(e,t,n){return mt(e,t,n)}async function mt(e,t,n,r){let i=r??globalThis.crypto.getRandomValues(new Uint8Array(12)),a=await F().importKey(`raw`,e,`AES-GCM`,!1,[`encrypt`]),o=new Uint8Array(await F().encrypt({name:`AES-GCM`,iv:i,additionalData:new TextEncoder().encode(n)},a,t));return{iv:I(i),ct:I(o)}}async function ht(e,t,n){let r=await F().importKey(`raw`,e,`AES-GCM`,!1,[`decrypt`]);return new Uint8Array(await F().decrypt({name:`AES-GCM`,iv:L(t.iv),additionalData:new TextEncoder().encode(n)},r,L(t.ct)))}async function gt(e){let t=new TextEncoder().encode(e),n=new Uint8Array(t.length+st.length);return n.set(t),n.set(st,t.length),new Uint8Array(await F().digest(`SHA-256`,n))}async function _t(e,t,n){let r=await F().importKey(`raw`,e,{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return I(new Uint8Array(await F().sign(`HMAC`,r,new TextEncoder().encode(`sender|${t}|${n}`))))}async function vt(e,t,n,r){let i;try{i=L(r)}catch{return!1}let a=await F().importKey(`raw`,e,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);return F().verify(`HMAC`,a,i,new TextEncoder().encode(`sender|${t}|${n}`))}async function yt(e){let t=Ve(new Uint8Array(await F().digest(`SHA-256`,L(e)))).slice(0,16).toUpperCase();return`${t.slice(0,4)}-${t.slice(4,8)}-${t.slice(8,12)}-${t.slice(12,16)}`}var bt=`kymoscope-workbook-export-v2`,xt=(e,t)=>`workbook:${e}:${t}`,St=(e,t,n)=>`workbook:${e}|${t}:${n}`,Ct=(e,t)=>`kymoscope-recovery-key-v1|${e}|${t}`,wt=(e,t,n)=>`recovery:${e}|${t}:${n}`;function Tt(e,t,n){return Et(e,t,n)}async function Et(e,t,n,r){let i=r??globalThis.crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await F().encrypt({name:`AES-GCM`,iv:i,additionalData:new TextEncoder().encode(n)},e,t));return{iv:I(i),ct:I(a)}}async function Dt(e,t,n){return new Uint8Array(await F().decrypt({name:`AES-GCM`,iv:L(t.iv),additionalData:new TextEncoder().encode(n)},e,L(t.ct)))}function Ot(e,t,n){return kt(e,t,n)}async function kt(e,t,n,r,i){let a=I(r??globalThis.crypto.getRandomValues(new Uint8Array(16))),o=await Et(await z(e,a),t,n,i);return{kdf:{name:`PBKDF2`,hash:`SHA-256`,iterations:P,salt:a},...o}}async function At(e,t,n){let r=t?.kdf;if(r?.name!==`PBKDF2`||r.hash!==`SHA-256`||r.iterations!==P||typeof r.salt!=`string`)throw Error(`unsupported_kdf`);return Dt(await z(e,r.salt),t,n)}var B=`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`;function jt(e){let t=0,n=0,r=``;for(let i of e)for(n=(n<<8|i)&1048575,t+=8;t>=5;)r+=B[n>>>t-5&31],t-=5;return t>0&&(r+=B[n<<5-t&31]),r.match(/.{1,4}/g).join(`-`)}function Mt(e){let t=e.toUpperCase().replace(/[^A-Z2-7]/g,``);if(t.length!==52)return null;let n=[],r=0,i=0;for(let e of t)i=(i<<5|B.indexOf(e))&4095,r+=5,r>=8&&(n.push(i>>>r-8&255),r-=8);return n.length===32?new Uint8Array(n):null}async function Nt(){let e=await F().generateKey({name:`ECDH`,namedCurve:`P-256`},!0,[`deriveBits`]),t=await F().exportKey(`jwk`,e.privateKey),n=new Uint8Array(await F().exportKey(`raw`,e.publicKey));return{d:Be(t.d),publicKey:I(n)}}function Pt(e,t){let n=L(t);return F().importKey(`jwk`,{kty:`EC`,crv:`P-256`,ext:!1,x:R(n.subarray(1,33)),y:R(n.subarray(33,65)),d:R(e)},{name:`ECDH`,namedCurve:`P-256`},!1,[`deriveBits`])}var Ft=O(new WeakSet),It={length:0,x:new Float64Array,cols:new Map};function V(e,t,n,r){let i=t.length,a=t.map((e,t)=>`y${t}lo`),o=t.map((e,t)=>`y${t}hi`),s=new Uint8Array(e.length),c=0;for(let t=0;t<e.length;t++){let n=e[t];for(let e=0;e<i;e++){let r=n[o[e]];if(r!=null&&Number(r)!==Number(n[a[e]])){s[t]=1;break}}c+=1+s[t]}let l=new Float64Array(c),u=t.map(()=>new Float64Array(c).fill(NaN)),d,f=0,p=null;for(let t=0;t<e.length;t++){let m=e[t],h=n+(Number(m.b)+.5)*r,g=Number(m.pass??0);p!==null&&g!==p&&((d??=new Uint8Array(c))[f]=1),p=g,l[f]=h;for(let e=0;e<i;e++){let t=m[a[e]];t!=null&&(u[e][f]=Number(t))}if(f++,s[t]){l[f]=h;for(let e=0;e<i;e++){let t=m[o[e]];t!=null&&(u[e][f]=Number(t))}f++}}return{length:c,x:l,brk:d,cols:new Map(t.map((e,t)=>[e,u[t]]))}}function Lt(e,t){if(t>=e.length)return e;let n=new Map;for(let[r,i]of e.cols)n.set(r,i.subarray(0,t));return{length:t,x:e.x.subarray(0,t),brk:e.brk?.subarray(0,t),cols:n}}function Rt(e,t){if(t===void 0||e.length===0||e.x[e.length-1]<=t)return e;let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e.x[i]<=t?n=i+1:r=i}return Lt(e,n)}function zt(e,t,n){let r=(t,n)=>{let r=0,i=e.length;for(;r<i;){let a=r+i>>1;(n?e.x[a]<=t:e.x[a]<t)?r=a+1:i=a}return r},i=r(t,!1),a=r(n,!0);if(i===0&&a===e.length)return e;let o=new Map;for(let[t,n]of e.cols)o.set(t,n.subarray(i,a));return{length:a-i,x:e.x.subarray(i,a),brk:e.brk?.subarray(i,a),cols:o}}function Bt(e,t){let n=[];for(let r=0;r<e.length;r++)t(e.x[r])&&n.push(r);if(n.length===e.length)return e;let r=(e,t)=>{for(let r=0;r<n.length;r++)t[r]=e[n[r]];return t},i=new Map;for(let[t,a]of e.cols)i.set(t,r(a,new Float64Array(n.length)));return{length:n.length,x:r(e.x,new Float64Array(n.length)),brk:e.brk&&r(e.brk,new Uint8Array(n.length)),cols:i}}function Vt(e,t,i,a,o=``,s=0){let c=n(e),l=E(e.length,a),u=t=>{let n=c&&r(c,t);return n?e=>n[e]:n=>{let r=e[n][t];return typeof r==`number`?r:NaN}},d=u(t),f=[];for(let e of l)Number.isNaN(d(e))||f.push(e);let p=f.length,m=p===e.length&&s===0,h=c&&r(c,t),g=m&&h?h:Float64Array.from(f,e=>d(e)+s),_=new Map;for(let e of i){let t=c&&r(c,e);if(c&&!t)continue;if(m&&t){_.set(e+o,t);continue}let n=u(e),i=Float64Array.from(f,n);!t&&!i.some(e=>!Number.isNaN(e))||_.set(e+o,i)}return{length:p,x:g,cols:_}}function Ht(e,t,n){if(!t&&n===0)return e;let r=e.x;if(n!==0){r=new Float64Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.x[t]+n}let i=new Map;for(let[n,r]of e.cols)i.set(n+t,r);return{length:e.length,x:r,brk:e.brk,cols:i}}function Ut(e){let t=e.filter(e=>e.length>0);if(t.length===0)return It;if(t.length===1)return t[0];let n=t.reduce((e,t)=>e+t.length,0),r=new Float64Array(n),i=new Set;for(let e of t)for(let t of e.cols.keys())i.add(t);let a=new Map;for(let e of i)a.set(e,new Float64Array(n).fill(NaN));let o,s=0;for(let e of t){r.set(e.x,s),e.brk&&(o??=new Uint8Array(n)).set(e.brk,s);for(let[t,n]of e.cols)a.get(t).set(n,s);s+=e.length}return{length:n,x:r,brk:o,cols:a}}var H=64,U=class{nc;bucket;b;lo;hi;start=0;end=0;rowP;px=new Float64Array;pv=[];pStart=0;pEnd=0;mStart=0;mEnd=0;dirty=1/0;dirtyFront=-1;invalid=!0;constructor(e,t,n=1024){this.nc=e,this.bucket=t,this.b=new Float64Array(n),this.rowP=new Float64Array(n),this.lo=Array.from({length:e},()=>new Float64Array(n)),this.hi=Array.from({length:e},()=>new Float64Array(n))}get count(){return this.end-this.start}lowerBound(e){let t=this.start,n=this.end;for(;t<n;){let r=t+n>>>1;this.b[r]<e?t=r+1:n=r}return t}relocate(e,t){let n=this.count,r=n=>{if(t===n.length&&e<=this.start)return n.copyWithin(e,this.start,this.end),n;let r=new Float64Array(t);return r.set(n.subarray(this.start,this.end),e),r};this.b=r(this.b),this.rowP=r(this.rowP),this.lo=this.lo.map(r),this.hi=this.hi.map(r);let i=e-this.start;this.mStart+=i,this.mEnd+=i,this.dirty!==1/0&&(this.dirty+=i),this.dirtyFront>=0&&(this.dirtyFront+=i),this.start=e,this.end=e+n}touch(e){e===this.start&&e+1<this.mEnd?this.dirtyFront=e:e<this.dirty&&(this.dirty=e)}clearRow(e){for(let t=0;t<this.nc;t++)this.lo[t][e]=NaN,this.hi[t][e]=NaN;this.touch(e)}row(e){let t=this.end;if(t>this.start&&this.b[t-1]===e)return t-1;if(t===this.start||e>this.b[t-1])return t===this.b.length&&(this.start>this.count?this.relocate(0,this.b.length):this.relocate(0,Math.max(1024,this.b.length*2))),this.b[this.end]=e,this.clearRow(this.end),this.end++;let n=this.lowerBound(e);if(this.b[n]===e)return n;if(n!==this.start)throw Error(`TimeBuckets: insert inside the rows`);if(this.start===0){let e=Math.max(1024,this.count);this.relocate(e,2*e+this.count)}return this.start--,this.b[this.start]=e,this.clearRow(this.start),this.invalid=!0,this.start}dropBelow(e){this.start=this.lowerBound(e),this.start===this.end&&(this.start=this.end=0,this.invalid=!0)}reset(e){this.clearRow(e)}fold(e,t,n,r){this.touch(e);for(let i=0;i<t.length;i++){let a=t[i],o=1/0,s=-1/0;for(let e=n;e<r;e++){let t=a[e];t<o&&(o=t),t>s&&(s=t)}if(o===1/0)continue;let c=this.lo[i],l=this.hi[i],u=c[e],d=l[e];c[e]=u<=o?u:o,l[e]=d>=s?d:s}}toRows(e,t,n,r,i){let a=[];for(let o=e;o<t;o++){let e={...n,b:this.b[o],pass:0};for(let t=0;t<this.nc;t++){let n=this.lo[t][o];n===n&&(e[r[t]]=n,e[i[t]]=this.hi[t][o])}a.push(e)}return a}pointsOf(e){for(let t=0;t<this.nc;t++){let n=this.hi[t][e];if(n===n&&n!==this.lo[t][e])return 2}return 1}writeRow(e,t,n){let r=(this.b[e]+.5)*this.bucket;this.px[t]=r;for(let n=0;n<this.nc;n++)this.pv[n][t]=this.lo[n][e];if(n===2){this.px[t+1]=r;for(let n=0;n<this.nc;n++)this.pv[n][t+1]=this.hi[n][e]}}reserve(e){if(this.pEnd+e<=this.px.length)return;let t=this.pEnd-this.pStart,n=H-this.pStart,r=2*(t+e+H)<=this.px.length,i=r?this.px.length:Math.max(4096,2*(t+e+H)),a=e=>{if(r)return e.copyWithin(H,this.pStart,this.pEnd),e;let t=new Float64Array(i);return t.set(e.subarray(this.pStart,this.pEnd),H),t};this.px=a(this.px),this.pv=this.pv.map(a);for(let e=this.mStart;e<this.mEnd;e++)this.rowP[e]+=n;this.pStart=H,this.pEnd=H+t}writeFrom(e){this.mEnd=e;for(let t=e;t<this.end;t++){let e=this.pointsOf(t);this.reserve(e),this.rowP[t]=this.pEnd,this.writeRow(t,this.pEnd,e),this.pEnd+=e,this.mEnd=t+1}}sync(){if(this.pv.length!==this.nc&&(this.pv=Array.from({length:this.nc},()=>new Float64Array)),this.invalid||this.start<this.mStart||this.start>=this.mEnd)this.pStart=this.pEnd=H,this.mStart=this.mEnd=this.start,this.reserve(0),this.writeFrom(this.start);else{this.start>this.mStart&&(this.mStart=this.start,this.pStart=this.rowP[this.start]);let e=Math.max(this.start,Math.min(this.dirty,this.mEnd)),t=this.dirtyFront;if(t===this.start)if(t+1<e){let e=this.pointsOf(t),n=this.rowP[t+1]-e;if(n<0)return this.invalid=!0,this.sync();this.rowP[t]=n,this.pStart=n,this.writeRow(t,n,e)}else e=t;e<this.end&&(e<this.mEnd&&(this.pEnd=this.rowP[e]),this.writeFrom(e))}this.dirty=1/0,this.dirtyFront=-1,this.invalid=!1}toPoints(e,t,n){this.sync();let r=e<t?this.rowP[e]:0,i=e<t?t<this.mEnd?this.rowP[t]:this.pEnd:0;return{length:i-r,x:this.px.subarray(r,i),cols:new Map(n.map((e,t)=>[e,this.pv[t].subarray(r,i)]))}}};function Wt(e){if(!(e>0)||!Number.isFinite(e))return e;let t=10**Math.floor(Math.log10(e)),n=e/t;return(n<1.5?1:n<3.5?2:n<7.5?5:10)*t}function Gt(e,t,n,r,i){if(n instanceof Float64Array||n instanceof Float32Array)e.set(n.subarray(r,r+i),t);else for(let a=0;a<i;a++)e[t+a]=+n[r+a]}function Kt(e,t){let n=e.t.length,r=Object.keys(e.columns).filter(e=>e!==t);for(let t of r)if(e.columns[t].length!==n)throw RangeError(`live column "${t}" has ${e.columns[t].length} values for ${n} times`);return r}var qt=`ElapsedTime`,Jt=[];function Yt(e){let t=Jt[e];if(!t){let n=Array.from({length:e},(e,t)=>`y${t}lo`),r=Array.from({length:e},(e,t)=>`y${t}hi`);t={lo:n,hi:r,row:JSON.parse(JSON.stringify(Object.fromEntries([[`b`,0],[`pass`,0],...n.flatMap((e,t)=>[[e,null],[r[t],null]])])))},Jt[e]=t}return t}var Xt=4096,Zt=4,Qt=class{time;alloc;maxBytes;cols=new Map;head=0;count=0;full=!1;pushed=0;clears=0;signalOrder=[];unitByName=new Map;capacity;timeColumn;timeUnit;lastBackAbs=-1;get timeMonotonic(){return this.lastBackAbs<=this.pushed-this.size}lastPushT=-1/0;decCache=null;prevCyclePts=null;curCyclePts=null;trackers=new Map;debugLastScan=0;timeDec=null;mirrors=new Map;historyDec=null;constructor(e,t=qt,n=`s`,r=1/0){this.capacity=Math.max(2,Math.floor(e)),this.timeColumn=t,this.timeUnit=n,this.maxBytes=r,this.alloc=Math.min(this.capacity,Xt),this.time=new Float64Array(this.alloc)}get maxSamples(){return this.capacity}newColumn(){return new Float64Array(this.alloc).fill(NaN)}grow(){let e=Math.min(this.capacity,this.alloc*2);if(e*8*(1+this.cols.size)>this.maxBytes){this.capacity=this.alloc;return}let t=t=>{let n=new Float64Array(e);return n.set(t),n};this.time=t(this.time);for(let[e,n]of this.cols)this.cols.set(e,t(n));this.alloc=e}get version(){return this.pushed+this.clears}get size(){return this.full?this.capacity:this.count}push(e){for(let[t,n]of this.trackers){let r=t===this.timeColumn?e.t:e.signals.find(e=>e.name===t)?.value;r!==void 0&&Number.isFinite(r)&&this.advanceCycle(t,n,r,this.pushed)}e.t<this.lastPushT&&this.steppedBack(this.pushed),this.lastPushT=e.t,!this.full&&this.count===this.alloc&&(this.grow(),this.count===this.capacity&&(this.full=!0));let t=this.full?this.head:this.count;this.time[t]=e.t;for(let e of this.signalOrder)this.cols.get(e)[t]=NaN;for(let n of e.signals){if(this.computed.has(n.name))continue;let e=this.cols.get(n.name);e?n.unit&&n.unit!==this.unitByName.get(n.name)&&(this.unitByName.get(n.name)&&this.dropColumnSamples(n.name,e),this.unitByName.set(n.name,n.unit)):(e=this.newColumn(),this.cols.set(n.name,e),this.signalOrder.push(n.name),this.unitByName.set(n.name,n.unit??``)),e[t]=n.value}this.pushed++,this.full?this.head=(this.head+1)%this.capacity:(this.count++,this.count===this.capacity&&(this.full=!0))}pushColumns(e){let t=e.t,n=t.length,r=Kt(e,this.timeColumn);if(n===0)return;if(this.trackers.size>0){for(let i=0;i<n;i++)this.push({t:t[i],signals:r.map(t=>({name:t,unit:e.units?.[t],value:e.columns[t][i]}))});return}for(let t of r){if(this.computed.has(t))continue;let n=e.units?.[t],r=this.cols.get(t);r?n&&n!==this.unitByName.get(t)&&(this.unitByName.get(t)&&this.dropColumnSamples(t,r),this.unitByName.set(t,n)):(this.cols.set(t,this.newColumn()),this.signalOrder.push(t),this.unitByName.set(t,n??``))}for(let e=0;e<n;e++){let n=+t[e];n<this.lastPushT&&this.steppedBack(this.pushed+e),this.lastPushT=n}let i=Math.max(0,n-this.capacity);for(this.pushed+=i;i<n;){!this.full&&this.count===this.alloc&&(this.grow(),this.count===this.capacity&&(this.full=!0));let r=this.full?this.head:this.count,a=Math.min(n-i,this.full?this.capacity-this.head:this.alloc-this.count);Gt(this.time,r,t,i,a);for(let t of this.signalOrder){let n=this.cols.get(t),o=this.computed.has(t)?void 0:e.columns[t];o?Gt(n,r,o,i,a):n.fill(NaN,r,r+a)}this.pushed+=a,i+=a,this.full?this.head=(this.head+a)%this.capacity:(this.count+=a,this.count===this.capacity&&(this.full=!0))}}steppedBack(e){this.lastBackAbs=e,this.timeDec=null}dropColumnSamples(e,t){t.fill(NaN),this.decCache=null,this.timeDec=null;for(let t of this.trackers.values())t.previous?.cols.delete(e);this.clears++}clear(){this.clears++,this.head=0,this.count=0,this.full=!1,this.pushed=0,this.cols.clear(),this.computed.clear(),this.signalOrder.length=0,this.unitByName.clear(),this.decCache=null,this.timeDec=null,this.lastBackAbs=-1,this.lastPushT=-1/0,this.trackers.clear()}columnArray(e){return e===this.timeColumn?this.time:this.cols.get(e)}physOf(e){let t=e-(this.pushed-this.size);return this.full?(this.head+t)%this.capacity:t}copyRange(e,t,n,r=[this.timeColumn,...this.signalOrder]){let i=Math.max(t,this.pushed-this.size),a=Math.max(0,n-i),o=this.columnArray(e),s=new Float64Array(a),c=new Map;for(let e of r)this.columnArray(e)&&c.set(e,new Float64Array(a));for(let e=0;e<a;e++){let t=this.physOf(i+e);s[e]=o?o[t]:NaN;for(let[n,r]of c)r[e]=this.columnArray(n)[t]}return{x:s,cols:c}}advanceCycle(e,t,n,r){Number.isFinite(t.lastX)&&n<t.lastX&&t.lastX-n>(t.hi-t.lo)/2?(t.previous=this.copyRange(e,t.start,r),t.start=r,t.lo=t.hi=n):Number.isFinite(t.lastX)?(n<t.lo&&(t.lo=n),n>t.hi&&(t.hi=n)):t.lo=t.hi=n,n<t.allLo&&(t.allLo=n),n>t.allHi&&(t.allHi=n),t.lastX=n}trackCycles(e){if(this.trackers.has(e))return;let t={start:this.pushed-this.size,lo:0,hi:0,lastX:NaN,allLo:1/0,allHi:-1/0,previous:null},n=this.columnArray(e),r=this.pushed-this.size;if(n)for(let i=r;i<this.pushed;i++){let r=n[this.physOf(i)];Number.isFinite(r)&&this.advanceCycle(e,t,r,i)}this.trackers.set(e,t)}cycleSpan(e){let t=this.trackers.get(e);return t&&t.allHi>t.allLo?[t.allLo,t.allHi]:null}decimateCycle(e,t,n,r,i,a){let o=this.trackers.get(e),s=n.filter(e=>this.cols.has(e));if(!o)return{x0:r,bucket:0,rows:[],columns:s};let c=t===`previous`?o.previous:this.copyRange(e,o.start,this.pushed,s);if(!c)return{x0:r,bucket:0,rows:[],columns:s};let l=s.map(e=>c.cols.get(e)??new Float64Array(c.x.length).fill(NaN));return ie(c.x,l,s,r,i,a)}decimateCyclePoints(e,t,n,r,i,a){let o=()=>{let o=this.decimateCycle(e,t,n,r,i,a);return V(o.rows,o.columns,o.x0,o.bucket)},s=this.trackers.get(e),c=Math.floor(a),l=this.columnArray(e);if(!s||!l||!(i>r)||c<1)return o();let u=n.filter(e=>this.cols.has(e)),d=u.join(` `);if(t===`previous`){let e=this.prevCyclePts;if(e&&e.snap===s.previous&&e.x0===r&&e.x1===i&&e.mp===a&&e.colsKey===d)return e.pts;let t=o();return this.prevCyclePts={snap:s.previous,x0:r,x1:i,mp:a,colsKey:d,pts:t},t}if(s.start<this.pushed-this.size)return o();let f=this.curCyclePts;if((!f||f.key!==e||f.start!==s.start||f.x0!==r||f.x1!==i||f.mp!==a||f.colsKey!==d||f.clears!==this.clears)&&(f=this.curCyclePts={key:e,start:s.start,x0:r,x1:i,mp:a,colsKey:d,clears:this.clears,done:s.start,pts:null,seen:new Uint8Array(c),lo:u.map(()=>new Float64Array(c).fill(1/0)),hi:u.map(()=>new Float64Array(c).fill(-1/0))}),f.pts&&f.done===this.pushed)return f.pts;let p=(i-r)/a,m=u.map(e=>this.columnArray(e));for(let e=f.done;e<this.pushed;e++){let t=this.physOf(e),n=l[t];if(!(n>=r&&n<=i))continue;let a=Math.floor((n-r)/p);a>=c&&(a=c-1),f.seen[a]=1;for(let e=0;e<m.length;e++){let n=m[e][t];n===n&&(n<f.lo[e][a]&&(f.lo[e][a]=n),n>f.hi[e][a]&&(f.hi[e][a]=n))}}f.done=this.pushed;let h=0,g=new Uint8Array(c);for(let e=0;e<c;e++)if(f.seen[e]){for(let t=0;t<m.length;t++){let n=f.hi[t][e];if(n!==-1/0&&n!==f.lo[t][e]){g[e]=1;break}}h+=1+g[e]}let _=new Float64Array(h),v=u.map(()=>new Float64Array(h)),y=0;for(let e=0;e<c;e++){if(!f.seen[e])continue;let t=r+(e+.5)*p;_[y]=t;for(let t=0;t<m.length;t++){let n=f.lo[t][e];v[t][y]=n===1/0?NaN:n}if(y++,g[e]){_[y]=t;for(let t=0;t<m.length;t++){let n=f.hi[t][e];v[t][y]=n===-1/0?NaN:n}y++}}return f.pts={length:h,x:_,cols:new Map(u.map((e,t)=>[e,v[t]]))},f.pts}computed=new Set;get firstAbs(){return this.pushed-this.size}get endAbs(){return this.pushed}range(e,t,n){let r=Math.max(t,this.firstAbs),i=new Float64Array(Math.max(0,Math.min(n,this.pushed)-r)),a=this.columnArray(e);if(!a)return i.fill(NaN);for(let e=0;e<i.length;e++)i[e]=a[this.physOf(r+e)];return i}mirrorColumn(e){let t=this.columnArray(e);if(!t)return;let n=this.firstAbs,r=this.pushed,i=this.mirrors.get(e);if((!i||i.clears!==this.clears)&&(i={arr:new Float64Array(Math.max(16,r-n)),first:n,end:n,clears:this.clears,view:null},this.mirrors.set(e,i)),i.first===n&&i.end===r&&i.view)return i.view;if(n>i.first){let e=Math.max(0,i.end-n);e>0&&i.arr.copyWithin(0,n-i.first,i.end-i.first),i.first=n,i.end=n+e}if(i.arr.length<r-n){let e=new Float64Array(Math.max(r-n,i.arr.length*2));e.set(i.arr.subarray(0,i.end-i.first)),i.arr=e}for(let e=i.end;e<r;){let a=this.physOf(e),o=Math.min(r-e,(this.full?this.capacity:this.alloc)-a);i.arr.set(t.subarray(a,a+o),e-n),e+=o}return i.end=r,i.view=i.arr.subarray(0,r-n),i.view}writeComputed(e,t,n,r){let i=this.mirrors.get(e);i&&n<i.end&&(i.end=Math.max(i.first,n),i.view=null);let a=this.cols.get(e);(!a||!this.computed.has(e))&&(a||(a=this.newColumn(),this.cols.set(e,a),this.signalOrder.push(e)),this.computed.add(e)),this.unitByName.set(e,t);for(let e=0;e<r.length;e++){let t=n+e;t<this.firstAbs||t>=this.pushed||(a[this.physOf(t)]=r[e]??NaN)}}clearComputed(){for(let e of this.computed){this.cols.delete(e),this.unitByName.delete(e);for(let t of this.trackers.values())t.previous?.cols.delete(e)}this.signalOrder.splice(0,this.signalOrder.length,...this.signalOrder.filter(e=>!this.computed.has(e))),this.computed.clear(),this.decCache=null,this.timeDec=null,this.clears++}get columnNames(){return[this.timeColumn,...this.signalOrder]}unitOf(e){return e===this.timeColumn?this.timeUnit:this.unitByName.get(e)??``}columnValues(e){let t=this.size,n=new Float64Array(t),r=e===this.timeColumn?this.time:this.cols.get(e);if(!r)return n.fill(NaN),n;for(let e=0;e<t;e++)n[e]=r[this.full?(this.head+e)%this.capacity:e];return n}accumulate(e,t,n,r,i,a=0){let o=Yt(i.length),s=n[t];if(Number.isNaN(s))return;let c=Math.floor(s/r),l=e.get(c);(!l||l.pass<a)&&(l={...o.row,b:c,pass:a},e.set(c,l));for(let e=0;e<i.length;e++){let n=i[e][t];if(Number.isNaN(n))continue;let r=o.lo[e],a=o.hi[e],s=l[r],c=l[a];l[r]=s==null?n:Math.min(s,n),l[a]=c==null?n:Math.max(c,n)}}decimateColumns(e,t,n,r,i){if(e===this.timeColumn&&this.timeMonotonic)return this.decimateTime(t,n,r,i);let a=e===this.timeColumn?this.time:this.cols.get(e),o=a?t.filter(e=>this.cols.has(e)):[],s=(r-n)/i,c=this.size;if(c>1&&e===this.timeColumn&&this.timeMonotonic&&a){let e=a[this.full?this.head:0],t=(a[this.full?(this.head+c-1)%this.capacity:c-1]-e)/(c-1);t>0&&t<s&&(s=.7*Math.max(t,(r-n)/(i*Zt)))}let l=Wt(s);{let t=this.decCache;t&&t.xKey===e&&t.colsKey===o.join(` `)&&t.bucket>0&&s>=t.bucket*.5&&s<=t.bucket*2&&(l=t.bucket)}if(!a||o.length===0||!(r>n)||!(l>0))return{x0:n,bucket:0,rows:[],columns:o};let u=o.map(e=>this.cols.get(e)),d=this.size,f=o.join(`\0`);this.debugLastScan=0;let p=this.decCache,m=p!==null&&e===this.timeColumn&&this.timeMonotonic&&p.xKey===e&&p.colsKey===f&&p.bucket===l&&this.pushed>=p.pushed&&this.pushed-p.pushed<d&&p.map.size<this.capacity*2,h=p!==null&&p.xKey===e&&p.colsKey===f&&p.bucket===l&&p.pushed===this.pushed,g;if(h&&p)g=p.map;else if(m&&p){g=p.map;let e=this.pushed-p.pushed;for(let t=d-e;t<d;t++){let e=this.full?(this.head+t)%this.capacity:t;this.debugLastScan++,this.accumulate(g,e,a,l,u)}if(this.full&&d>0){let e=a[this.head];if(!Number.isNaN(e)){let t=Math.floor(e/l);for(let e=p.lowB;e<t;e++)g.delete(e);g.delete(t);for(let e=0;e<d;e++){let n=(this.head+e)%this.capacity,r=a[n];if(!Number.isNaN(r)){if(Math.floor(r/l)>t)break;this.debugLastScan++,this.accumulate(g,n,a,l,u)}}p.lowB=t}}p.pushed=this.pushed}else{g=new Map;let t=1/0,n=1/0;if(e!==this.timeColumn||!this.timeMonotonic){let{x0:t,x1:r}=this.columnBounds(e);r>t&&(n=(r-t)/2)}let r=0,i=NaN;for(let e=0;e<d;e++){let o=this.full?(this.head+e)%this.capacity:e,s=a[o];if(Number.isNaN(s))continue;s<i-n&&r++,i=s,this.debugLastScan++,this.accumulate(g,o,a,l,u,r);let c=Math.floor(s/l);c<t&&(t=c)}if(r>0)for(let[e,t]of g)(t.pass??0)<r&&g.delete(e);this.decCache={xKey:e,colsKey:f,cols:o,bucket:l,map:g,pushed:this.pushed,lowB:Number.isFinite(t)?t:0}}let _=Math.floor(n/l),v=Math.floor(r/l),y=[];for(let e of g.values()){let t=e.b;t>=_&&t<=v&&y.push(e)}return y.sort((e,t)=>Number(e.b)-Number(t.b)),{x0:0,bucket:l,rows:y,columns:o}}timeIndex(e){let t=0,n=this.size;for(;t<n;){let r=t+n>>>1;this.time[this.full?(this.head+r)%this.capacity:r]<e?t=r+1:n=r}return t}foldBuckets(e,t,n,r,i){this.eachBucketRun(t,n,r,(t,n,r)=>e.fold(e.row(t),i,n,r))}eachBucketRun(e,t,n,r){if(t<=e)return;this.debugLastScan+=t-e;let i=this.time,a=e=>Math.floor(i[e]/n),o=(e,t)=>{let n=e;for(;n<t;){let e=a(n),i=n,o=1;for(;n+o<t&&a(n+o)===e;)i=n+o,o*=2;let s=i+1,c=Math.min(n+o,t);for(;s<c;){let t=s+c>>>1;a(t)===e?s=t+1:c=t}r(e,n,s),n=s}};if(!this.full)return o(e,t);let s=(this.head+e)%this.capacity,c=s+(t-e);if(c<=this.capacity)return o(s,c);o(s,this.capacity),o(0,c-this.capacity)}decimateTime(e,t,n,r){let i=this.timeBuckets(e,t,n,r);if(!i.store)return{x0:t,bucket:0,rows:[],columns:i.cols};let a=Yt(i.cols.length),o=()=>i.store.toRows(i.i0,i.i1,a.row,a.lo,a.hi),s=this.historyDec;return{x0:0,bucket:i.bucket,rows:s?.store===i.store?s.rows??=o():o(),columns:i.cols}}decimatePoints(e,t,n,r,i){if(e===this.timeColumn&&this.timeMonotonic){let e=this.timeBuckets(t,n,r,i);return e.store?e.store.toPoints(e.i0,e.i1,e.cols):{length:0,x:new Float64Array,cols:new Map(e.cols.map(e=>[e,new Float64Array]))}}let a=this.decimateColumns(e,t,n,r,i);return V(a.rows,a.columns,a.x0,a.bucket)}timeBuckets(e,t,n,r){let i=e.filter(e=>this.cols.has(e)),a=this.size,o={cols:i,bucket:0,store:null,i0:0,i1:0};if(i.length===0||!(n>t)||a===0)return o;let s=e=>this.full?(this.head+e)%this.capacity:e,c=this.time[s(0)],l=this.time[s(a-1)],u=(n-t)/r;if(a>1){let e=(l-c)/(a-1);e>0&&e<u&&(u=.7*Math.max(e,(n-t)/(r*Zt)))}let d=Wt(u),f=i.join(` `),p=this.timeDec;if(p&&p.colsKey===f&&u>=p.bucket*.5&&u<=p.bucket*2&&(d=p.bucket),!(d>0))return o;let m=i.map(e=>this.cols.get(e)),h=Math.floor(t/d),g=Math.floor(n/d);this.debugLastScan=0;let _=e=>({cols:i,bucket:d,store:e,i0:e.lowerBound(h),i1:e.lowerBound(g+1)});if(n<l-(n-t)){let e=this.timeIndex(h*d),t=this.timeIndex((g+1)*d),n=this.pushed-a,r=`${f}|${d}|${h}|${g}|${n+e}|${n+t}|${this.clears}`;if(this.historyDec?.key!==r){let n=new U(i.length,d);this.foldBuckets(n,e,t,d,m),this.historyDec={key:r,store:n}}return _(this.historyDec.store)}let v=p?this.pushed-p.pushed:0;if(p&&p.colsKey===f&&p.bucket===d&&v>=0&&v<a){let e=p.store;if(h<p.fromB){let t=new U(i.length,d);this.foldBuckets(t,this.timeIndex(h*d),this.timeIndex(p.fromB*d),d,m);for(let n=t.end-1;n>=t.start;n--){let r=e.row(t.b[n]);for(let i=0;i<t.nc;i++)e.lo[i][r]=t.lo[i][n],e.hi[i][r]=t.hi[i][n]}p.fromB=h}v>0&&this.foldBuckets(e,a-v,a,d,m);let t=Math.floor(c/d);return this.full&&t>=p.fromB&&(e.dropBelow(t),e.reset(e.row(t)),this.foldBuckets(e,0,this.timeIndex((t+1)*d),d,m),p.fromB=t),h>p.fromB&&(e.dropBelow(h),p.fromB=h),p.pushed=this.pushed,_(e)}let y=new U(i.length,d),b=this.timeIndex(h*d);return this.foldBuckets(y,b,a,d,m),this.timeDec={colsKey:f,bucket:d,store:y,pushed:this.pushed,fromB:b===0?Math.floor(c/d):h},_(y)}lastValue(e){let t=e===this.timeColumn?this.time:this.cols.get(e);return!t||this.size===0?NaN:t[this.full?(this.head-1+this.capacity)%this.capacity:this.count-1]}xTravel(e,t){let n=this.columnArray(e),r=this.size;if(!n||r<2)return NaN;let i=e=>this.full?(this.head+e)%this.capacity:e,a=this.time[i(r-1)],o=0,s=NaN,c=a;for(let e=r-1;e>=0;e--){let r=i(e),l=this.time[r];if(l<a-t)break;let u=n[r];Number.isNaN(u)||(s>u&&(o+=s-u),s=u,c=l)}let l=a-c;return l>0&&l<t?o*t/l:o}latestTime(){return this.lastValue(this.timeColumn)}xAtTime(e,t){let n=this.columnArray(e),r=this.size;if(!n||r===0||!this.timeMonotonic)return NaN;let i=e=>this.full?(this.head+e)%this.capacity:e,a=0,o=r-1;if(t<=this.time[i(0)])return n[i(0)];if(t>=this.time[i(o)])return n[i(o)];for(;o-a>1;){let e=a+o>>1;this.time[i(e)]<=t?a=e:o=e}let s=i(a),c=i(o),l=n[s],u=n[c];if(!(u>=l))return l;let d=this.time[s],f=this.time[c];return f>d?l+(u-l)*(t-d)/(f-d):l}boundsCache=new Map;columnBounds(e){let t=e===this.timeColumn?this.time:this.cols.get(e),n=this.size;if(!t||n===0)return{x0:0,x1:0};if(t===this.time&&this.timeMonotonic)return{x0:this.time[this.full?this.head:0],x1:this.time[this.full?(this.head+n-1)%this.capacity:n-1]};let r=this.boundsCache.get(e);if(r&&r.version===this.version)return r.b;let i=this.scanBounds(t,n);return this.boundsCache.set(e,{version:this.version,b:i}),i}scanBounds(e,t){let n=1/0,r=-1/0;for(let i=0;i<t;i++){let t=e[this.full?(this.head+i)%this.capacity:i];Number.isNaN(t)||(t<n&&(n=t),t>r&&(r=t))}return Number.isFinite(n)?{x0:n,x1:r}:{x0:0,x1:0}}toDataset(e){let t=[this.timeColumn,...this.signalOrder],n=[this.timeUnit,...this.signalOrder.map(e=>this.unitByName.get(e)??``)],r=this.size,i=e&&e>0&&r>e?Math.ceil(r/e):1,a=e=>{let t=this.full?(this.head+e)%this.capacity:e,n={[this.timeColumn]:this.time[t]};for(let e of this.signalOrder){let r=this.cols.get(e)[t];n[e]=Number.isNaN(r)?null:r}return n},o=this.pushed-r,s=i>1?(i-o%i)%i:0,c=[];for(let e=s;e<r;e+=i)c.push(a(e));return r>0&&(c.length===0||(r-1-s)%i!=0)&&c.push(a(r-1)),{meta:``,columnNames:t,units:n,rows:c}}};new TextEncoder;var $t=4096;function en(e,t,n){let r=t,i=r+n,a=[],o=``;for(;r<i;){let t=e[r++];if(!(t&128))a.push(t);else if((t&224)==192){let n=e[r++]&63;a.push((t&31)<<6|n)}else if((t&240)==224){let n=e[r++]&63,i=e[r++]&63;a.push((t&31)<<12|n<<6|i)}else if((t&248)==240){let n=e[r++]&63,i=e[r++]&63,o=e[r++]&63,s=(t&7)<<18|n<<12|i<<6|o;s>65535&&(s-=65536,a.push(s>>>10&1023|55296),s=56320|s&1023),a.push(s)}else a.push(t);a.length>=$t&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}var tn=new TextDecoder,nn=200;function rn(e,t,n){let r=e.subarray(t,t+n);return tn.decode(r)}function an(e,t,n){return n>nn?rn(e,t,n):en(e,t,n)}var W=class{type;data;constructor(e,t){this.type=e,this.data=t}},G=class e extends Error{constructor(t){super(t);let n=Object.create(e.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,`name`,{configurable:!0,enumerable:!1,value:e.name})}};function on(e,t,n){let r=Math.floor(n/4294967296),i=n;e.setUint32(t,r),e.setUint32(t+4,i)}function sn(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}function cn(e,t){let n=e.getUint32(t),r=e.getUint32(t+4);return n*4294967296+r}var ln=4294967295,un=17179869183;function dn({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=un)if(t===0&&e<=ln){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}else{let n=e/4294967296,r=e&4294967295,i=new Uint8Array(8),a=new DataView(i.buffer);return a.setUint32(0,t<<2|n&3),a.setUint32(4,r),i}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,t),on(r,4,e),n}}function fn(e){let t=e.getTime(),n=Math.floor(t/1e3),r=(t-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function pn(e){return e instanceof Date?dn(fn(e)):null}function mn(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{let e=t.getUint32(0),n=t.getUint32(4);return{sec:(e&3)*4294967296+n,nsec:e>>>2}}case 12:return{sec:sn(t,4),nsec:t.getUint32(0)};default:throw new G(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function hn(e){let t=mn(e);return new Date(t.sec*1e3+t.nsec/1e6)}var gn={type:-1,encode:pn,decode:hn},_n=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(gn)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{let r=-1-e;this.builtInEncoders[r]=t,this.builtInDecoders[r]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){let r=this.builtInEncoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new W(-1-n,i)}}for(let n=0;n<this.encoders.length;n++){let r=this.encoders[n];if(r!=null){let i=r(e,t);if(i!=null)return new W(n,i)}}return e instanceof W?e:null}decode(e,t,n){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,n):new W(t,e)}};function vn(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}function yn(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):vn(e)?new Uint8Array(e):Uint8Array.from(e)}function K(e){return`${e<0?`-`:``}0x${Math.abs(e).toString(16).padStart(2,`0`)}`}var bn=16,xn=16,Sn=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=bn,t=xn){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){let r=this.caches[n-1];FIND_CHUNK:for(let i of r){let r=i.bytes;for(let i=0;i<n;i++)if(r[i]!==e[t+i])continue FIND_CHUNK;return i.str}return null}store(e,t){let n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)}decode(e,t,n){let r=this.find(e,t,n);if(r!=null)return this.hit++,r;this.miss++;let i=en(e,t,n),a=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(a,i),i}},q=`array`,J=`map_key`,Cn=`map_value`,wn=e=>{if(typeof e==`string`||typeof e==`number`)return e;throw new G(`The type of key must be string or number but `+typeof e)},Tn=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=q,t.position=0,t.size=e,t.array=Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=J,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){return this.stackHeadPosition++,this.stackHeadPosition===this.stack.length&&this.stack.push({type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null}),this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw Error(`Invalid stack state. Released state is not on top of the stack.`);if(e.type===q){let t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===J||e.type===Cn){let 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}},Y=-1,X=new DataView(new ArrayBuffer(0)),En=new Uint8Array(X.buffer);try{X.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw Error(`This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access`)}var Dn=RangeError(`Insufficient data`),On=new Sn,kn=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=X;bytes=En;headByte=Y;stack=new Tn;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??_n.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder===void 0?On:e.keyDecoder,this.mapKeyConverter=e?.mapKeyConverter??wn}clone(){return new e({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=Y,this.stack.reset()}setBuffer(e){let t=yn(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Y&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),n=yn(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:n}=this;return RangeError(`Extra ${t.byteLength-n} 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);let 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,n;for await(let r of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(r);try{n=this.doDecodeSync(),t=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}let{headByte:r,pos:i,totalPos:a}=this;throw RangeError(`Insufficient data in parsing ${K(r)} at ${a} (${i} 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 n=t,r=-1;for await(let i of e){if(t&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(r=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--r!==0;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){DECODE:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue DECODE}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue DECODE}else t=[]}else{let 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)t=this.useBigInt64?this.readU64AsBigInt():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)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(e===217){let e=this.lookU8();t=this.decodeString(e,1)}else if(e===218){let e=this.lookU16();t=this.decodeString(e,2)}else if(e===219){let e=this.lookU32();t=this.decodeString(e,4)}else if(e===220){let e=this.readU16();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===221){let e=this.readU32();if(e!==0){this.pushArrayState(e),this.complete();continue DECODE}else t=[]}else if(e===222){let e=this.readU16();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===223){let e=this.readU32();if(e!==0){this.pushMapState(e),this.complete();continue DECODE}else t={}}else if(e===196){let e=this.lookU8();t=this.decodeBinary(e,1)}else if(e===197){let e=this.lookU16();t=this.decodeBinary(e,2)}else if(e===198){let e=this.lookU32();t=this.decodeBinary(e,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){let e=this.lookU8();t=this.decodeExtension(e,1)}else if(e===200){let e=this.lookU16();t=this.decodeExtension(e,2)}else if(e===201){let e=this.lookU32();t=this.decodeExtension(e,4)}else throw new G(`Unrecognized type byte: ${K(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let e=n.top();if(e.type===q)if(e.array[e.position]=t,e.position++,e.position===e.size)t=e.array,n.release(e);else continue DECODE;else if(e.type===J){if(t===`__proto__`)throw new G(`The key __proto__ is not allowed`);e.key=this.mapKeyConverter(t),e.type=Cn;continue DECODE}else if(e.map[e.key]=t,e.readCount++,e.readCount===e.size)t=e.map,n.release(e);else{e.key=null,e.type=J;continue DECODE}}return t}}readHeadByte(){return this.headByte===Y&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Y}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new G(`Unrecognized array type byte: ${K(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new G(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new G(`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){if(e>this.maxStrLength)throw new G(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Dn;let n=this.pos+t,r;return r=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,n,e):an(this.bytes,n,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===J:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new G(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Dn;let n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r}decodeExtension(e,t){if(e>this.maxExtLength)throw new G(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=cn(this.view,this.pos);return this.pos+=8,e}readI64(){let e=sn(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function An(e,t){return new kn(t).decode(e)}var Z=12,jn=16;function Mn(e){let t=new Uint8Array(e),n=t.length>0&&t[0]&128?2:1;return t.length<n+Z+jn?null:{kind:t[0]&-129,keyId:n===2?t[1]:null,iv:t.subarray(n,n+Z),ciphertext:t.subarray(n+Z),aad:t.subarray(0,n)}}async function Nn(e,t){let n=Mn(t);if(!n)return null;let r=typeof e==`function`?await e(n.keyId):e;if(!r)return null;let i=await Ke(r,n.iv,n.ciphertext,n.aad);return{kind:n.kind,plaintext:i}}function Pn(e,t,n,r){return Fn(e,t,n,r)}async function Fn(e,t,n,r,i){let a=r===void 0?new Uint8Array([t]):new Uint8Array([t|128,r&255]),o=i??globalThis.crypto.getRandomValues(new Uint8Array(Z)),s=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:`AES-GCM`,iv:o,additionalData:a},e,n)),c=new Uint8Array(a.length+Z+s.length);return c.set(a),c.set(o,a.length),c.set(s,a.length+Z),c.buffer}var In=1,Q=e=>e+7&-8;function Ln(e){let t=e=>RangeError(`columns message: ${e}`);e.byteOffset%8!=0&&(e=e.slice());let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<8)throw t(`short`);if(n.getUint8(0)!==In)throw t(`version ${n.getUint8(0)}`);let r=n.getUint16(2,!0),i=n.getUint32(4,!0),a=new TextDecoder,o=[],s=8;for(let i=0;i<r;i++){if(s+3>e.byteLength)throw t(`short channel table`);let r=n.getUint8(s),i=n.getUint8(s+1),c=n.getUint8(s+2);if(s+=3,r!==4&&r!==8)throw t(`value size ${r}`);if(s+i+c>e.byteLength)throw t(`short channel table`);o.push({name:a.decode(e.subarray(s,s+i)),unit:a.decode(e.subarray(s+i,s+i+c)),size:r}),s+=i+c}if(s=Q(s),s+Q(i*8)+o.reduce((e,t)=>e+Q(i*t.size),0)>e.byteLength)throw t(`short data`);let c=e.byteOffset,l=new Float64Array(e.buffer,c+s,i);s+=Q(i*8);let u={},d={};for(let t of o)u[t.name]=t.size===4?new Float32Array(e.buffer,c+s,i):new Float64Array(e.buffer,c+s,i),t.unit&&(d[t.name]=t.unit),s+=Q(i*t.size);return{t:l,columns:u,units:d}}var Rn=(e,t,n)=>`recording_key:${e}|${t}:${n}`,zn=(e,t,n)=>n===e.stream_epoch?lt(e.stream_id,t,n):Rn(e.id,t,n),$=12,Bn=16;function Vn(e){let t=new Map;return async n=>{if(n.length===0)return null;let r=n[0]&128?2:1;if(n.length<r+$+Bn)return null;let i=r===2?n[1]:null,a=t.get(i),o=[...a?[a]:[],...e.filter(e=>e.keyId===i&&e.key!==a).map(e=>e.key)];for(let e of o)try{let a=await Ke(e,n.subarray(r,r+$),n.subarray(r+$),n.subarray(0,r));return t.set(i,e),{kind:n[0]&-129,plaintext:a}}catch{}return null}}var Hn=56,Un=[75,82,67,49];function Wn(e){let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Gn(e){if(e.length<56||Un.some((t,n)=>e[n]!==t))throw RangeError(`not a KRC1 chunk`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint16(4,!0);if(n!==1)throw RangeError(`KRC version ${n}`);let r=t.getUint16(6,!0);if(r<56)throw RangeError(`KRC header too short`);return{recordingId:Wn(e.subarray(8,24)),seq:t.getUint32(24,!0),count:t.getUint32(28,!0),bytes:t.getUint32(32,!0),headerBytes:r,t0:t.getFloat64(40,!0),t1:t.getFloat64(48,!0)}}function Kn(e){let t=Gn(e),n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Math.min(e.length,t.bytes),i=[],a=t.headerBytes;for(;i.length<t.count&&a+12<=r;){let t=n.getUint32(a+8,!0);if(a+12+t>r)break;i.push({at:n.getFloat64(a,!0),bytes:e.subarray(a+12,a+12+t)}),a+=12+t}return{header:t,messages:i,truncated:i.length<t.count}}export{ot as $,Nt as A,O as At,dt as B,y as Bt,bt as C,k as Ct,yt as D,ce as Dt,Ue as E,ue as Et,ht as F,m as Ft,pt as G,jt as H,r as Ht,Dt as I,_ as It,gt as J,Tt as K,At as L,v as Lt,Xe as M,ne as Mt,ft as N,l as Nt,Ze as O,ie as Ot,Je as P,u as Pt,rt as Q,Mt as R,h as Rt,Vt as S,fe as St,z as T,_e as Tt,Ct as U,n as Ut,wt as V,E as Vt,Pt as W,a as Wt,$e as X,_t as Y,lt as Z,Ut as _,be as _t,Rn as a,Re as at,V as b,ge as bt,Nn as c,Ee as ct,qt as d,Pe as dt,Ye as et,Qt as f,Oe as ft,Rt as g,xe as gt,zt as h,Se as ht,Vn as i,it,He as j,re as jt,tt as k,le as kt,Pn as l,ke as lt,It as m,we as mt,Kn as n,xt as nt,zn as o,Le as ot,Kt as p,Te as pt,Ot as q,Gn as r,St as rt,Ln as s,Fe as st,Hn as t,vt as tt,An as u,Ne as ut,Bt as v,ye as vt,ut as w,de as wt,Ht as x,he as xt,Ft as y,ve as yt,ct as z,b as zt};