@mdgs/pivotjet 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Manikumaran Jaganathan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,628 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # pivotjet
2
+
3
+ A pivot table **engine, viewer and designer** built for large data. Ingests and pivots **10 million+ records in the browser or Node**, with zero dependencies and no framework lock-in.
4
+
5
+ - **Engine** (`@mdgs/pivotjet/core`): columnar, dictionary-encoded store + single-pass aggregation. DOM-free: use it in Node, workers, SSR.
6
+ - **Viewer**: virtualized grid (only visible cells are in the DOM), expand/collapse, subtotals, grand totals, sort by value, drill-through, **charts**, **CSV / Excel / PDF export**, light/dark.
7
+ - **Designer**: drag & drop field list, rows / columns / values / filters, aggregate & format pickers (incl. distinct count and median), date grouping, value filters, **calculated fields**, **saved layouts**, table/chart toggle.
8
+ - **Scale**: 10 M+ rows in memory; unlimited rows via **streaming** or a built-in **server** (`pivotjet serve`).
9
+ - Works from **vanilla JS, React, Vue, Angular, Svelte**, or a plain `<script>` tag (custom elements included). Types included.
10
+
11
+ ## Screenshots
12
+
13
+ **Designer.** Drag fields onto the filter, column, row and value zones. Shown on 1,000,000 rows: the field list on the left, the virtualized grid below.
14
+
15
+ ![The pivotjet designer with field list, drop zones and grid](https://cdn.jsdelivr.net/npm/@mdgs/pivotjet@0.1.0/docs/images/designer.png)
16
+
17
+ **Configure fields.** The **Fields** button opens a dialog to pick fields and arrange Columns, Rows and Values, with an aggregate picker per value.
18
+
19
+ ![The Configure Pivot fields dialog](https://cdn.jsdelivr.net/npm/@mdgs/pivotjet@0.1.0/docs/images/configure-fields.png)
20
+
21
+ **Cell formats.** Rules (threshold highlights, subtotal styling, number formats) stack top to bottom; right-click any cell to format just that cell.
22
+
23
+ ![Conditional cell formats on a pivot](https://cdn.jsdelivr.net/npm/@mdgs/pivotjet@0.1.0/docs/images/cell-formats.png)
24
+
25
+ **10 million rows.** 10,000,000 rows loaded in the browser (about 320 MB, 8 s on the test machine); this pivot recomputes in 0.37 s.
26
+
27
+ ![The designer on 10,000,000 rows](https://cdn.jsdelivr.net/npm/@mdgs/pivotjet@0.1.0/docs/images/large-dataset.png)
28
+
29
+ **Charts.** Any pivot as a chart (column, bar, line, area, pie, donut) from the same spec.
30
+
31
+ ![A pivot shown as a column chart](https://cdn.jsdelivr.net/npm/@mdgs/pivotjet@0.1.0/docs/images/chart.png)
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ npm install @mdgs/pivotjet
37
+ ```
38
+
39
+ ## Quick start (ESM)
40
+
41
+ ```js
42
+ import { Dataset, PivotDesigner } from '@mdgs/pivotjet';
43
+
44
+ const ds = Dataset.fromRows(rows, [
45
+ 'Region', 'Product',
46
+ { name: 'Date', type: 'date' },
47
+ { name: 'Revenue', role: 'measure' },
48
+ ]);
49
+
50
+ new PivotDesigner('#app', {
51
+ dataset: ds,
52
+ spec: {
53
+ rows: [{ field: 'Region' }, { field: 'Product' }],
54
+ cols: [{ field: 'Date', bucket: 'year' }],
55
+ values: [{ field: 'Revenue', agg: 'sum', format: 'compact' }],
56
+ },
57
+ });
58
+ ```
59
+
60
+ Viewer only (no designer panel):
61
+
62
+ ```js
63
+ import { PivotViewer } from '@mdgs/pivotjet';
64
+ const viewer = new PivotViewer('#app', { dataset: ds, spec });
65
+ viewer.on('cellclick', (e) => console.log(e.row, e.col, e.value));
66
+ await viewer.setSpec(newSpec);
67
+ ```
68
+
69
+ Headless (Node / worker / server):
70
+
71
+ ```js
72
+ import { Dataset, computePivot } from '@mdgs/pivotjet/core';
73
+ const result = await computePivot(ds, spec);
74
+ const east = result.rowRoot.children.find((n) => n.label === 'East');
75
+ result.get(east, result.colRoot, 0); // East total, value #0
76
+ result.get(result.rowRoot, result.colRoot, 0); // grand total
77
+ console.log(result.toCSV());
78
+ ```
79
+
80
+ CommonJS: `const { Dataset } = require('@mdgs/pivotjet')`.
81
+
82
+ **Designer layout.** The **Columns** and **Rows** drop zones sit in the grid's top-left corner, as in mdg-pivot: column fields are listed beside the column headers (one per header level) and row fields in the line under them. Drag fields in from the list, drag chips to reorder or move them between zones, `×` removes. **Filters** and **Values** stay in a slim strip above the grid. In Chart view (no grid) all four zones return to the strip. `new PivotDesigner(el, { fieldZones: 'top' })` keeps the older all-in-a-strip layout.
83
+
84
+ **Configure dialogs** (as in mdg-pivot). **⚙ Fields** opens "Configure Pivot fields": the field list (search, select all, a checkbox per field, formula fields in their own group) beside **Columns**, **Rows** and **Values** panes. Ticking a number adds it to Values (Sum), ticking anything else adds it to Rows; drag items between panes, click one and use ▲ ▼ to reorder, pick the aggregate per value, and **Add Formula Field** creates a calculated field. Nothing changes until **Apply** (Cancel / Esc discards). **⏷ Filters** opens the same dialog for the filter fields. Open them from code with `designer.openConfigDialog('fields' | 'filters')`. The ⛶ button toggles full screen.
85
+
86
+ ### Script tag / any framework (web components)
87
+
88
+ ```html
89
+ <script src="https://unpkg.com/@mdgs/pivotjet"></script>
90
+ <pivotjet-designer id="p" style="height:560px"></pivotjet-designer>
91
+ <script>
92
+ const el = document.getElementById('p');
93
+ el.data = PivotJet.Dataset.fromRows(rows);
94
+ el.spec = { rows: [{ field: 'Region' }], values: [{ field: 'Sales' }] };
95
+ el.addEventListener('change', (e) => save(e.detail));
96
+ </script>
97
+ ```
98
+
99
+ `<pivotjet-viewer>` is the read-only version. Per-framework samples (React, Next.js, Vue, Nuxt, Angular, Svelte, Solid, Astro, plain JS) are in [Framework integration](#framework-integration). With the web components: React `<pivotjet-designer ref={r => r && (r.data = ds)} />`, Vue `<pivotjet-designer :data.prop="ds" :spec.prop="spec" />`, Angular `CUSTOM_ELEMENTS_SCHEMA`; `import '@mdgs/pivotjet/elements'` registers them in bundler setups.
100
+
101
+ ## Framework integration
102
+
103
+ pivotjet has no framework dependency. Every sample below follows the same three rules:
104
+
105
+ 1. **Create** the designer/viewer once the host element exists (mounted / `useEffect` / `ngAfterViewInit`).
106
+ 2. **Update** it with `setDataset()` / `setSpec()` when your props change.
107
+ 3. **Destroy** it on unmount (`destroy()` removes listeners, workers and DOM).
108
+
109
+ `import '@mdgs/pivotjet'` is safe to import on the server (no DOM access at import time); only *construct* the designer in the browser. Use `PivotViewer` instead of `PivotDesigner` for a read-only grid; both take `{ dataset, spec, theme }` and emit `change` / `compute-end` / `cellclick`. The data source can be an in-memory `Dataset`, a `StreamSource`, or a `RemoteDataset` from your server (`await RemoteDataset.connect('https://host', 'sales', { token })`).
110
+
111
+ > **Keep the dataset out of reactive proxies.** A `Dataset` holds large typed arrays; Vue (`ref`, `reactive`), Svelte 5 (`$state`) and Solid stores wrap objects in deep proxies, which makes every aggregation slow. Hold it in `shallowRef` / `markRaw` (Vue), `$state.raw` (Svelte) or a plain variable / signal (Solid), as the samples do. React and Angular do not proxy.
112
+
113
+ ### React
114
+
115
+ ```jsx
116
+ // Pivot.jsx
117
+ import { useEffect, useRef } from 'react';
118
+ import { PivotDesigner } from '@mdgs/pivotjet';
119
+
120
+ export function Pivot({ dataset, spec, onChange, height = 600 }) {
121
+ const host = useRef(null);
122
+ const pivot = useRef(null);
123
+ const cb = useRef(onChange);
124
+ cb.current = onChange;
125
+
126
+ useEffect(() => { // create once (StrictMode-safe: cleanup destroys)
127
+ pivot.current = new PivotDesigner(host.current, { dataset, spec });
128
+ const off = pivot.current.on('change', (s) => cb.current && cb.current(s));
129
+ return () => { off(); pivot.current.destroy(); pivot.current = null; };
130
+ }, []);
131
+ useEffect(() => { if (pivot.current && dataset) pivot.current.setDataset(dataset); }, [dataset]);
132
+
133
+ return <div ref={host} style={{ height }} />;
134
+ }
135
+
136
+ // App.jsx
137
+ import { useMemo } from 'react';
138
+ import { Dataset } from '@mdgs/pivotjet';
139
+ import { Pivot } from './Pivot';
140
+
141
+ export default function App({ rows }) {
142
+ const dataset = useMemo(() => Dataset.fromRows(rows, ['Region', 'Product', { name: 'Revenue', role: 'measure' }]), [rows]);
143
+ return <Pivot dataset={dataset} spec={{ rows: [{ field: 'Region' }], values: [{ field: 'Revenue' }] }} onChange={(s) => localStorage.setItem('layout', JSON.stringify(s))} />;
144
+ }
145
+ ```
146
+
147
+ ### Next.js (App Router or Pages)
148
+
149
+ The component above is browser-only, so load it without SSR:
150
+
151
+ ```jsx
152
+ // app/pivot/page.jsx
153
+ 'use client';
154
+ import dynamic from 'next/dynamic';
155
+ const Pivot = dynamic(() => import('../../components/Pivot').then((m) => m.Pivot), { ssr: false });
156
+
157
+ export default function Page() {
158
+ return <Pivot dataset={/* from state, a fetch, or RemoteDataset */ null} />;
159
+ }
160
+ ```
161
+
162
+ Fetch the data in a `useEffect` (or serve it from a route handler and use `RemoteDataset`); do not build a large `Dataset` during server rendering.
163
+
164
+ ### Vue 3
165
+
166
+ ```vue
167
+ <!-- Pivot.vue -->
168
+ <script setup>
169
+ import { onMounted, onBeforeUnmount, ref, watch } from 'vue';
170
+ import { PivotDesigner } from '@mdgs/pivotjet';
171
+
172
+ const props = defineProps({ dataset: Object, spec: Object });
173
+ const emit = defineEmits(['change']);
174
+ const host = ref(null);
175
+ let pivot = null, off = null; // plain variables: never make the instance reactive
176
+
177
+ onMounted(() => {
178
+ pivot = new PivotDesigner(host.value, { dataset: props.dataset, spec: props.spec });
179
+ off = pivot.on('change', (s) => emit('change', s));
180
+ });
181
+ onBeforeUnmount(() => { if (off) off(); if (pivot) pivot.destroy(); });
182
+ watch(() => props.dataset, (ds) => { if (pivot && ds) pivot.setDataset(ds); });
183
+ </script>
184
+
185
+ <template><div ref="host" style="height: 600px"></div></template>
186
+ ```
187
+
188
+ ```vue
189
+ <!-- App.vue -->
190
+ <script setup>
191
+ import { shallowRef } from 'vue';
192
+ import { Dataset } from '@mdgs/pivotjet';
193
+ import Pivot from './Pivot.vue';
194
+
195
+ const dataset = shallowRef(null); // shallowRef (or markRaw) keeps the Dataset un-proxied
196
+ fetch('/sales.json').then((r) => r.json()).then((rows) => { dataset.value = Dataset.fromRows(rows); });
197
+ </script>
198
+
199
+ <template><Pivot v-if="dataset" :dataset="dataset" @change="console.log" /></template>
200
+ ```
201
+
202
+ ### Nuxt 3
203
+
204
+ Name the component `components/Pivot.client.vue` (the `.client` suffix renders it only in the browser), or wrap it: `<ClientOnly><Pivot :dataset="dataset" /></ClientOnly>`. The component code is the Vue 3 sample above; keep the `Dataset` in `shallowRef`.
205
+
206
+ ### Angular (standalone components, v15+)
207
+
208
+ ```ts
209
+ // pivot.component.ts
210
+ import { AfterViewInit, Component, ElementRef, EventEmitter, Input, NgZone, OnChanges, OnDestroy, Output, SimpleChanges, ViewChild } from '@angular/core';
211
+ import { Dataset, PivotDesigner, PivotSpec } from '@mdgs/pivotjet';
212
+
213
+ @Component({
214
+ selector: 'app-pivot',
215
+ standalone: true,
216
+ template: '<div #host style="height: 600px"></div>',
217
+ })
218
+ export class PivotComponent implements AfterViewInit, OnChanges, OnDestroy {
219
+ @Input() dataset?: Dataset;
220
+ @Input() spec?: PivotSpec;
221
+ @Output() specChange = new EventEmitter<PivotSpec>();
222
+ @ViewChild('host', { static: true }) host!: ElementRef<HTMLDivElement>;
223
+
224
+ private pivot?: PivotDesigner;
225
+ private off?: () => void;
226
+ constructor(private zone: NgZone) {}
227
+
228
+ ngAfterViewInit() {
229
+ // run outside Angular so scrolling / dragging does not trigger change detection
230
+ this.zone.runOutsideAngular(() => {
231
+ this.pivot = new PivotDesigner(this.host.nativeElement, { dataset: this.dataset, spec: this.spec });
232
+ this.off = this.pivot.on('change', (s) => this.zone.run(() => this.specChange.emit(s)));
233
+ });
234
+ }
235
+ ngOnChanges(c: SimpleChanges) {
236
+ if (c['dataset'] && this.dataset && this.pivot) this.pivot.setDataset(this.dataset);
237
+ }
238
+ ngOnDestroy() { this.off?.(); this.pivot?.destroy(); }
239
+ }
240
+ ```
241
+
242
+ ```html
243
+ <!-- app.component.html -->
244
+ <app-pivot [dataset]="dataset" [spec]="spec" (specChange)="save($event)"></app-pivot>
245
+ ```
246
+
247
+ No wrapper needed if you prefer the web component: add `schemas: [CUSTOM_ELEMENTS_SCHEMA]`, `import '@mdgs/pivotjet/elements';` once, then `<pivotjet-designer [data]="dataset" [spec]="spec" (change)="save($event.detail)"></pivotjet-designer>`.
248
+
249
+ ### Svelte / SvelteKit
250
+
251
+ ```svelte
252
+ <!-- Pivot.svelte (Svelte 5) -->
253
+ <script>
254
+ import { onMount } from 'svelte';
255
+ import { PivotDesigner } from '@mdgs/pivotjet';
256
+
257
+ let { dataset, spec, onchange } = $props();
258
+ let host;
259
+ let pivot;
260
+
261
+ onMount(() => { // runs in the browser only, so SvelteKit SSR is fine
262
+ pivot = new PivotDesigner(host, { dataset, spec });
263
+ const off = pivot.on('change', (s) => onchange?.(s));
264
+ return () => { off(); pivot.destroy(); };
265
+ });
266
+ $effect(() => { if (pivot && dataset) pivot.setDataset(dataset); });
267
+ </script>
268
+
269
+ <div bind:this={host} style="height: 600px"></div>
270
+ ```
271
+
272
+ ```svelte
273
+ <script>
274
+ import { Dataset } from '@mdgs/pivotjet';
275
+ import Pivot from './Pivot.svelte';
276
+ let dataset = $state.raw(null); // $state.raw: no deep proxy around the Dataset
277
+ fetch('/sales.json').then((r) => r.json()).then((rows) => (dataset = Dataset.fromRows(rows)));
278
+ </script>
279
+
280
+ {#if dataset}<Pivot {dataset} onchange={(s) => console.log(s)} />{/if}
281
+ ```
282
+
283
+ (Svelte 4: use `export let dataset;` and `$: if (pivot && dataset) pivot.setDataset(dataset);`.)
284
+
285
+ ### SolidJS
286
+
287
+ ```jsx
288
+ import { createEffect, onCleanup, onMount } from 'solid-js';
289
+ import { PivotDesigner } from '@mdgs/pivotjet';
290
+
291
+ export function Pivot(props) {
292
+ let host;
293
+ let pivot;
294
+ onMount(() => {
295
+ pivot = new PivotDesigner(host, { dataset: props.dataset, spec: props.spec });
296
+ const off = pivot.on('change', (s) => props.onChange?.(s));
297
+ onCleanup(() => { off(); pivot.destroy(); });
298
+ });
299
+ createEffect(() => { const ds = props.dataset; if (pivot && ds) pivot.setDataset(ds); });
300
+ return <div ref={host} style="height: 600px" />;
301
+ }
302
+ ```
303
+
304
+ ### Astro, Qwik, Lit and everything else
305
+
306
+ Use the web components: `import '@mdgs/pivotjet/elements'` in a client-side script, then `<pivotjet-designer>` / `<pivotjet-viewer>` in any template (Astro: put the import inside `<script>` so it runs in the browser). Set data with the `data` property and listen for the `change` event (`e.detail` is the spec). Without a bundler, load `https://unpkg.com/@mdgs/pivotjet` and use the `PivotJet` global as in the web-component sample above.
307
+
308
+ ### Plain JavaScript, jQuery, server-rendered pages
309
+
310
+ ```html
311
+ <div id="pivot" style="height: 600px"></div>
312
+ <script type="module">
313
+ import { Dataset, PivotDesigner } from 'https://unpkg.com/@mdgs/pivotjet/src/index.js';
314
+ const rows = await (await fetch('/api/sales')).json();
315
+ new PivotDesigner('#pivot', { dataset: Dataset.fromRows(rows), spec: { rows: [{ field: 'Region' }], values: [{ field: 'Revenue' }] } });
316
+ </script>
317
+ ```
318
+
319
+ ### Show a saved report from any stack
320
+
321
+ A saved report renders with no framework and no data (see *Reports*): `PivotJet.renderReport('#el', report)`, or serve the server's share page `/report/<dataset>/<id>` in an `<iframe>`.
322
+
323
+ ## Loading data
324
+
325
+ | API | Use |
326
+ | --- | --- |
327
+ | `Dataset.fromRows(rows, fields?)` | array of objects |
328
+ | `Dataset.fromColumns({ a: [...], b: Float64Array })` | column arrays |
329
+ | `ds.addRowArrays(batch)` | positional arrays, fastest (~1.4 M rows/s) |
330
+ | `ds.loadAsync(asyncIterable)` | stream batches; yields to the UI between batches |
331
+ | `await loadCSV(fileOrResponseOrStream, opts)` | streaming CSV: quotes, CRLF, BOM, type inference. Never holds the file in memory |
332
+
333
+ Fields: `{ name, type?: 'string'|'number'|'date'|'boolean', role?: 'dimension'|'measure'|'both'|'skip' }`. By default numbers are measures and everything else is a dimension. Use `role: 'both'` for numeric fields you also want to group by (e.g. Year), and `role: 'skip'` for columns you never pivot (IDs, free text). That is also how you save memory.
334
+
335
+ ## Pivot spec
336
+
337
+ ```ts
338
+ {
339
+ rows: [{ field, bucket?: 'year'|'quarter'|'month'|'day', sort?: 'asc'|'desc'|'natural' }],
340
+ cols: [ /* same */ ],
341
+ values: [{ field, agg?: 'sum'|'count'|'avg'|'min'|'max'|'distinct'|'median', label?, format?, showAs?: 'value'|'pctRow'|'pctCol'|'pctGrand' }
342
+ | { calc: '[A] / [B]', label?, format? }],
343
+ filters: [{ field, include?: [...] } | { field, exclude?: [...] }],
344
+ options: { grandTotals?, colSubtotals?, expandRows?, expandCols?, maxCells?, view?: 'table'|'chart', chart?: { type, ... } }
345
+ }
346
+ ```
347
+
348
+ The spec is plain JSON: store it, send it, version it. Date buckets use UTC so results don't depend on the viewer's timezone. `{ agg: 'count' }` with no field counts rows.
349
+
350
+ ## How it handles 10 million rows
351
+
352
+ - **Columnar, chunked storage.** Dimensions are dictionary-encoded into `Uint8/16/32Array` (width chosen per 131k-row chunk and upgraded on demand); measures are `Float64Array`. No per-row objects, so the cost is a few bytes per field per row. The benchmark dataset (6 dimensions + 3 measures × 10 M rows) uses **~320 MB**.
353
+ - **One scan, then work proportional to the result.** A single pass accumulates leaf cells into a dense typed array or (for large key spaces) a hash. Subtotals and grand totals are rolled up from leaf cells; every supported aggregate is decomposable, so they never rescan rows.
354
+ - **The UI never freezes.** Scans are time-sliced (≈24 ms) with progress and cancellation (`AbortSignal`); a newer request supersedes an older one automatically. Dictionary ordering is cached between queries.
355
+ - **Virtualized rendering.** Only visible cells exist in the DOM, and scroll positions are scaled so results with millions of rows stay under browser element-size limits.
356
+ - **Guard rails.** `maxCells` (default 2 M) rejects runaway pivots with a clear `PivotLimitError` after a few seconds, not an out-of-memory crash. Dimensions beyond `maxCardinality` (default 2 M distinct values, e.g. order IDs) are disabled with a warning.
357
+
358
+ ### Measured (Node 24, 10,000,000 rows, 6 dims + 3 measures)
359
+
360
+ `npm run bench` reproduces these on your machine. Measured on an Intel i7-11800H (16 threads), 32 GB RAM, Windows 11, Node 24, with nothing else running.
361
+
362
+ | Operation | Time | Result cells |
363
+ | --- | --- | --- |
364
+ | Ingest 10 M rows | 4.6 s (2.2 M rows/s), **320 MB** data, 651 MB process | |
365
+ | Grand total | 0.07 s | 1 |
366
+ | Region × Channel (sum, avg, count) | 0.18 s | 45 |
367
+ | Year > Quarter × Region | 0.20 s | 234 |
368
+ | Category > Product (80k leaf rows) × Channel | 0.33 s | 400,205 |
369
+ | Customer (50k rows) × Year, 3 measures + min / max | 0.68 s | 300,006 |
370
+ | APAC only: Category > Product × Month (hash path) | 2.0 s | 1,183,014 |
371
+ | Filtered (APAC, Web), Category > Product | 0.13 s | 78,433 |
372
+ | Runaway pivot (38 M possible cells), refused by the `maxCells` guard | 0.75 s, `PivotLimitError` | |
373
+
374
+ The longest UI stall (time the page cannot respond) was about 20-60 ms for most pivots and at most about 210 ms.
375
+
376
+ In a Chromium-based browser the same 10 M dataset loads in 5.1 s into 320 MB of typed arrays; Region × Channel takes 0.13 s, Category > Product × Channel (400k cells) 0.30 s and Customer (50k rows) × Year 0.53 s. A 1.2 M-leaf-row pivot with roll-ups renders correctly across the whole scroll range (scroll scaling kicks in past ~8 M px).
377
+
378
+ ### Measured: GST invoices, 10,000,000 line items
379
+
380
+ A realistic invoice register: **363,417 invoices with 5-50 items each** (10 M lines, 26 columns): invoice no / date / type, customer, GSTIN, place of supply, payment terms, salesperson, warehouse, item, HSN, UoM, GST rate, qty, rate, discount %, gross, discount, taxable value, CGST / SGST / IGST (IGST for inter-state), line total, plus credit notes. Source: [`bench/invoice-example.mjs`](bench/invoice-example.mjs) (`node --max-old-space-size=8192 bench/invoice-example.mjs`; add `ONLY=median` to run one case). Node 24, Intel i7-11800H (16 threads), 32 GB RAM, Windows 11.
381
+
382
+ | Operation | Time | Result cells |
383
+ | --- | --- | --- |
384
+ | Ingest 10 M lines × 26 columns | 11.5 s (0.87 M lines/s), **1.08 GB** data, 1.6 GB process | |
385
+ | Add formula column `[Taxable] / [Qty]` over all 10 M lines | 0.35 s | |
386
+ | Register totals (distinct invoices, lines, qty, taxable, CGST, SGST, IGST, total) | 0.46 s | 1 |
387
+ | Month × place of supply (GST summary) | 0.32 s | 275 |
388
+ | GSTR-1 style HSN summary (HSN > UoM, qty, taxable, CGST, SGST, IGST) | 0.31 s | 6,001 |
389
+ | GST rate × tax type | 0.25 s | 18 |
390
+ | Invoice-wise register (one row per invoice: lines, taxable, total) | 1.0 s | 363,418 |
391
+ | Customer (20k) × quarter, with distinct invoices | 1.4 s | 163,521 |
392
+ | Item group > item × quarter | 0.25 s | 27,369 |
393
+ | Average of a formula column by item group | 0.14 s | 41 |
394
+ | Credit notes only, customer > invoice | 0.10 s | 19,035 |
395
+ | Karnataka tax invoices only, item detail | 0.08 s | 3,001 |
396
+ | Median line value, salesperson × warehouse | 1.6 s | 156 |
397
+
398
+ Median and distinct count are the heavier aggregates (they cannot be rolled up from subtotals). With the typed-array fast path, median went from 19.8 s to 1.6 s and the register's distinct invoice count from 1.3 s to 0.46 s on this data. The Customer × quarter pivot is too wide for the fast path and still uses the hash route (1.4-2.5 s across runs).
399
+
400
+ Memory scales linearly: about **110 bytes per line for this 26-column table**, so a 32 GB machine holds roughly 250 M such lines in memory. Beyond that use streaming or a server (next section).
401
+
402
+ #### Streaming: 9,997,706 invoices, 275,000,000 line items (55.4 GB CSV)
403
+
404
+ The same register at 27× the size, read with `StreamSource` (`csvFileStream`) so memory stays flat while every pivot re-reads the file. Generate with `node bench/invoice-example.mjs 275e6 --no-load --csv invoices.csv`, then `node bench/invoice-stream.mjs invoices.csv`. Same machine as above, file on a second drive.
405
+
406
+ | Pivot over 275 M lines | Time | Throughput | Process memory |
407
+ | --- | --- | --- | --- |
408
+ | Register totals (lines, qty, taxable, CGST, SGST, IGST, total) ² | 21.2 min | 0.22 M lines/s | 522 MB |
409
+ | Month × place of supply (275 cells) ² | 21.1 min | 0.22 M lines/s | 542 MB |
410
+ | GSTR-1 style HSN summary (6,001 cells) | 17.8 min | 0.26 M lines/s | 540 MB |
411
+ | Credit notes only, GST rate × tax type | 10.5 min | 0.44 M lines/s | 608 MB |
412
+
413
+ ² These two ran while other tests were using the machine, so they are slightly pessimistic.
414
+
415
+ Streaming is bounded by CSV parsing (about 45-55 MB/s on one core), not by the pivot, so memory never grows with the file but each pivot costs a full read; a filter that discards most lines is about twice as fast. For interactive use on data this size, load it once into a server with enough RAM (about 30 GB for these 26 columns) or pre-aggregate; use streaming for scheduled reports and one-off questions.
416
+
417
+ ### Limits worth knowing
418
+
419
+ - An in-memory `Dataset` lives in one tab/process. 10 M rows is comfortable; for more, use a **server** or **streaming** (next section).
420
+ - Result size matters more than input size. Group by something with 5 M distinct values and you'll hit `maxCells`, by design.
421
+ - `distinct` and `median` are not decomposable, so they cost more time and memory than `sum`. They take a fast path (flat typed arrays, a few times faster) while the per-cell state fits roughly 50 MB / 12 M cells, and fall back to hash maps for very wide pivots such as one row per customer with distinct invoices. State is guarded by `maxHolisticEntries` (default 20 M) and fails with a clear `PivotLimitError`.
422
+
423
+ ## Beyond one tab's memory
424
+
425
+ Three ways to go past what a browser tab can hold:
426
+
427
+ **1. Streaming (any file size, bounded memory).** Rows are never stored; every pivot re-reads the source. Memory is proportional to the *result*, not the input.
428
+
429
+ ```js
430
+ import { csvFileStream } from '@mdgs/pivotjet/node';
431
+ const src = await csvFileStream('huge.csv'); // or StreamSource.fromCSV(() => fetch(url))
432
+ const result = await src.compute(spec, { onProgress }); // same PivotResult as an in-memory Dataset
433
+ ```
434
+
435
+ Measured: a 10 M-row, 562 MB CSV pivots in ~26 s with Node limited to 300 MB of heap (in-memory: ~19 s to load once, then ~0.2 s per pivot). Throughput is about 0.4 M rows/s, so 100 M rows is roughly 4+ minutes per pivot (extrapolated, not measured). Streaming does not support drill-through, distinct-count or median.
436
+
437
+ **2. Server.** Load the data once in a Node process and let any browser pivot it remotely. Only the (small) result crosses the network.
438
+
439
+ ```bash
440
+ npx @mdgs/pivotjet serve data.csv --port 8080 --token SECRET --layouts-dir ./layouts
441
+ npx @mdgs/pivotjet serve data.csv --stream # bounded-memory server
442
+ ```
443
+
444
+ ```js
445
+ import { createPivotServer } from '@mdgs/pivotjet/server';
446
+ createPivotServer({ sources: { sales: ds }, token: 'SECRET', cors: true, layouts: { dir: './layouts' } }).listen(8080);
447
+
448
+ // browser
449
+ const remote = await PivotJet.RemoteDataset.connect('http://host:8080', 'sales', { token: 'SECRET' });
450
+ new PivotJet.PivotDesigner('#app', { dataset: remote }); // viewer, designer, charts and export all work
451
+ ```
452
+
453
+ The server holds the rows in *its* RAM, so the practical limit is that machine's memory (or use `--stream`). A client disconnect aborts the computation. Results travel as a compact binary payload and are identical to local results (tested).
454
+
455
+ **3. Pre-aggregate** upstream (SQL, warehouse) and pivot the summary.
456
+
457
+ ## Aggregates
458
+
459
+ `sum | count | avg | min | max | distinct | median`. **distinct** is exact. **median** uses a log-bucket sketch with ~0.1% relative error (exact when values are well separated).
460
+
461
+ ## Calculated fields and values
462
+
463
+ - **Calculated field** (per record, in memory): `ds.addCalculatedField({ name: 'Margin', formula: '([Revenue] - [Cost]) / [Revenue]' })`, then use it like any measure. Also in the designer (+ fx next to Fields).
464
+ - **Calculated value** (on the result, any source including remote and streaming): `{ calc: '[Revenue] / [Orders]', label: 'AOV', format: 'currency' }`, or with aggregates inline: `sum(Revenue) / distinct(Customer)`. Works at every subtotal and grand total, so ratios are correct rather than averaged.
465
+
466
+ Formulas support `+ - * / ( )`, comparison, `abs round floor ceil sqrt ln log10 exp pow min max if iferror`, `[Field With Spaces]`. They are parsed and compiled by a small safe interpreter (no `eval`). Null propagates; divide by zero gives null.
467
+
468
+ ## Charts
469
+
470
+ Column, bar, stacked column/bar, line, area, stacked area, pie, donut, rendered as dependency-free SVG with tooltips, legend toggling and click events.
471
+
472
+ ```js
473
+ new PivotViewer('#app', { dataset: ds, spec, view: 'chart', chart: { type: 'stackedColumn' } }); // or toggle Table/Chart in the designer
474
+ viewer.downloadChartSVG();
475
+ const svg = renderSVG(buildChartModel(result), { type: 'line', inline: true }); // headless
476
+ ```
477
+
478
+ ## Export: CSV, Excel, PDF
479
+
480
+ ```js
481
+ viewer.downloadCSV(); viewer.downloadXLSX(); viewer.downloadPDF({ title: 'Sales' });
482
+ const bytes = toXLSX(result); // Uint8Array, real .xlsx (OOXML), numeric cells with formats
483
+ const pdf = toPDF(result, { locale: 'en-US', pageSize: 'a4', orientation: 'landscape' });
484
+ ```
485
+
486
+ ```bash
487
+ npx @mdgs/pivotjet pivot data.csv --stream --rows Region,Date@year --cols Channel --values sum:Revenue,count --out report.xlsx
488
+ ```
489
+
490
+ Excel is limited to 1,048,576 rows × 16,384 columns (a clear error is thrown beyond that). PDF paginates and splits wide pivots into column bands. PDF number formatting uses the machine's locale unless you pass `locale`.
491
+
492
+ ## Per-cell formatting
493
+
494
+ Rules are plain JSON in `spec.options.cellRules`, so they save with layouts and reports. Each rule picks cells (by value, kind, row/column path, condition) and sets a style, number format or text. Later rules override earlier ones.
495
+
496
+ ```js
497
+ viewer.setCellRules([
498
+ { scope: { value: 'Revenue', kind: 'leaf' }, when: { op: '<', a: 0 }, style: { color: '#9c0006', background: '#ffc7ce', bold: true } },
499
+ { scope: { kind: 'grand' }, style: { bold: true, background: '#e3e9f4' } },
500
+ { scope: { row: ['East', 'Widget'], col: ['2024'], value: 'Revenue', exact: true }, format: { style: 'currency', currency: 'EUR' }, text: 'see note' },
501
+ { when: { op: 'empty' }, text: '–' },
502
+ ]);
503
+ ```
504
+
505
+ | Field | Meaning |
506
+ | --- | --- |
507
+ | `scope.value` | value index or its label / field name (omit = every value) |
508
+ | `scope.kind` | `any` (default), `leaf`, `sub` (subtotals), `grand`, `total` (sub + grand) |
509
+ | `scope.row`, `scope.col` | label path of a row / column; matches that node and everything under it, `exact: true` for only that node, `[]` = grand total |
510
+ | `when` | `{ op, a, b }`, op: `> >= < <= = != between outside empty notempty` |
511
+ | `format` | any number format: preset or Intl options with `prefix` / `suffix` |
512
+ | `text` | literal text shown instead of the number |
513
+ | `style` | `color`, `background`, `bold`, `italic`, `underline`, `align`, `font` (family), `size` (5-96) |
514
+
515
+ Rules apply on screen, in **print**, **Excel** (real cell fills, fonts, number formats) and **PDF** (fills, text colour, bold, italic, underline, font family and size, alignment). In the designer use **Cell formats ▾**, or **right-click any cell** to format just that cell. Use hex or `rgb()`/`hsl()` colours if you need them in Excel/PDF (about 40 CSS colour names are supported); on screen a fill without a text colour gets readable black or white text automatically. CSV always contains raw numbers. A malformed rule fails with `Cell rule #n: ...`.
516
+
517
+ ### PDF fonts
518
+
519
+ The PDF writer knows the 12 standard fonts (Helvetica, Times, Courier x regular/bold/italic/bold-italic; names such as Arial, Georgia, `serif`, `monospace` map to them). Their width tables cover ASCII; other characters use a default width. For any other font, or for non-Latin text, **embed your own TrueType/OpenType file**; TrueType is subset to the characters used, so a report adds only a few kB.
520
+
521
+ ```js
522
+ toPDF(result, { fonts: { Inter: { regular: interBytes, bold: interBoldBytes } }, font: 'Inter' });
523
+ new Viewer(el, { dataset, pdfFonts: { Inter: { regular: bytes } } }); // viewer / designer export
524
+ ```
525
+
526
+ Bold or italic without a matching file falls back to the regular file. Fonts whose licence forbids embedding (restricted `fsType`) are refused with an error. OpenType/CFF (`.otf`) fonts are embedded whole, not subset. On the server: `--pdf-font Inter=Inter.ttf --pdf-font Inter:bold=Inter-Bold.ttf`.
527
+
528
+ ## Print
529
+
530
+ `viewer.print()` prints the **whole** pivot (not just the visible window) plus the chart when it is showing, with per-cell formatting, repeated header rows on every page and your title / subtitle / footer / page size / orientation (`spec.options.print`, saved with layouts and reports). Choose "Save as PDF" in the browser dialog for a file. The designer has **Print ▾**; standalone report pages have a Print button. Headless: `toPrintHTML(result, opts)` / `toHTMLTable(result)` return HTML (also handy for e-mail).
531
+
532
+ ## Reports: publish a pivot, render it later
533
+
534
+ A **report** is one JSON document that holds everything needed to show the pivot again:
535
+
536
+ | Saved | Where |
537
+ | --- | --- |
538
+ | dimensions, values, filters, number formats, calculated **values** | `spec` |
539
+ | calculated **fields** (formula columns on the dataset) | `fields` |
540
+ | per-cell format rules | `spec.options.cellRules` |
541
+ | print setup | `spec.options.print` |
542
+ | table / chart view and chart settings | `spec.options` |
543
+ | expansion, sort, column widths | `state` |
544
+ | locale, title, description, author, source | top level |
545
+ | source column list (documentation) | `schema` |
546
+ | frozen numbers (optional) | `snapshot` |
547
+
548
+ ```js
549
+ const report = viewer.toReport({ title: 'Q4 sales', author: 'Finance' }); // or createReport({ spec, result, fields, state })
550
+ JSON.stringify(report); // save it anywhere
551
+
552
+ renderReport('#app', report); // offline: the frozen snapshot, no server or data
553
+ renderReport('#app', report, { dataset }); // live: recomputes on current data; formula columns are re-created if missing
554
+ ```
555
+
556
+ - **Snapshot** reports show the exact numbers at save time (expand/collapse, sort, chart toggle, print and Excel/PDF/CSV export all work; drill-through needs live data).
557
+ - **Live** reports (no result passed to `createReport`) always show current data. `applyReportFields(dataset, report)` adds the report's formula columns to an in-memory `Dataset`; a server or streamed source cannot add fields, so there the columns must already exist (you get a clear error naming the field and formula).
558
+ - **Standalone page:** one self-contained `.html` file (about 170 kB, no network, with a Print button) that anyone can open or email.
559
+
560
+ From the designer: **Export ▾ → Report file (.json)** or **Standalone page (.html)**. From the CLI:
561
+
562
+ ```bash
563
+ npx @mdgs/pivotjet pivot sales.csv --rows Region --cols Channel --values sum:Revenue --out q4.html --title "Q4 sales"
564
+ npx @mdgs/pivotjet pivot sales.csv --rows Region --values sum:Revenue --out q4.json # report file
565
+ npx @mdgs/pivotjet report q4.json --out q4.html # json -> standalone page
566
+ ```
567
+
568
+ Reports carry a format marker and version; `parseReport()` rejects anything else, including malformed rules, with a clear error.
569
+
570
+ ### Reports stored on the server
571
+
572
+ Start the server with `--reports` (memory) or `--reports-dir ./reports` (files, survive restarts), or `createPivotServer({ reports: { dir } })`. The designer then shows **Reports ▾**: save, open, version history, PDF / Excel download, copy share link, delete.
573
+
574
+ | Endpoint | |
575
+ | --- | --- |
576
+ | `GET /api/:ds/reports` | list |
577
+ | `POST /api/:ds/reports` | `{ report, id?, baseVersion? }` creates, or adds a version |
578
+ | `GET /api/:ds/reports/:id[?version=n]` | load |
579
+ | `GET /api/:ds/reports/:id/versions` | version list |
580
+ | `DELETE /api/:ds/reports/:id` | delete |
581
+ | `GET /api/:ds/reports/:id/export?format=pdf, xlsx, html or json [&live=0/1]` | server-rendered file with the report's cell formats, print setup and fonts (locale defaults to `en-US` unless the report stores one) |
582
+ | `GET /report/:ds/:id` | share page: renders the report in any browser (asks for the token on a protected server) |
583
+
584
+ - Each save is a new **version** (the last 20 are kept). Pass `baseVersion` (the version you edited): if someone saved since, you get HTTP 409 / `ConflictError` instead of an overwrite.
585
+ - Saving a report whose formula columns are missing adds them to the server's in-memory dataset; a streamed source cannot, and the save is refused with a message.
586
+ - The token goes in the `Authorization` header; `?token=` is accepted only on export downloads, so those links open directly.
587
+ - From code: `remoteDataset.reportStore()` (`list/load/save/versions/remove/exportBytes/shareUrl`), `ReportStore` with your own adapter, or `LocalStorageReportStore` in the browser (about 5 MB: save without a snapshot, or use a server).
588
+
589
+ ## Saved layouts
590
+
591
+ The designer has a built-in **Layouts** menu: save, load, set default (auto-applied on start), delete.
592
+
593
+ - Browser default: `localStorage`. `layouts: false` disables it; `layoutsKey` namespaces it.
594
+ - Any backend: `layouts: new RestAdapter('/api/layouts', { token })`, or your own `{ read(), write(state) }` adapter.
595
+ - With `RemoteDataset` against `pivotjet serve`, layouts are stored on the server per dataset (shared between users, optionally as JSON files).
596
+ - Headless: `new LayoutStore(adapter)` with `list / load / save / remove / setDefault / getDefault`.
597
+
598
+ ## Memory option
599
+
600
+ For very large numeric columns, `{ name: 'Revenue', precision: 'single' }` stores the measure as Float32: half the memory, ~7 significant digits.
601
+
602
+ ## Events (viewer & designer)
603
+
604
+ `compute-start`, `compute-end` (result), `cellclick`, `drill`, `toggle`, `sort`, `view`, `chartclick`, `error`; designer adds `change` (spec), `layout-save`, `layout-load`, `field-added`. `on()` returns an unsubscribe function.
605
+
606
+ Double-click a cell (or press Enter on a selected one) to drill into the raw records behind it. Arrow keys move the selection.
607
+
608
+ ## Theming
609
+
610
+ CSS variables on `.mp-root` (`--mp-bg`, `--mp-fg`, `--mp-accent`, `--mp-line`, …). `theme: 'light' | 'dark' | 'auto'` follows `prefers-color-scheme`. Styles are injected automatically; there is no CSS file to import.
611
+
612
+ ## Develop
613
+
614
+ ```bash
615
+ npm test # engine + CSV tests (node --test)
616
+ npm run bench # 10M-row benchmark
617
+ npm run build # dist/ (CJS + minified browser bundle)
618
+ npm run demo # http://localhost:5173/demo/ (generate 100k-10M rows, try the designer)
619
+ ```
620
+
621
+ ## Publish
622
+
623
+ ```bash
624
+ npm login
625
+ npm publish # runs tests + build via prepublishOnly; scope is public
626
+ ```
627
+
628
+ MIT