@kymoscope/sdk 0.16.0 → 0.18.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.
Files changed (37) hide show
  1. package/dist/assets/{importer.worker-BblHvxro.js → importer.worker-BEjFe0TV.js} +4 -4
  2. package/dist/assets/liveIngestWorker-MA_RO8uZ.js +1 -0
  3. package/dist/importers-4ETLHzYe.js +5 -0
  4. package/dist/keys-CbPoU_jx.js +11 -0
  5. package/dist/kymoscope-embed.js +69 -69
  6. package/dist/kymoscope-sdk.js +84 -84
  7. package/dist/types/analysis/capability.d.ts +1 -1
  8. package/dist/types/analysis/context.d.ts +2 -2
  9. package/dist/types/analysis/control.d.ts +1 -1
  10. package/dist/types/analysis/energy.d.ts +1 -1
  11. package/dist/types/analysis/infer.d.ts +1 -1
  12. package/dist/types/analysis/known.d.ts +1 -1
  13. package/dist/types/analysis/lines.d.ts +1 -1
  14. package/dist/types/analysis/losses.d.ts +1 -1
  15. package/dist/types/analysis/oee.d.ts +1 -1
  16. package/dist/types/analysis/presets.d.ts +2 -2
  17. package/dist/types/analysis/ranges.d.ts +1 -1
  18. package/dist/types/analysis/report.d.ts +1 -1
  19. package/dist/types/analysis/review.d.ts +1 -1
  20. package/dist/types/analysis/text.d.ts +1 -1
  21. package/dist/types/analysis/types.d.ts +5 -5
  22. package/dist/types/charts/ChartBody.d.ts +6 -1
  23. package/dist/types/components/SpectrogramChart.d.ts +24 -1
  24. package/dist/types/lib/data/liveDataSource.d.ts +14 -0
  25. package/dist/types/lib/importers/types.d.ts +2 -0
  26. package/dist/types/lib/live/blockWire.d.ts +17 -7
  27. package/dist/types/lib/live/buffer.d.ts +14 -1
  28. package/dist/types/lib/live/liveIngest.d.ts +16 -0
  29. package/dist/types/lib/live/sparseFeed.d.ts +39 -0
  30. package/dist/types/lib/live/sparseStore.d.ts +18 -0
  31. package/dist/types/lib/live/wire.d.ts +2 -0
  32. package/dist/types/lib/render/heatGrid.d.ts +5 -0
  33. package/dist/types/lib/stft.d.ts +30 -0
  34. package/package.json +1 -1
  35. package/dist/assets/liveIngestWorker-UV5D515-.js +0 -1
  36. package/dist/importers-CLmQyVrb.js +0 -5
  37. package/dist/keys-B-nvFeb4.js +0 -11
@@ -3,7 +3,7 @@ import { type Classified, type Missing, type ReportInput, type SectionOut } from
3
3
  * context. Ppk = min(USL − mean, mean − LSL) / 3σ over the period's judged batches (σ: the overall sample standard
4
4
  * deviation, so Ppk, not Cpk). With no spread it is ±∞: capable when every batch is inside, not capable otherwise. */
5
5
  export declare const MIN_CPK_BATCHES = 30;
6
- /** Capable from this Ppk unless Process context sets another (`ppkMin`: 1.67 for PPAP). */
6
+ /** Capable from this Ppk unless Context sets another (`ppkMin`: 1.67 for PPAP). */
7
7
  export declare const CPK_OK = 1.33;
8
8
  /** Ppk is indicative: it assumes a normal distribution and a stable process, neither of which the report tests. */
9
9
  export declare const PPK_NOTE = "Ppk is indicative: it assumes the values are normally distributed and the process stable, which this report does not test.";
@@ -1,7 +1,7 @@
1
1
  import { type KnownFinding } from './known';
2
2
  import { type PresetId } from './presets';
3
3
  import { type SectionId } from './types';
4
- /** The project's Process context (spec 2026-11-10, delivery B): what a report needs that the data can't say — the
4
+ /** The project’s Context (spec 2026-11-10, delivery B): what a report needs that the data can't say — the
5
5
  * process in the customer's words (the AI's main context), each channel's role, unit, ranges and limits, the lines,
6
6
  * machine units, shifts and planned stops, the costs. Report settings (views, reviewer, approver, schedule) live in the plain `report_settings` row. Stored per project, one version per
7
7
  * save, sealed under the project config key in an end-to-end encrypted project. Plain JSON, the same shape in the
@@ -120,7 +120,7 @@ export interface ContextGap {
120
120
  needs: string;
121
121
  }
122
122
  export declare function contextGaps(ctx: ProcessContext | null, alertRules: number): ContextGap[];
123
- /** What would put money in the reports (the Process context tab's first line): each cost not set yet and what it shows.
123
+ /** What would put money in the reports (the project’s Context tab's first line): each cost not set yet and what it shows.
124
124
  * The scrap cost is asked for only once something says which batches are scrap (a specification limit). */
125
125
  export declare function moneyGaps(ctx: ProcessContext | null): Array<{
126
126
  add: string;
@@ -1,6 +1,6 @@
1
1
  import type { Part } from './parts';
2
2
  import type { Classified, ReportInput } from './types';
3
- /** 04.3 (2026-11-13): with no specification limits in Process context there is no capability to compute, so 04 looks
3
+ /** 04.3 (2026-11-13): with no specification limits in the project’s Context there is no capability to compute, so 04 looks
4
4
  * at the process's own voice instead: an individuals control chart (Shewhart) per stream of each level KPI (mean,
5
5
  * minimum, maximum, at start, at end) of the channels a batch is judged by. Centre line = the mean; σ from the average
6
6
  * moving range (MR̄ / 1.128), so a slow drift doesn't widen its own limits; limits = mean ± 3σ. A KPI is named only
@@ -1,5 +1,5 @@
1
1
  import { type Classified, type Missing, type ReportInput, type SectionOut } from './types';
2
- /** Section 09 (spec 2026-11-10): energy per batch from the Process context's energy channel (measured per batch by the
2
+ /** Section 09 (spec 2026-11-10): energy per batch from the project’s Context's energy channel (measured per batch by the
3
3
  * app: a power channel integrated over the batch, or an energy meter's change), against the period before when its
4
4
  * batches' energy is stored; its cost at the price per kWh (without one, kWh alone) and its CO₂ at the grid factor
5
5
  * (Scope 2, location-based, the factor the customer entered); and whether off-golden batches use more than the rest
@@ -1,6 +1,6 @@
1
1
  import { type PlannedStop, type ProcessContext, type Shift } from './context';
2
2
  import { type ChannelHealth } from './health';
3
- /** Fill from data (Process context, delivery B): what the project's recordings already say about the line — units,
3
+ /** Fill from data (Context, delivery B): what the project's recordings already say about the line — units,
4
4
  * expected ranges, the energy channel, shifts and planned stops, comparable lines and machine units — proposed from
5
5
  * compact summaries (times, channel declarations, stored sensor health), never from samples. Every value it returns is
6
6
  * a proposal: `applyInferred` puts it only where the context is empty and marks it suggested. */
@@ -1,6 +1,6 @@
1
1
  import type { ReportDoc } from './types';
2
2
  /** Findings a person said are not a problem (phase 6, 2026-11-19: learning from one click, no daily input). Each is kept
3
- * in the Process context with its finding's signature — its section and its words, numbers and dates left out, in
3
+ * in the project’s Context with its finding's signature — its section and its words, numbers and dates left out, in
4
4
  * the engine's own vocabulary — and the numbers it had then. A later report sets a finding with that signature aside
5
5
  * (listed under "Known", never deleted), with the actions that rest on it alone; it comes back when a number of it
6
6
  * grew past KNOWN_GROWTH times what it was when it was marked (a stuck sensor that is flat by design for 2 h is news
@@ -1,5 +1,5 @@
1
1
  import { type Classified, type ReportInput, type SectionOut } from './types';
2
- /** Section 10 (spec 2026-11-10): the lines named in Process context (each a set of this project's streams) side by
2
+ /** Section 10 (spec 2026-11-10): the lines named in the project’s Context (each a set of this project's streams) side by
3
3
  * side, each measured against its own streams' goldens: batches, the share at golden level or better and the share
4
4
  * better than the golden; a line that runs off-golden more (or less) often than the other lines (two-proportion
5
5
  * test, Benjamini–Hochberg at q = 0.01 across lines). */
@@ -27,7 +27,7 @@ export interface LossesIn {
27
27
  } | null;
28
28
  /** Batches to count as scrap: outside their specification limits or flagged bad (measured). `assumed`: nothing says
29
29
  * which batches are scrap, so the off-golden ones stand in (never when the value to compare is the cycle time: a slow
30
- * batch is not scrap). Valued at the Process context's cost of a scrapped batch. */
30
+ * batch is not scrap). Valued at the project’s Context's cost of a scrapped batch. */
31
31
  scrap?: {
32
32
  batches: number;
33
33
  assumed: boolean;
@@ -8,7 +8,7 @@ import { type Classified, type ReportInput, type SectionOut } from './types';
8
8
  * more). Performance = the ideal cycle × batches / the time not stopped (at most 1); the ideal cycle runs from one
9
9
  * batch's start to the next one's: the golden's cycle time plus the shortest wait between batches the line reaches again
10
10
  * and again (1 wait in 20), so the handling a machine needs between two strokes is no loss, and a wait longer than that
11
- * is. An ideal cycle time set in Process context replaces that one, for every stream. Quality = good batches / batches: not flagged bad and inside the specification limits; when the value to compare
11
+ * is. An ideal cycle time set in the project’s Context replaces that one, for every stream. Quality = good batches / batches: not flagged bad and inside the specification limits; when the value to compare
12
12
  * is not the cycle time and has no limits of its own, also at golden level or better (offGoldenIsBad).
13
13
  * What is lost, in hours of planned time (and money with the cost of an hour). */
14
14
  export declare const BLOCK_S = 900;
@@ -3,7 +3,7 @@ import type { ReportDoc, ReportInput, ReportRole, SectionId } from './types';
3
3
  * first, which start folded, who each section is for and the words a report uses. `applyPreset` runs after
4
4
  * `buildReport` and never touches a number: the same findings, ids, evidence and amounts, in another order and
5
5
  * vocabulary. "generic" is the report as it always was (applying it returns the document unchanged). None of the
6
- * signup industries (src/lib/industries.ts) is a regulated one, so "regulated" is only ever chosen in Process context. */
6
+ * signup industries (src/lib/industries.ts) is a regulated one, so "regulated" is only ever chosen in the project’s Context. */
7
7
  export declare const PRESET_IDS: readonly ["generic", "discrete", "process", "regulated", "motorsport", "lab"];
8
8
  export type PresetId = (typeof PRESET_IDS)[number];
9
9
  export interface Preset {
@@ -22,7 +22,7 @@ export interface Preset {
22
22
  }
23
23
  export declare const PRESETS: Record<PresetId, Preset>;
24
24
  export declare const presetOf: (id: unknown) => Preset;
25
- /** The preset a signup industry (src/lib/industries.ts) starts with; a project changes it in its Process context. */
25
+ /** The preset a signup industry (src/lib/industries.ts) starts with; a project changes it in its Context. */
26
26
  export declare const presetForIndustry: (industry: unknown) => PresetId;
27
27
  /** `text` in the preset's vocabulary: whole words and phrases, a capital kept ("Batches" → "Parts"); never inside a
28
28
  * longer name ("batch_temp", "Batch.id"). `keep`: names the customer chose (a stream "Batch reactor", a rule
@@ -1,6 +1,6 @@
1
1
  import type { Part } from './parts';
2
2
  import type { Classified, ReportInput } from './types';
3
- /** 05.7 (2026-11-18): the expected ranges set in Process context, read. A channel past its range in RANGE_MIN batches
3
+ /** 05.7 (2026-11-18): the expected ranges set in the project’s Context, read. A channel past its range in RANGE_MIN batches
4
4
  * in a row or more (its highest value over the top, or its lowest under the bottom), lasting RANGE_MIN_S or more, is
5
5
  * an episode: when, how far, and what the batches' value did meanwhile against the stream's other batches of those
6
6
  * days. Not an episode: a batch past its range alone (a stop inside a batch), a run chance alone would make (N·pⁿ ≥
@@ -1,7 +1,7 @@
1
1
  import { OWNER, SHOWN_ACTIONS, actionRow } from './actions';
2
2
  import { type Finding, type ReportDoc, type ReportInput, type ReportRole, type ReportSection } from './types';
3
3
  /** The production report (spec 2026-11-10, delivery D revised 2026-11-11): sections 00–14, each from the data and the
4
- * one-time Process context (those with their inputs), worded from fixed templates. Pure: the same input gives the same
4
+ * one-time Context (those with their inputs), worded from fixed templates. Pure: the same input gives the same
5
5
  * document. */
6
6
  export declare function buildReport(given: ReportInput): ReportDoc;
7
7
  /** The sections a role's view shows (the Full report: all). */
@@ -41,7 +41,7 @@ export interface ReviewPack {
41
41
  amount: string;
42
42
  detail: string;
43
43
  }>;
44
- /** What people said is not a problem, or known (the Process context's known findings): the AI weighs the rest with it. */
44
+ /** What people said is not a problem, or known (the project’s Context's known findings): the AI weighs the rest with it. */
45
45
  known: Array<{
46
46
  text: string;
47
47
  reason: string;
@@ -3,7 +3,7 @@ import { type Finding } from './types';
3
3
  export declare const pct: (x: number) => string;
4
4
  /** A percentage already in %: whole from 10 up, one decimal under it (4.13 → "4.1%", 20.4 → "20%"). */
5
5
  export declare const pct1: (p: number) => string;
6
- /** An amount in the Process context's currency: cents under 100, whole units above. */
6
+ /** An amount in the project’s Context's currency: cents under 100, whole units above. */
7
7
  export declare function money(x: number, currency: string): string;
8
8
  /** Numbers as a manager reads them, the report's one formatter: at most 3 significant figures (2 under 1: "0.37",
9
9
  * "0.012"), whole with thousands separators from 1,000 up ("33,392"). */
@@ -33,7 +33,7 @@ export interface CycleIn {
33
33
  flag: 'good' | 'bad' | 'excluded' | null;
34
34
  /** Per channel, its lowest and highest value in the batch (measured with the deviation): what a level alert would see. */
35
35
  range?: Record<string, [number, number]> | null;
36
- /** The batch's energy in kWh (09), measured with the Process context's energy channel. */
36
+ /** The batch's energy in kWh (09), measured with the project’s Context's energy channel. */
37
37
  kwh?: number | null;
38
38
  /** Seconds the batch spent in each phase of its rule (none: the rule has no phases). */
39
39
  phases?: Record<string, number>;
@@ -98,7 +98,7 @@ export interface ReportInput {
98
98
  t0: number;
99
99
  t1: number;
100
100
  }>;
101
- /** The project's Process context and its version (delivery B); null or absent: none set. */
101
+ /** The project’s Context and its version (delivery B); null or absent: none set. */
102
102
  context?: ProcessContext | null;
103
103
  contextVersion?: number | null;
104
104
  /** The project's enabled alert rules and the alerts they raised in the period's recordings (07). */
@@ -351,7 +351,7 @@ export interface ReportSection {
351
351
  }>;
352
352
  /** An industry preset starts this section as its verdict alone, the rest one press away (the PDF prints it whole). */
353
353
  collapsed?: true;
354
- /** What this section took from the data because nobody set it in Process context yet (shifts, planned stops…). */
354
+ /** What this section took from the data because nobody set it in the project’s Context yet (shifts, planned stops…). */
355
355
  assumed?: string[];
356
356
  }
357
357
  export interface SectionOut {
@@ -379,7 +379,7 @@ export interface ReportCover {
379
379
  madeBy: string;
380
380
  madeAt: number;
381
381
  tz: string;
382
- /** "Process context v3" (absent in reports made before delivery B); the AI model that wrote the text, if one did. */
382
+ /** "Context v3" (absent in reports made before delivery B); the AI model that wrote the text, if one did. */
383
383
  context?: string;
384
384
  ai?: string;
385
385
  }
@@ -397,7 +397,7 @@ export interface ReportDoc {
397
397
  }>;
398
398
  /** Kymoscope's AI review (review.ts): the model, the checks it asked for and their results (what was sent back),
399
399
  * and the findings it set aside or merged, each with its reason. Absent: no review. */
400
- /** Findings set aside because the Process context lists them as known (known.ts), each with the reason a person gave. */
400
+ /** Findings set aside because the project’s Context lists them as known (known.ts), each with the reason a person gave. */
401
401
  known?: Array<{
402
402
  id: string;
403
403
  section: string;
@@ -57,7 +57,12 @@ export interface ChartBodyProps {
57
57
  onContextMenu: (e: ContextMenuEvent) => void;
58
58
  xyzRef?: Ref<XYZMeshChartHandle>;
59
59
  }
60
- /** Every column a chart's settings pick (series, slots, lists); helper fields such as the multiband's add picker don't count. */
60
+ /**
61
+ * Whether a spectrogram reads its stream itself, every frame (SpectrogramLive): the flat view of one live stream
62
+ * shown alone (`loneLive`). The worksheet's data is still refreshed as samples arrive (its sample rate when it comes
63
+ * from a time column, and what `view.data()` returns); the picture no longer waits for that.
64
+ */
65
+ export declare function spectrogramPullsLive(settings: PanelChartSettings | undefined, loneLive: boolean): boolean;
61
66
  export declare function chosenColumns(settings: PanelChartSettings | undefined): string[];
62
67
  /** Renders the chart and reports whether it had anything to draw: an empty chart whose chosen
63
68
  * channels aren't all in this data says so ('missing'), the same for every kind. */
@@ -12,5 +12,28 @@ export interface SpectrogramChartProps {
12
12
  clientX: number;
13
13
  clientY: number;
14
14
  }) => void;
15
+ /**
16
+ * A live stream read every frame (no React at data rate): its raw samples, transformed as they arrive (only the
17
+ * new windows, see rollingSpectrogram) and scrolled with the smooth playout the live multiband uses, so the
18
+ * picture moves every frame instead of in a step per received message. `signal` is not read then.
19
+ */
20
+ live?: SpectrogramLive;
15
21
  }
16
- export declare function SpectrogramChart({ signal, sampleRate, windowSize, overlap, winFunc, yMode, logFreq, label, backgroundToken, onPlotContextMenu, }: SpectrogramChartProps): import("react/jsx-runtime").JSX.Element;
22
+ export interface SpectrogramLive {
23
+ /** Changes whenever samples arrive. */
24
+ version: () => number;
25
+ /** Every buffered sample of the signal, oldest first, and how many the stream had before them (see
26
+ * LiveDataSource.samplesSync). null: the stream has no such column. */
27
+ samples: () => {
28
+ values: Float64Array;
29
+ first: number;
30
+ } | null;
31
+ /** Time of the newest sample, and of the oldest after a time: the smooth playout (see advancePlayout). */
32
+ latestT: () => number;
33
+ timeAfter?: (t: number) => number;
34
+ /** The stream's id: its charts share one playout, so they show one instant. */
35
+ id?: string;
36
+ /** Seconds shown, ending now (the worksheet's live window); null: everything buffered. */
37
+ windowSeconds: number | null;
38
+ }
39
+ export declare function SpectrogramChart({ signal, sampleRate, windowSize, overlap, winFunc, yMode, logFreq, label, backgroundToken, onPlotContextMenu, live, }: SpectrogramChartProps): import("react/jsx-runtime").JSX.Element;
@@ -11,7 +11,12 @@ import type { PointColumns } from './pointColumns';
11
11
  */
12
12
  export declare class LiveDataSource implements DataSource {
13
13
  #private;
14
+ /** Called with the columns a read names, before it reads (a stream over 1,000 channels activates them: see
15
+ * sparseFeed.ts). */
16
+ onUse?: (columns: string[]) => void;
14
17
  constructor(buffer: LiveBuffer | (() => LiveBuffer));
18
+ /** Track again every key trackCycles was asked for: after the buffer was rebuilt (its clear() drops them). */
19
+ retrackCycles(): void;
15
20
  /** Current sample count of the underlying ring, read live (no allocation). Lets
16
21
  * a host's sample-count badge show the climbing count by polling itself, instead of the
17
22
  * count riding on the ~1 Hz `connections` state whose update re-renders the App. */
@@ -26,6 +31,15 @@ export declare class LiveDataSource implements DataSource {
26
31
  * LiveBuffer.mirrorColumn). A new map per call: the columns as they are now.
27
32
  */
28
33
  columns(): ReadonlyMap<string, Float64Array>;
34
+ /**
35
+ * Every buffered sample of `column`, oldest first (see LiveBuffer.mirrorColumn: a call copies only what arrived
36
+ * since the last), and how many samples the stream had before the first of them: an index that stays put while
37
+ * the ring drops its oldest. For charts that read the raw signal every frame (the live spectrogram).
38
+ */
39
+ samplesSync(column: string): {
40
+ values: Float64Array;
41
+ first: number;
42
+ } | null;
29
43
  /** Whether `column` has had a finite value (a column the snapshot rows may thin out of view). */
30
44
  hasValues(column: string): boolean;
31
45
  /** A fresh row snapshot of the newest samples (at most `maxRows`, evenly thinned). */
@@ -58,6 +58,8 @@ export interface ImportPlan {
58
58
  pick?: boolean;
59
59
  /** Groups read when nobody chooses (default: all). */
60
60
  defaultGroups?: number[];
61
+ /** Channels read when nobody chooses, when not every channel of `defaultGroups` (a recording over 1,000 channels). */
62
+ defaultSelection?: GroupSelection[];
61
63
  /**
62
64
  * The groups share one data stream (unsorted MF4, bus logging): read them in
63
65
  * one pass with `stream`, even when the importer has `streamGroup`.
@@ -14,8 +14,8 @@ export interface BlockSchema {
14
14
  id: number;
15
15
  channels: BlockChannel[];
16
16
  }
17
- /** The channel table of a decrypted KIND_BLOCK_SCHEMA plaintext. Throws RangeError if malformed. */
18
- export declare function decodeBlockSchema(p: Uint8Array): BlockSchema;
17
+ /** The channel table of a decrypted KIND_BLOCK_SCHEMA plaintext, version 2 or 3. Throws RangeError if malformed. */
18
+ export declare function decodeBlockSchema(p: Uint8Array): Promise<BlockSchema>;
19
19
  /** KIND_BLOCK_SCHEMA plaintext with a given id (tests and local publishers; senders use the CRC-32 of the table). */
20
20
  export declare function encodeBlockSchema(id: number, channels: BlockChannel[]): Uint8Array;
21
21
  /** One channel of a KIND_LAST_VALUES: its last finite value and that value's time (stream seconds). */
@@ -26,18 +26,28 @@ export interface LastValue {
26
26
  v: number;
27
27
  }
28
28
  /**
29
- * The channels with a value of a decrypted KIND_LAST_VALUES plaintext (u8 version 1, u8 flags, u16 reserved,
30
- * u32 schema id, u32 count, count f64 times then count f64 values, NaN time = none yet; little-endian), named by
31
- * the schema it refers to; null until that schema has arrived. Throws RangeError if malformed.
32
- * Normative format: docs/superpowers/specs/2026-10-26-last-values.md; pinned by tests/vectors/last-values-v1.json.
29
+ * The channels with a value of a decrypted KIND_LAST_VALUES plaintext, version 1 (above) or 2 (u8 version, u8 flags,
30
+ * u16 reserved, u32 schema id, u32 count, f64 reference time, optional u32 channel indexes, u32 ms before the
31
+ * reference per entry, byte-split values, optionally deflated). Null until its schema has arrived.
32
+ * Throws RangeError if malformed. Pinned by tests/vectors/capacity-v1.json.
33
33
  */
34
- export declare function decodeLastValues(p: Uint8Array, schemas: ReadonlyMap<number, BlockSchema>): LastValue[] | null;
34
+ export declare function decodeLastValues(p: Uint8Array, schemas: ReadonlyMap<number, BlockSchema>): Promise<LastValue[] | null>;
35
35
  /** KIND_LAST_VALUES plaintext of `t` / `v` in `schema`'s channel order, NaN for none (tests and local publishers). */
36
36
  export declare function encodeLastValues(schema: BlockSchema, t: ArrayLike<number>, v: ArrayLike<number>): Uint8Array;
37
37
  /** A decrypted KIND_BLOCK plaintext's rows; null until its schema has arrived. Throws RangeError if malformed. */
38
38
  export declare function decodeBlock(p: Uint8Array, schemas: ReadonlyMap<number, BlockSchema>): Promise<{
39
39
  block: LiveColumnsBlock;
40
40
  historical: boolean;
41
+ schemaId: number;
42
+ } | null>;
43
+ /** A decrypted KIND_SPARSE plaintext: event k is channel `index[k]` of the schema at `t[k]` with `v[k]`. Null until
44
+ * its schema has arrived. Throws RangeError if malformed. */
45
+ export declare function decodeSparse(p: Uint8Array, schemas: ReadonlyMap<number, BlockSchema>): Promise<{
46
+ schemaId: number;
47
+ index: Uint32Array;
48
+ t: Float64Array;
49
+ v: Float64Array;
50
+ historical: boolean;
41
51
  } | null>;
42
52
  /** KIND_BLOCK plaintext of `block` under `schema` (tests and local publishers). Little-endian hosts only. */
43
53
  export declare function encodeBlock(block: {
@@ -41,6 +41,8 @@ export declare class LiveBuffer {
41
41
  private pushed;
42
42
  /** Times the buffer was cleared (keeps `version` moving even though `pushed` resets). */
43
43
  private clears;
44
+ /** Rows pushed before the last clear, in all: `version` never goes back after a clear and fewer rows. */
45
+ private pushedBefore;
44
46
  private readonly signalOrder;
45
47
  private readonly unitByName;
46
48
  private capacity;
@@ -83,6 +85,9 @@ export declare class LiveBuffer {
83
85
  private snapDec;
84
86
  /** Each column's newest finite value and its time, kept past the ring (see lastKnown). */
85
87
  private latest;
88
+ /** Channels listed without a column (a stream over 1,000 channels: see sparseFeed.ts), name -> unit. A column per
89
+ * listed channel cost 32 KB each: 3.2 GB for 100k channels before a sample arrived. */
90
+ private readonly listed;
86
91
  /**
87
92
  * `capacity`: samples kept (the oldest are dropped past it). Memory grows with
88
93
  * the samples actually received; `maxBytes` caps it — once the columns would
@@ -114,7 +119,7 @@ export declare class LiveBuffer {
114
119
  * the size it has, the oldest samples dropped from here, instead of failing the push and losing its samples.
115
120
  */
116
121
  private refused;
117
- /** Samples ever pushed (and bumped by clear): a data version for consumers. */
122
+ /** Samples ever pushed (and bumped by clear): a data version for consumers, never repeated. */
118
123
  get version(): number;
119
124
  get size(): number;
120
125
  push(msg: LiveMessage): void;
@@ -187,6 +192,10 @@ export declare class LiveBuffer {
187
192
  clearComputed(): void;
188
193
  /** Column names in order: the time column first, then the signals. */
189
194
  get columnNames(): string[];
195
+ /** `columnNames.length` without building it (100k listed names on every ingest). */
196
+ get columnCount(): number;
197
+ /** Whether `name` is in `columnNames` (the time column, a column, or a listed channel). */
198
+ has(name: string): boolean;
190
199
  /** Unit string for a column (empty if unknown). */
191
200
  unitOf(name: string): string;
192
201
  /**
@@ -327,6 +336,8 @@ export declare class LiveBuffer {
327
336
  /** Whether `name` has had a finite value (a sample or a last known value) since the stream started (or was
328
337
  * cleared), in the ring or not. */
329
338
  hasValues(name: string): boolean;
339
+ /** The bytes the columns may take (the constructor's `maxBytes`). */
340
+ get memoryBudget(): number;
330
341
  /** How many columns have had a finite value (moves when one gets its first). */
331
342
  get valuedCount(): number;
332
343
  /** The newest finite value of `name` and its time (a sample, or a last known value when newer), past the ring. */
@@ -334,6 +345,8 @@ export declare class LiveBuffer {
334
345
  t: number;
335
346
  v: number;
336
347
  } | undefined;
348
+ /** List `name` without a column (its last value `t`/`v` when finite); a channel that has a column is left as is. */
349
+ list(name: string, unit: string, t?: number, v?: number): void;
337
350
  /**
338
351
  * A channel's last value as the sender knows it (KIND_LAST_VALUES): not a sample (the ring, decimation, cycles
339
352
  * and readers of samples never see it), only the value a quiet channel holds. Creates the column (no samples)
@@ -29,6 +29,22 @@ export type Decoded = {
29
29
  | {
30
30
  type: 'integrity';
31
31
  integrity: StreamIntegrity;
32
+ }
33
+ /** A channel table for the page's SparseFeed: a stream over SPARSE_CHANNELS channels, or one that sends events. */
34
+ | {
35
+ type: 'schema';
36
+ id: number;
37
+ names: string[];
38
+ units: string[];
39
+ }
40
+ /** KIND_SPARSE events of schema `schemaId`: event k is channel index[k] at t[k] with v[k]. */
41
+ | {
42
+ type: 'sparse';
43
+ schemaId: number;
44
+ index: Uint32Array;
45
+ t: Float64Array;
46
+ v: Float64Array;
47
+ historical: boolean;
32
48
  };
33
49
  /**
34
50
  * A stream's messages opened with `key` and handed to `emit` in the order they arrived (decrypted as they arrive, in
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A stream over SPARSE_CHANNELS channels (spec docs/superpowers/specs/2026-11-23-stream-capacity-design.md): every
3
+ * channel is listed in the LiveBuffer without a column, every channel's events kept in a SparseStore, and only the
4
+ * active channels (the ones something read, see LiveDataSource.onUse) get rows in the buffer. 20 charted tags of 50k
5
+ * cost what 20 tags cost.
6
+ */
7
+ import type { LiveBuffer, LiveColumnsBlock } from './buffer';
8
+ import type { LastValue } from './blockWire';
9
+ /** A stream with more channels than this is listed, not held as columns: see the SparseFeed. */
10
+ export declare const SPARSE_CHANNELS = 1000;
11
+ /** ponytail: a cap so a reader of every column (an export) can't densify the stream; eviction of channels nobody
12
+ * read for minutes if someone browses more than this in one session. */
13
+ export declare const MAX_ACTIVE = 1000;
14
+ export declare class SparseFeed {
15
+ private readonly buffer;
16
+ private readonly store;
17
+ private readonly schemas;
18
+ /** Every channel ever listed: unit and newest value (survives a replay's clear). */
19
+ private readonly known;
20
+ private readonly active;
21
+ constructor(buffer: LiveBuffer, maxBytes: number);
22
+ schema(id: number, names: string[], units: string[]): void;
23
+ last(values: LastValue[]): void;
24
+ /** Events of schema `id`. The active channels' ones go into the buffer as rows; that block is returned (null:
25
+ * none, or the schema is unknown). */
26
+ push(id: number, index: Uint32Array, t: Float64Array, v: Float64Array): LiveColumnsBlock | null;
27
+ /** {@link push} by channel name (a dense block on a big stream, as events): names not listed are ignored. */
28
+ pushNamed(t: ArrayLike<number>, names: string[], v: ArrayLike<number>): LiveColumnsBlock | null;
29
+ private events;
30
+ /** Mark `names` active (unknown names and the time column are ignored); true when one was added. Their stored
31
+ * events come with the next {@link replay} (the caller runs one for a tick's activations, not inside a read). */
32
+ activate(names: Iterable<string>): boolean;
33
+ /** Rebuild the buffer: clear, list every channel, and the active channels' newest stored events (at most
34
+ * `buffer.maxSamples` distinct times), merged by time in chunks.
35
+ * ponytail: resets cycles and the segment axis; fine while activation is rare (a chart gets a channel). Each
36
+ * channel's events are taken as time-ordered (arrival order); a late one lands through the buffer's late path. */
37
+ replay(): void;
38
+ private note;
39
+ }
@@ -0,0 +1,18 @@
1
+ export declare class SparseStore {
2
+ private readonly channels;
3
+ private events_;
4
+ private readonly maxBytes;
5
+ constructor(maxBytes: number);
6
+ /** Bytes of events held. */
7
+ get bytes(): number;
8
+ add(name: string, t: number, v: number): void;
9
+ /** `name`'s events, oldest first (views: valid until the next add). */
10
+ events(name: string): {
11
+ t: Float64Array;
12
+ v: Float64Array;
13
+ };
14
+ /** Down to 90% of the budget in one pass (the 10% of slack makes passes rare): the busiest channel loses its oldest
15
+ * half, again and again. Each round halves channels busiest first and sorts again once the halved ones are the
16
+ * busiest again. Ends: each round halves its busiest channel; a store of nothing stops it (a budget of 0 or less). */
17
+ private evict;
18
+ }
@@ -12,6 +12,8 @@ export declare const KIND_VIDEO = 6;
12
12
  export declare const KIND_LAST_VALUES = 7;
13
13
  /** An integrity checkpoint over the messages before it in its lane (see chainWire.ts). */
14
14
  export declare const KIND_CHAIN = 8;
15
+ /** Events of a stream over 1,000 channels, each one channel at its own time (see blockWire.ts decodeSparse). */
16
+ export declare const KIND_SPARSE = 9;
15
17
  export declare const KEY_ID_FLAG = 128;
16
18
  export interface SealedMessage {
17
19
  kind: number;
@@ -7,3 +7,8 @@ export declare function narrowed(g: HeatGrid, maxW: number): {
7
7
  grid: HeatGrid;
8
8
  per: number;
9
9
  };
10
+ /**
11
+ * A colour scale a theme gives as hex colours separated by commas, lowest first (`--chart-spectrogram`), as RGB
12
+ * stops. null when it is unset or anything but two or more hex colours: the chart keeps its own scale.
13
+ */
14
+ export declare function hexStops(css: string): [number, number, number][] | null;
@@ -35,3 +35,33 @@ export interface SpectrogramGrid {
35
35
  readonly key: string;
36
36
  }
37
37
  export declare function spectrogramGrid(signal: ArrayLike<number>, winSz: number, step: number, useHann: boolean, db: boolean, rowBin: Int32Array | null, prev?: SpectrogramGrid | null): SpectrogramGrid;
38
+ /**
39
+ * A spectrogram that follows a stream: the newest `cap` windows on the stream's own hop grid (window F starts at
40
+ * the stream's sample F * hop, counted from its first ever), the newest in the last column. A live chart reads the
41
+ * stream every frame, and the stream arrives in blocks of any size: {@link spectrogramGrid} finds the windows two
42
+ * signals share only when one starts a whole number of hops into the other, which a ring fed 500 samples at a time
43
+ * never does, so there every window was transformed again at each block and landed on a new grid (the picture
44
+ * re-rolled in place). Here the grid is the stream's: an update transforms the windows that became whole since the
45
+ * last one and moves the rest left in place. Nothing is allocated after the first call.
46
+ */
47
+ export interface RollingSpectrogram {
48
+ /** `bins` rows × `cap` columns (row r, column c at values[r * cap + c]), as amplitudes or dB like
49
+ * {@link SpectrogramGrid}; a column never filled is NaN. */
50
+ readonly values: Float32Array;
51
+ readonly cap: number;
52
+ readonly bins: number;
53
+ /** One past the newest window held, on the stream's hop grid: the columns end there. -1 before the first. */
54
+ end: number;
55
+ /** Windows held, in the last `count` columns. */
56
+ count: number;
57
+ /** The largest amplitude among them. */
58
+ max: number;
59
+ /** Windows transformed by the last update. */
60
+ computed: number;
61
+ /**
62
+ * The stream as it is now: `samples` oldest first, `first` how many samples it had before them (a ring that
63
+ * dropped its oldest). True when it took a new window.
64
+ */
65
+ update(samples: ArrayLike<number>, first: number): boolean;
66
+ }
67
+ export declare function rollingSpectrogram(winSz: number, hop: number, cap: number, useHann: boolean, db: boolean, rowBin: Int32Array | null): RollingSpectrogram;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kymoscope/sdk",
3
- "version": "0.16.0",
3
+ "version": "0.18.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 +0,0 @@
1
- const e=e=>e.startsWith(`eyJ`);function t(e){try{let t=e.split(`.`)[1]??``,n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)+`===`.slice((t.length+3)%4)),r=JSON.parse(n).exp;return typeof r==`number`?r:null}catch{return null}}function n(e,t){return`${e.replace(/\/+$/,``)}/v1/streams/${t}/watch`}function r(r,i,a,o){let s=null,c=null,l=null,u=!1,d=0,f=()=>{l&&=(clearTimeout(l),null)},p=(n,a)=>{f();let o=t(a);if(o===null)return;let c=e(a),d=c?Math.min(o,Date.now()/1e3+300):o,m=Math.min(Math.max((d-(c?90:30))*1e3-Date.now(),1e4),2**31-1);l=setTimeout(async()=>{l=null;let e=null;try{e=await r.getToken(i)}catch{e=null}if(!(u||s!==n||!e)){try{n.send(JSON.stringify({type:`auth`,token:e}))}catch{return}p(n,e)}},m)},m=(e=!1)=>{if(u||c)return;let t=e?0:Math.min(3e4,2e3*2**d++)*(.75+Math.random()/2);c=setTimeout(()=>{c=null,h()},t)},h=async()=>{if(u)return;let e=null;try{e=await r.getToken(i)}catch{e=null}if(u)return;if(!e){o?.(`error`),m();return}let t=new WebSocket(n(r.url,i),[`kymoscope-live.v1`,`kymoscope-live.ack1`,`kymoscope-live.ack2`,`bearer.${e}`]);t.binaryType=`arraybuffer`,s=t;let c=e,l=Date.now(),h=0,g=setInterval(()=>{if(!(h===0||t.readyState!==1)){try{t.send(JSON.stringify({type:`ack`,b:h}))}catch{return}h=0}},1e3);t.onopen=()=>{o?.(`subscribed`),p(t,c)},t.onmessage=e=>{if(d=0,typeof e.data!=`string`){h+=e.data.byteLength,a(e.data);return}if(e.data.startsWith(`{"type":"probe"`))try{let n=JSON.parse(e.data).id;typeof n==`string`&&n.length<=64&&t.send(JSON.stringify({type:`ack`,id:n}))}catch{}},t.onclose=()=>{clearInterval(g),s===t&&(s=null,f(),!u&&(o?.(`error`),m(Date.now()-l>=1e4)))}};return h(),()=>{if(u=!0,c&&=(clearTimeout(c),null),f(),s){let e=s;s=null,e.close(1e3)}}}new TextEncoder;function i(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>=4096&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}const a=new TextDecoder;function o(e,t,n){let r=e.subarray(t,t+n);return a.decode(r)}function s(e,t,n){return n>200?o(e,t,n):i(e,t,n)}var c=class{type;data;constructor(e,t){this.type=e,this.data=t}},l=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 u(e,t,n){let r=Math.floor(n/4294967296),i=n;e.setUint32(t,r),e.setUint32(t+4,i)}function d(e,t){let n=e.getInt32(t),r=e.getUint32(t+4);return n*4294967296+r}function f(e,t){let n=e.getUint32(t),r=e.getUint32(t+4);return n*4294967296+r}function p({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=17179869183)if(t===0&&e<=4294967295){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),u(r,4,e),n}}function m(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 h(e){return e instanceof Date?p(m(e)):null}function g(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:d(t,4),nsec:t.getUint32(0)};default:throw new l(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function _(e){let t=g(e);return new Date(t.sec*1e3+t.nsec/1e6)}const ee={type:-1,encode:h,decode:_};var v=class e{static defaultCodec=new e;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(ee)}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 c(-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 c(n,i)}}return e instanceof c?e:null}decode(e,t,n){let r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,n):new c(t,e)}};function y(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}function b(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):y(e)?new Uint8Array(e):Uint8Array.from(e)}function x(e){return`${e<0?`-`:``}0x${Math.abs(e).toString(16).padStart(2,`0`)}`}var te=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=16,t=16){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 a=i(e,t,n),o=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(o,a),a}};const S=`array`,C=`map_key`,w=`map_value`,T=e=>{if(typeof e==`string`||typeof e==`number`)return e;throw new l(`The type of key must be string or number but `+typeof e)};var E=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=S,t.position=0,t.size=e,t.array=Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=C,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===S){let t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===C||e.type===w){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}};const D=new DataView(new ArrayBuffer(0)),ne=new Uint8Array(D.buffer);try{D.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`)}const O=RangeError(`Insufficient data`),re=new te;var ie=class e{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=D;bytes=ne;headByte=-1;stack=new E;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??v.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?re:e.keyDecoder,this.mapKeyConverter=e?.mapKeyConverter??T}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=-1,this.stack.reset()}setBuffer(e){let t=b(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===-1&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),n=b(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 ${x(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 l(`Unrecognized type byte: ${x(e)}`);this.complete();let n=this.stack;for(;n.length>0;){let e=n.top();if(e.type===S)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===C){if(t===`__proto__`)throw new l(`The key __proto__ is not allowed`);e.key=this.mapKeyConverter(t),e.type=w;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=C;continue DECODE}}return t}}readHeadByte(){return this.headByte===-1&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}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 l(`Unrecognized array type byte: ${x(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new l(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new l(`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 l(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw O;let n=this.pos+t,r;return r=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,n,e):s(this.bytes,n,e),this.pos+=t+e,r}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===C:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new l(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw O;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 l(`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=f(this.view,this.pos);return this.pos+=8,e}readI64(){let e=d(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 k(e,t){return new ie(t).decode(e)}function A(){let e=globalThis.crypto;if(!e?.subtle)throw Error(`WebCrypto SubtleCrypto is not available`);return e.subtle}async function j(e,t,n,r){let i=await A().decrypt({name:`AES-GCM`,iv:t,additionalData:r},e,n);return new Uint8Array(i)}new TextEncoder().encode(`kymoscope-device-wrap-v1`),new TextEncoder().encode(`kymoscope-sender-bind-v1`);function M(e){let t=new Uint8Array(e),n=t.length>0&&t[0]&128?2:1;return t.length<n+12+16?null:{kind:t[0]&-129,keyId:n===2?t[1]:null,iv:t.subarray(n,n+12),ciphertext:t.subarray(n+12),aad:t.subarray(0,n)}}async function N(e,t){let n=M(t);if(!n)return null;let r=typeof e==`function`?await e(n.keyId):e;if(!r)return null;let i=await j(r,n.iv,n.ciphertext,n.aad);return{kind:n.kind,plaintext:i}}const P=e=>e+7&-8;function F(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)!==1)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=P(s),s+P(i*8)+o.reduce((e,t)=>e+P(i*t.size),0)>e.byteLength)throw t(`short data`);let c=e.byteOffset,l=new Float64Array(e.buffer,c+s,i);s+=P(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+=P(i*t.size);return{t:l,columns:u,units:d}}function I(e){if(e.length<24||e[0]!==1||e[2]!==1)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=(e[1]&1)!=0,r=t.getUint16(16,!0),i=t.getUint16(18,!0);if(i===0||r>=i)return null;let a=24,o=``;if(n&&r===0){if(e.length<a+1||e.length<a+1+e[a])return null;o=new TextDecoder().decode(e.subarray(a+1,a+1+e[a])),a+=1+e[a]}return{key:n,last:(e[1]&2)!=0,t:t.getFloat64(4,!0),seq:t.getUint32(12,!0),fragIndex:r,fragCount:i,width:t.getUint16(20,!0),height:t.getUint16(22,!0),codec:o,payload:e.subarray(a)}}const L=(e,t)=>RangeError(`${e}: ${t}`);function R(e){if(e.byteLength<8)throw L(`block schema`,`short`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(t.getUint8(0)!==2)throw L(`block schema`,`version ${t.getUint8(0)}`);let n=t.getUint16(2,!0),r=t.getUint32(4,!0),i=new TextDecoder(`utf-8`,{fatal:!0}),a=[],o=8;try{for(let r=0;r<n;r++){if(o+3>e.byteLength)throw L(`block schema`,`short channel table`);let n=t.getUint8(o),r=t.getUint8(o+1),s=t.getUint8(o+2);if(o+=3,n!==4&&n!==8)throw L(`block schema`,`value size ${n}`);if(o+r+s>e.byteLength)throw L(`block schema`,`short channel table`);a.push({name:i.decode(e.subarray(o,o+r)),unit:i.decode(e.subarray(o+r,o+r+s)),size:n}),o+=r+s}}catch(e){throw e instanceof RangeError?e:L(`block schema`,`invalid text`)}return{id:r,channels:a}}function z(e,t){if(e.byteLength<12)throw L(`last values`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==1)throw L(`last values`,`version ${n.getUint8(0)}`);let r=t.get(n.getUint32(4,!0));if(!r)return null;let i=n.getUint32(8,!0);if(i!==r.channels.length)throw L(`last values`,`channel count differs from its schema`);if(e.byteLength<12+16*i)throw L(`last values`,`short`);let a=[];for(let e=0;e<i;e++){let t=n.getFloat64(12+8*e,!0),o=n.getFloat64(12+8*(i+e),!0);Number.isFinite(t)&&Number.isFinite(o)&&a.push({name:r.channels[e].name,unit:r.channels[e].unit,t,v:o})}return a}async function B(e,t){let n=new Blob([e]).stream().pipeThrough(new DecompressionStream(`deflate`)).getReader(),r=new Uint8Array(t),i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+a.length>t)throw L(`block`,`body larger than its header says`);r.set(a,i),i+=a.length}}catch(e){throw await n.cancel().catch(()=>{}),e instanceof RangeError?e:L(`block`,`body is not valid deflate`)}if(i!==t)throw L(`block`,`body size mismatch`);return r}async function V(e,t){if(e.byteLength<20)throw L(`block`,`short`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint8(0)!==2)throw L(`block`,`version ${n.getUint8(0)}`);let r=n.getUint8(1),i=n.getUint16(2,!0),a=n.getUint32(4,!0),o=t.get(n.getUint32(8,!0));if(!o)return null;if(o.channels.length!==i)throw L(`block`,`channel count differs from its schema`);let s=n.getFloat64(12,!0),c=Math.max(0,a-1),l=4*c+o.channels.reduce((e,t)=>e+t.size*a,0);if(l>67108864)throw L(`block`,`too large`);let u;if(r&1)u=await B(e.subarray(20),l);else if(u=e.subarray(20),u.byteLength<l)throw L(`block`,`body size mismatch`);let d=new DataView(u.buffer,u.byteOffset,u.byteLength),f=new Float64Array(a),p=0;a&&(f[0]=s);for(let e=1;e<a;e++)p+=d.getInt32(4*(e-1),!0),f[e]=s+p/1e6;let m=4*c,h={},g={};for(let e of o.channels){let t=new Uint8Array(a*e.size);for(let n=0;n<e.size;n++)for(let r=0;r<a;r++)t[r*e.size+n]=u[m+n*a+r];h[e.name]=e.size===4?new Float32Array(t.buffer):new Float64Array(t.buffer),e.unit&&(g[e.name]=e.unit),m+=a*e.size}return{block:{t:f,columns:h,units:g},historical:(r&2)!=0}}const H=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),U=e=>{let t=H(e);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`};function W(e){if(e.length!==70||e[0]!==1)return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{streamId:U(e.subarray(1,17)),run:H(e.subarray(17,25)),lane:e[25],seq:t.getBigUint64(26,!0),count:t.getUint32(34,!0),hash:e.slice(38,70)}}const G=()=>globalThis.crypto.subtle,K=e=>G().digest(`SHA-256`,e);async function q(e){let t=await Promise.all(e),n=new Uint8Array(t.length*32);return t.forEach((e,t)=>n.set(new Uint8Array(e),t*32)),new Uint8Array(await K(n))}function J(e,t,n=()=>Date.now()){let r={verified:0,broken:0},i=null,a=0n,o=null,s=0,c=0,l=0,u=Promise.resolve(),d=e=>{e?r.verified++:(r.broken++,r.lastBrokenAt=n()),t({...r})};return{integrity:r,reset(){i=null,o=null,c=s,l++},arrive(t,n,r){if(n!==8){o&&(o.push(K(t)),s++);return}let f=s;o||(o=[],c=s);let p=l;u=u.then(async()=>{let t=await r.catch(()=>null);if(p!==l)return;let n=t?W(t.plaintext):null;if(!n||n.lane!==0||n.streamId!==e.toLowerCase()){i!==null&&d(!1);return}let s=f-c;if(i===null||n.run!==i){i=n.run,a=n.seq,o=o.slice(Math.max(0,s)),c=Math.max(c,f);return}let u=n.seq===a+1n&&n.count<=s&&ae(await q(o.slice(0,n.count)),n.hash);if(p!==l)return;a=n.seq;let m=u?n.count:s;o=o.slice(m),c+=m,d(u)})}}}const ae=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function oe(e,t,n){let r=new Map,i=Promise.resolve(),a=n?J(n,e=>t({type:`integrity`,integrity:e})):null;return Object.assign(n=>{let o=N(e,n).catch(()=>null);a?.arrive(n,new Uint8Array(n,0,1)[0]&127,o),i=i.then(async()=>{try{let e=await o;if(!e)return;if(e.kind===6){let n=I(e.plaintext);n&&t({type:`video`,m:n})}else if(e.kind===5){let t=R(e.plaintext);r.set(t.id,t)}else if(e.kind===7){let n=z(e.plaintext,r);n&&t({type:`last`,values:n})}else if(e.kind===4){let n=await V(e.plaintext,r);n&&t(n.historical?{type:`columns`,block:n.block,historical:!0}:{type:`columns`,block:n.block})}else if(e.kind===3)t({type:`columns`,block:F(e.plaintext)});else if(e.kind===2){let n=k(e.plaintext);t({type:`frames`,frames:Array.isArray(n?.frames)?n.frames:[]})}}catch{}})},{reset:()=>a?.reset()})}function Y(e){if(e.type!==`columns`)return[];let t=new Set,n=e=>{ArrayBuffer.isView(e)&&Object.prototype.toString.call(e.buffer)===`[object ArrayBuffer]`&&t.add(e.buffer)};n(e.block.t);for(let t of Object.values(e.block.columns))n(t);return[...t]}function se(e,t=67108864){let n=0,r=0,i=0;return{emit(a){let o=Y(a).reduce((e,t)=>e+t.byteLength,0);if(a.type===`columns`&&n>0&&n+o>t){r+=a.block.t.length,i+=a.block.t.length;return}a.type===`columns`&&i>0&&(e({type:`gap`,samples:i},0),i=0),n+=o,e(a,o)},ack(e){n=Math.max(0,n-e)},get dropped(){return r}}}let ce=1;const X=new Map,Z=(e,t)=>new Promise(n=>{let r=ce++;X.set(r,n),self.postMessage({type:`ask`,id:r,what:e,arg:t})});let Q=null;const $=se((e,t)=>self.postMessage({type:`decoded`,d:e,bytes:t},Y(e)));self.onmessage=e=>{let t=e.data;if(t.type===`reply`){X.get(t.id)?.(t.value),X.delete(t.id);return}if(t.type===`ack`){$.ack(t.bytes);return}if(t.type===`stop`){Q?.(),Q=null,self.close();return}let n=new Map,i=oe(t.key??(async e=>{let t=n.get(e);if(t)return t;let r=await Z(`key`,e);return r&&n.set(e,r),r}),$.emit,t.streamId);Q=r({url:t.url,getToken:()=>Z(`token`)},t.streamId,i,e=>{e===`subscribed`&&i.reset(),self.postMessage({type:`status`,status:e})})};