@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 +21 -0
- package/README.md +628 -3
- package/bin/pivotjet.mjs +122 -0
- package/dist/core.cjs +4926 -0
- package/dist/core.cjs.map +7 -0
- package/dist/index.cjs +7277 -0
- package/dist/index.cjs.map +7 -0
- package/dist/pivotjet.min.js +334 -0
- package/dist/pivotjet.min.js.map +7 -0
- package/docs/images/cell-formats.png +0 -0
- package/docs/images/chart.png +0 -0
- package/docs/images/configure-fields.png +0 -0
- package/docs/images/designer.png +0 -0
- package/docs/images/large-dataset.png +0 -0
- package/package.json +108 -4
- package/src/cellfmt.js +218 -0
- package/src/chart.js +595 -0
- package/src/core.d.ts +424 -0
- package/src/core.js +18 -0
- package/src/csv.js +198 -0
- package/src/dataset.js +404 -0
- package/src/designer.js +995 -0
- package/src/elements.js +50 -0
- package/src/engine.js +778 -0
- package/src/errors.js +2 -0
- package/src/export.js +775 -0
- package/src/expr.js +180 -0
- package/src/format.js +42 -0
- package/src/holistic.js +237 -0
- package/src/index.d.ts +155 -0
- package/src/index.js +6 -0
- package/src/layouts.js +105 -0
- package/src/node.d.ts +10 -0
- package/src/node.js +29 -0
- package/src/pdffont.js +361 -0
- package/src/remote.js +164 -0
- package/src/report-render.js +31 -0
- package/src/report.js +103 -0
- package/src/reportstore.js +135 -0
- package/src/server.d.ts +20 -0
- package/src/server.js +272 -0
- package/src/stream.js +285 -0
- package/src/styles.js +162 -0
- package/src/util.js +73 -0
- package/src/viewer.js +632 -0
package/src/server.js
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// Node-only: serve one or more datasets over HTTP so browsers (RemoteDataset) can pivot data far larger
|
|
2
|
+
// than a browser tab can hold. Zero dependencies (node:http, node:zlib).
|
|
3
|
+
//
|
|
4
|
+
// import { Dataset } from '@mdgs/pivotjet/core';
|
|
5
|
+
// import { createPivotServer } from '@mdgs/pivotjet/server';
|
|
6
|
+
// createPivotServer({ sources: { sales: ds }, token: 'secret' }).listen(8080);
|
|
7
|
+
//
|
|
8
|
+
// Endpoints (JSON): GET /api/sources · GET /api/:n/schema · POST /api/:n/pivot|distinct|drill
|
|
9
|
+
// `GET /` serves a ready-made designer UI that talks to this server.
|
|
10
|
+
|
|
11
|
+
import http from 'node:http';
|
|
12
|
+
import zlib from 'node:zlib';
|
|
13
|
+
import { readFile, writeFile, mkdir, readdir, rm } from 'node:fs/promises';
|
|
14
|
+
import { readFileSync } from 'node:fs';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { serializeResult } from './remote.js';
|
|
17
|
+
import { drillByPath, PivotError, PivotLimitError } from './engine.js';
|
|
18
|
+
import { FormulaError } from './expr.js';
|
|
19
|
+
import { ReportStore, MemoryReportAdapter, REPORT_ID } from './reportstore.js';
|
|
20
|
+
import { parseReport, createReport, applyReportFields } from './report.js';
|
|
21
|
+
import { deserializeResult } from './remote.js';
|
|
22
|
+
import { toXLSX, toPDF } from './export.js';
|
|
23
|
+
import { reportToHTMLFile } from './node.js';
|
|
24
|
+
|
|
25
|
+
const MAX_BODY = 1_000_000;
|
|
26
|
+
|
|
27
|
+
/** One JSON file per report under dir/<dataset>/<id>.json (written via a temp file so a crash never leaves half a report). */
|
|
28
|
+
class FileReportAdapter {
|
|
29
|
+
constructor(dir) { this.dir = dir; }
|
|
30
|
+
_f(id) { return join(this.dir, `${id}.json`); }
|
|
31
|
+
async get(id) { try { return JSON.parse(await readFile(this._f(id), 'utf8')); } catch { return null; } }
|
|
32
|
+
async put(id, doc) { await mkdir(this.dir, { recursive: true }); const t = this._f(id) + `.${process.pid}.tmp`; await writeFile(t, JSON.stringify(doc)); const { rename } = await import('node:fs/promises'); await rename(t, this._f(id)); }
|
|
33
|
+
async del(id) { await rm(this._f(id), { force: true }); }
|
|
34
|
+
async all() {
|
|
35
|
+
let names = [];
|
|
36
|
+
try { names = await readdir(this.dir); } catch { return []; }
|
|
37
|
+
const out = [];
|
|
38
|
+
for (const n of names) if (n.endsWith('.json')) { const d = await this.get(n.slice(0, -5)); if (d) out.push(d); }
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function readBody(req, max = MAX_BODY) {
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
let size = 0; const parts = [];
|
|
46
|
+
req.on('data', (c) => { size += c.length; if (size > max) { reject(new PivotError('Request too large')); req.destroy(); } else parts.push(c); });
|
|
47
|
+
req.on('end', () => { try { resolve(parts.length ? JSON.parse(Buffer.concat(parts).toString('utf8')) : {}); } catch { reject(new PivotError('Invalid JSON body')); } });
|
|
48
|
+
req.on('error', reject);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function send(req, res, status, data, headers = {}) {
|
|
53
|
+
const body = Buffer.from(typeof data === 'string' ? data : JSON.stringify(data));
|
|
54
|
+
const h = { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...headers };
|
|
55
|
+
if (body.length > 1024 && /\bgzip\b/.test(req.headers['accept-encoding'] || '')) {
|
|
56
|
+
h['content-encoding'] = 'gzip';
|
|
57
|
+
res.writeHead(status, h);
|
|
58
|
+
res.end(zlib.gzipSync(body, { level: 1 }));
|
|
59
|
+
} else { res.writeHead(status, h); res.end(body); }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const jsonInScript = (v) => JSON.stringify(v).replace(/</g, '\\u003c');
|
|
63
|
+
/** Shareable page: opens a saved report live from this server (falls back to its snapshot), with PDF / Excel / Print. */
|
|
64
|
+
const REPORT_PAGE = (name, id) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
65
|
+
<title>PivotJet report</title><style>html,body{height:100%;margin:0}body{display:flex;flex-direction:column;padding:12px 14px;box-sizing:border-box;gap:8px;font-family:system-ui,sans-serif}
|
|
66
|
+
.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}h1{font-size:18px;margin:0;flex:1}.meta{font-size:12px;color:#6b7280}button{font:inherit;padding:4px 10px;cursor:pointer}
|
|
67
|
+
#app{flex:1;min-height:0}#app .mp-root{height:100%}.err{color:#b91c1c;padding:12px}@media print{.bar button{display:none}}</style></head>
|
|
68
|
+
<body><div class="bar"><h1 id="t">Loading…</h1><span class="meta" id="m"></span><button id="mode" style="display:none"></button><button id="pdf">PDF</button><button id="xlsx">Excel</button><button id="print">Print</button></div><div id="app"></div>
|
|
69
|
+
<script src="/pivotjet.js"></script><script>
|
|
70
|
+
const N = ${jsonInScript(name)}, ID = ${jsonInScript(id)};
|
|
71
|
+
let token = new URLSearchParams(location.search).get('token') || sessionStorage.getItem('pj-token') || undefined, viewer, report, ds, live = true;
|
|
72
|
+
const store = () => new PivotJet.RestReportStore(location.origin + '/api/' + encodeURIComponent(N) + '/reports', { token });
|
|
73
|
+
const fail = (m) => { document.getElementById('app').innerHTML = '<div class="err"></div>'; document.querySelector('.err').textContent = m; document.getElementById('t').textContent = 'Report unavailable'; };
|
|
74
|
+
async function show() {
|
|
75
|
+
document.getElementById('app').innerHTML = '';
|
|
76
|
+
try {
|
|
77
|
+
viewer = live ? PivotJet.renderReport('#app', report, { dataset: ds }) : PivotJet.renderReport('#app', report, { mode: 'snapshot' });
|
|
78
|
+
viewer.on('error', (e) => { if (live && report.snapshot) { live = false; show(); } else fail(e.message); });
|
|
79
|
+
} catch (e) { if (live && report.snapshot) { live = false; return show(); } fail(e.message); }
|
|
80
|
+
const b = document.getElementById('mode'); b.style.display = report.snapshot ? '' : 'none'; b.textContent = live ? 'Show saved snapshot' : 'Show live data';
|
|
81
|
+
document.getElementById('m').textContent = live ? 'Live data' : 'Snapshot' + (report.snapshot ? ' of ' + new Date(report.snapshot.at).toLocaleString() : '');
|
|
82
|
+
}
|
|
83
|
+
async function start() {
|
|
84
|
+
try {
|
|
85
|
+
report = await store().load(ID);
|
|
86
|
+
if (!report) return fail('Report not found');
|
|
87
|
+
document.getElementById('t').textContent = report.title; document.title = report.title;
|
|
88
|
+
ds = await PivotJet.RemoteDataset.connect(location.origin, N, { token });
|
|
89
|
+
await show();
|
|
90
|
+
} catch (e) {
|
|
91
|
+
if (/token/i.test(e.message) && !token) { token = prompt('Access token'); if (token) { sessionStorage.setItem('pj-token', token); return start(); } }
|
|
92
|
+
fail(e.message);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
document.getElementById('mode').onclick = () => { live = !live; show(); };
|
|
96
|
+
document.getElementById('print').onclick = () => viewer && viewer.print();
|
|
97
|
+
for (const f of ['pdf', 'xlsx']) document.getElementById(f).onclick = async () => {
|
|
98
|
+
try { PivotJet.downloadBlob(await store().exportBytes(ID, f, { live }), (report.title || 'report').replace(/[^\\w -]+/g, '') + '.' + f, f === 'pdf' ? 'application/pdf' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); }
|
|
99
|
+
catch (e) { alert(e.message); }
|
|
100
|
+
};
|
|
101
|
+
start();
|
|
102
|
+
</script></body></html>`;
|
|
103
|
+
|
|
104
|
+
const PAGE = (name) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
105
|
+
<title>PivotJet – ${name}</title><style>html,body{height:100%;margin:0}body{padding:10px;box-sizing:border-box;font-family:system-ui}#app{height:100%}#app .mp-root{height:100%}</style></head>
|
|
106
|
+
<body><div id="app"></div><script src="/pivotjet.js"></script><script>
|
|
107
|
+
const t = new URLSearchParams(location.search).get('token');
|
|
108
|
+
PivotJet.RemoteDataset.connect(location.origin, ${JSON.stringify(name)}, { token: t || undefined }).then(ds => {
|
|
109
|
+
const info = ds.fieldInfo();
|
|
110
|
+
const dims = info.filter(f => f.isDimension && !f.isMeasure && (f.cardinality ?? 0) < 200);
|
|
111
|
+
const meas = info.filter(f => f.isMeasure);
|
|
112
|
+
new PivotJet.PivotDesigner('#app', { dataset: ds, spec: { rows: dims.slice(0, 1).map(f => ({ field: f.name })), values: meas.slice(0, 1).map(f => ({ field: f.name, agg: 'sum' })) } });
|
|
113
|
+
}).catch(e => { document.body.textContent = 'Could not connect: ' + e.message; });
|
|
114
|
+
</script></body></html>`;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* @param {{sources: Record<string, object>, token?: string, cors?: boolean|string, maxCells?: number,
|
|
118
|
+
* layouts?: boolean|{dir?:string}, reports?: boolean|{dir?:string, keepVersions?:number, maxBytes?:number},
|
|
119
|
+
* fonts?: Record<string,{regular?:string|Uint8Array,bold?:string|Uint8Array,italic?:string|Uint8Array,boldItalic?:string|Uint8Array}>}} opts layouts: persist saved designer layouts per dataset (in memory, or as JSON files in `dir`)
|
|
120
|
+
* sources: name -> Dataset | StreamSource (anything with fieldInfo/compute/distinct)
|
|
121
|
+
* @returns {http.Server} (call .listen(port))
|
|
122
|
+
*/
|
|
123
|
+
export function createPivotServer(opts) {
|
|
124
|
+
const sources = opts.sources || {};
|
|
125
|
+
const names = Object.keys(sources);
|
|
126
|
+
// fonts for server-side PDF export: values may be file paths (read once at start-up) or bytes
|
|
127
|
+
const fonts = {};
|
|
128
|
+
for (const [fam, styles] of Object.entries(opts.fonts || {})) {
|
|
129
|
+
fonts[fam] = {};
|
|
130
|
+
for (const [k, v] of Object.entries(styles)) fonts[fam][k] = typeof v === 'string' ? new Uint8Array(readFileSync(v)) : v;
|
|
131
|
+
}
|
|
132
|
+
const reportOpts = opts.reports && typeof opts.reports === 'object' ? opts.reports : {};
|
|
133
|
+
const maxReport = reportOpts.maxBytes || 25_000_000;
|
|
134
|
+
const stores = new Map();
|
|
135
|
+
const reportStore = (n) => {
|
|
136
|
+
let st = stores.get(n);
|
|
137
|
+
if (!st) {
|
|
138
|
+
const adapter = reportOpts.dir ? new FileReportAdapter(join(reportOpts.dir, n.replace(/[^\w.-]/g, '_'))) : new MemoryReportAdapter();
|
|
139
|
+
st = new ReportStore(adapter, {
|
|
140
|
+
keepVersions: reportOpts.keepVersions || 20,
|
|
141
|
+
// reject malformed reports and make sure the report's formula columns exist on the (in-memory) dataset
|
|
142
|
+
validate: (report) => { parseReport(report); applyReportFields(sources[n], report); },
|
|
143
|
+
});
|
|
144
|
+
stores.set(n, st);
|
|
145
|
+
}
|
|
146
|
+
return st;
|
|
147
|
+
};
|
|
148
|
+
const exportReport = async (src, report, format, live, signal) => {
|
|
149
|
+
const o = report.spec.options || {}, print = o.print || {};
|
|
150
|
+
let result = null;
|
|
151
|
+
if (live !== false) {
|
|
152
|
+
try { applyReportFields(src, report); result = await src.compute(report.spec, { signal, maxCells: opts.maxCells }); }
|
|
153
|
+
catch (e) { if (live === true || !report.snapshot || (e && e.name === 'AbortError')) throw e; }
|
|
154
|
+
}
|
|
155
|
+
if (!result) {
|
|
156
|
+
if (!report.snapshot) throw new PivotError('This report has no snapshot');
|
|
157
|
+
result = deserializeResult(report.snapshot.result);
|
|
158
|
+
}
|
|
159
|
+
const common = { rules: o.cellRules, locale: report.locale || 'en-US' }; // never the server's own locale: exports must not change with where they run
|
|
160
|
+
if (format === 'xlsx') return { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ext: 'xlsx', body: Buffer.from(toXLSX(result, { ...common, subtotals: print.subtotals })) };
|
|
161
|
+
if (format === 'pdf') {
|
|
162
|
+
return { type: 'application/pdf', ext: 'pdf', body: Buffer.from(toPDF(result, { ...common, title: print.title || report.title, subtitle: print.subtitle || report.description, footer: print.footer, pageSize: print.pageSize, orientation: print.orientation, font: print.font, fonts, subtotals: print.subtotals })) };
|
|
163
|
+
}
|
|
164
|
+
if (format === 'html') {
|
|
165
|
+
const snap = createReport({ title: report.title, description: report.description, author: report.author, spec: report.spec, result, fields: report.fields, schema: report.schema, state: report.state, locale: report.locale });
|
|
166
|
+
return { type: 'text/html; charset=utf-8', ext: 'html', body: Buffer.from(await reportToHTMLFile(snap)) };
|
|
167
|
+
}
|
|
168
|
+
if (format === 'json') return { type: 'application/json', ext: 'json', body: Buffer.from(JSON.stringify(report)) };
|
|
169
|
+
throw new PivotError('format must be pdf, xlsx, html or json');
|
|
170
|
+
};
|
|
171
|
+
const layoutMem = new Map();
|
|
172
|
+
const layoutDir = opts.layouts && opts.layouts.dir;
|
|
173
|
+
const layoutFile = (n) => join(layoutDir, `${n.replace(/[^\w.-]/g, '_')}.layouts.json`);
|
|
174
|
+
const readLayouts = async (n) => {
|
|
175
|
+
if (layoutDir) { try { return JSON.parse(await readFile(layoutFile(n), 'utf8')); } catch { return { layouts: [], defaultId: null }; } }
|
|
176
|
+
return layoutMem.get(n) || { layouts: [], defaultId: null };
|
|
177
|
+
};
|
|
178
|
+
const writeLayouts = async (n, state) => {
|
|
179
|
+
if (layoutDir) { await mkdir(layoutDir, { recursive: true }); await writeFile(layoutFile(n), JSON.stringify(state)); } else layoutMem.set(n, state);
|
|
180
|
+
};
|
|
181
|
+
return http.createServer(async (req, res) => {
|
|
182
|
+
const cors = opts.cors ? { 'access-control-allow-origin': opts.cors === true ? '*' : opts.cors, 'access-control-allow-headers': 'content-type, authorization', 'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS' } : {};
|
|
183
|
+
const ac = new AbortController();
|
|
184
|
+
res.on('close', () => { if (!res.writableEnded) ac.abort(); });
|
|
185
|
+
try {
|
|
186
|
+
const url = new URL(req.url, 'http://x');
|
|
187
|
+
if (req.method === 'OPTIONS') { res.writeHead(204, cors); return res.end(); }
|
|
188
|
+
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/pivotjet.js')) {
|
|
189
|
+
if (url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...cors }); return res.end(PAGE(names[0] || 'data')); }
|
|
190
|
+
try {
|
|
191
|
+
const js = await readFile(new URL('../dist/pivotjet.min.js', import.meta.url));
|
|
192
|
+
res.writeHead(200, { 'content-type': 'text/javascript', ...cors }); return res.end(js);
|
|
193
|
+
} catch { res.writeHead(404); return res.end('dist/pivotjet.min.js not built (run npm run build)'); }
|
|
194
|
+
}
|
|
195
|
+
const parts = url.pathname.split('/').filter(Boolean).map(decodeURIComponent);
|
|
196
|
+
if (req.method === 'GET' && parts[0] === 'report' && parts.length === 3 && opts.reports) {
|
|
197
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...cors }); return res.end(REPORT_PAGE(parts[1], parts[2]));
|
|
198
|
+
}
|
|
199
|
+
// downloads may carry ?token= (explicit user choice for plain links); everything else needs the header
|
|
200
|
+
const queryOk = req.method === 'GET' && parts[2] === 'reports' && parts[4] === 'export' && url.searchParams.get('token') === opts.token;
|
|
201
|
+
if (opts.token && req.headers.authorization !== `Bearer ${opts.token}` && !queryOk) {
|
|
202
|
+
return send(req, res, 401, { error: { name: 'Unauthorized', message: 'Missing or invalid token' } }, cors);
|
|
203
|
+
}
|
|
204
|
+
if (parts[0] !== 'api') { res.writeHead(404, cors); return res.end('not found'); }
|
|
205
|
+
if (parts[1] === 'sources' && req.method === 'GET') return send(req, res, 200, names.map((n) => ({ name: n, rowCount: sources[n].rowCount ?? null })), cors);
|
|
206
|
+
const src = sources[parts[1]];
|
|
207
|
+
if (!src) return send(req, res, 404, { error: { name: 'NotFound', message: `Unknown dataset "${parts[1]}"` } }, cors);
|
|
208
|
+
const action = parts[2];
|
|
209
|
+
if (action === 'schema' && req.method === 'GET') {
|
|
210
|
+
return send(req, res, 200, { rowCount: src.rowCount ?? null, fields: src.fieldInfo(), supportsDrill: !!src.byName, supportsLayouts: !!opts.layouts, supportsReports: !!opts.reports }, cors);
|
|
211
|
+
}
|
|
212
|
+
if (action === 'reports' && opts.reports) {
|
|
213
|
+
const store = reportStore(parts[1]), id = parts[3], sub = parts[4];
|
|
214
|
+
if (id !== undefined && !REPORT_ID.test(id)) throw new PivotError('Invalid report id');
|
|
215
|
+
if (!id) {
|
|
216
|
+
if (req.method === 'GET') return send(req, res, 200, await store.list(), cors);
|
|
217
|
+
if (req.method === 'POST') {
|
|
218
|
+
const b = await readBody(req, maxReport);
|
|
219
|
+
if (!b || typeof b.report !== 'object') throw new PivotError('Body must be { report, id?, baseVersion? }');
|
|
220
|
+
return send(req, res, 200, await store.save(b.report, { id: b.id || undefined, baseVersion: b.baseVersion }), cors);
|
|
221
|
+
}
|
|
222
|
+
} else if (!sub) {
|
|
223
|
+
if (req.method === 'GET') {
|
|
224
|
+
const r = await store.load(id, { version: url.searchParams.get('version') ?? undefined });
|
|
225
|
+
return r ? send(req, res, 200, r, cors) : send(req, res, 404, { error: { name: 'NotFoundError', message: `No report ${id}` } }, cors);
|
|
226
|
+
}
|
|
227
|
+
if (req.method === 'DELETE') { await store.remove(id); return send(req, res, 200, { ok: true }, cors); }
|
|
228
|
+
} else if (sub === 'versions' && req.method === 'GET') return send(req, res, 200, await store.versions(id), cors);
|
|
229
|
+
else if (sub === 'export' && req.method === 'GET') {
|
|
230
|
+
const report = await store.load(id, { version: url.searchParams.get('version') ?? undefined });
|
|
231
|
+
if (!report) return send(req, res, 404, { error: { name: 'NotFoundError', message: `No report ${id}` } }, cors);
|
|
232
|
+
const lv = url.searchParams.get('live');
|
|
233
|
+
const out = await exportReport(src, report, url.searchParams.get('format') || 'pdf', lv === null ? undefined : lv !== '0', ac.signal);
|
|
234
|
+
const fname = (report.title || 'report').replace(/[^\w -]+/g, '').trim().replace(/\s+/g, '-') || 'report';
|
|
235
|
+
res.writeHead(200, { 'content-type': out.type, 'content-disposition': `attachment; filename="${fname}.${out.ext}"`, 'cache-control': 'no-store', ...cors });
|
|
236
|
+
return res.end(out.body);
|
|
237
|
+
}
|
|
238
|
+
return send(req, res, 405, { error: { name: 'MethodNotAllowed', message: 'Unsupported method for this endpoint' } }, cors);
|
|
239
|
+
}
|
|
240
|
+
if (action === 'layouts' && opts.layouts) {
|
|
241
|
+
if (req.method === 'GET') return send(req, res, 200, await readLayouts(parts[1]), cors);
|
|
242
|
+
if (req.method === 'PUT') {
|
|
243
|
+
const st = await readBody(req);
|
|
244
|
+
if (!st || !Array.isArray(st.layouts)) throw new PivotError('Invalid layouts payload');
|
|
245
|
+
await writeLayouts(parts[1], { layouts: st.layouts.slice(0, 500), defaultId: st.defaultId || null });
|
|
246
|
+
return send(req, res, 200, { ok: true }, cors);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (req.method !== 'POST') return send(req, res, 405, { error: { name: 'MethodNotAllowed', message: 'Use POST' } }, cors);
|
|
250
|
+
const body = await readBody(req);
|
|
251
|
+
if (action === 'pivot') {
|
|
252
|
+
const result = await src.compute(body.spec || {}, { signal: ac.signal, maxCells: Math.min(body.maxCells || opts.maxCells || 2_000_000, opts.maxCells || 2_000_000) });
|
|
253
|
+
return send(req, res, 200, serializeResult(result), cors);
|
|
254
|
+
}
|
|
255
|
+
if (action === 'distinct') {
|
|
256
|
+
return send(req, res, 200, await src.distinct(body.field, { search: body.search || '', limit: Math.min(body.limit || 500, 2000) }), cors);
|
|
257
|
+
}
|
|
258
|
+
if (action === 'drill') {
|
|
259
|
+
if (!src.byName) throw new PivotError('Drill-through is not available for this dataset');
|
|
260
|
+
const out = await drillByPath(src, body.spec || {}, body.rowPath || [], body.colPath || [], { limit: Math.min(body.limit || 200, 5000), signal: ac.signal });
|
|
261
|
+
return send(req, res, 200, out, cors);
|
|
262
|
+
}
|
|
263
|
+
return send(req, res, 404, { error: { name: 'NotFound', message: 'Unknown endpoint' } }, cors);
|
|
264
|
+
} catch (e) {
|
|
265
|
+
if (e && e.name === 'AbortError') return;
|
|
266
|
+
const status = (e && e.status) || null;
|
|
267
|
+
const client = e instanceof PivotError || e instanceof PivotLimitError || e instanceof FormulaError || (e && /^Unknown field/.test(e.message || ''));
|
|
268
|
+
if (!res.headersSent) send(req, res, status || (client ? 400 : 500), { error: { name: e.name || 'Error', message: client ? e.message : 'Internal error', ...(e && e.current !== undefined ? { current: e.current } : {}) } }, cors);
|
|
269
|
+
if (!client) console.error(e);
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
}
|
package/src/stream.js
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
// Streaming pivot: aggregate an arbitrarily large (async) stream of rows with memory proportional to
|
|
2
|
+
// the *result*, not the input. This is how you pivot 100M+ rows (e.g. a multi-GB CSV) without a
|
|
3
|
+
// 100M-row in-memory Dataset. Trade-offs vs. an in-memory Dataset: each pivot change re-reads the
|
|
4
|
+
// source, and drill-through, distinct count and median are not available.
|
|
5
|
+
|
|
6
|
+
import { Dataset, compareValues } from './dataset.js';
|
|
7
|
+
import { normalizeSpec, finishPivot, CellStore, buildLayout, PivotError, PivotLimitError } from './engine.js';
|
|
8
|
+
import { csvHead, csvBatches, inferFields } from './csv.js';
|
|
9
|
+
import { Slicer, now } from './util.js';
|
|
10
|
+
|
|
11
|
+
const R22 = 4194304; // 2^22 : max distinct values per dimension / leaf tuples per axis
|
|
12
|
+
const MAX_SAFE = Number.MAX_SAFE_INTEGER;
|
|
13
|
+
const pad = (n) => (n < 10 ? '0' + n : '' + n);
|
|
14
|
+
|
|
15
|
+
function bucketOf(ms, bucket) {
|
|
16
|
+
const d = new Date(ms);
|
|
17
|
+
const y = d.getUTCFullYear(), m = d.getUTCMonth() + 1, day = d.getUTCDate();
|
|
18
|
+
if (bucket === 'year') return [y, String(y)];
|
|
19
|
+
if (bucket === 'quarter') { const q = Math.ceil(m / 3); return [y * 10 + q, `${y} Q${q}`]; }
|
|
20
|
+
if (bucket === 'month') return [y * 100 + m, `${y}-${pad(m)}`];
|
|
21
|
+
return [y * 10000 + m * 100 + day, `${y}-${pad(m)}-${pad(day)}`];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function toNumber(v) {
|
|
25
|
+
let x;
|
|
26
|
+
if (typeof v === 'number') x = v;
|
|
27
|
+
else if (v == null || v === '') return NaN;
|
|
28
|
+
else if (v instanceof Date) x = v.getTime();
|
|
29
|
+
else if (typeof v === 'boolean') x = v ? 1 : 0;
|
|
30
|
+
else x = Number(v);
|
|
31
|
+
return x - x !== 0 ? NaN : x;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {AsyncIterable<any[]>|Iterable<any[]>} source batches of rows (objects, or arrays when opts.positional)
|
|
36
|
+
* @param {Array<string|object>|null} fields field definitions (same shape as Dataset); null = keys of first row
|
|
37
|
+
* @param {object} spec pivot spec (same as computePivot)
|
|
38
|
+
* @param {{positional?:boolean,signal?:AbortSignal,onProgress?:(p:number,info?:object)=>void,maxCells?:number,
|
|
39
|
+
* totalRows?:number,progressFn?:()=>number,sliceMs?:number}} [opts]
|
|
40
|
+
*/
|
|
41
|
+
export async function computePivotStream(source, fields, spec, opts = {}) {
|
|
42
|
+
const t0 = now();
|
|
43
|
+
const positional = !!opts.positional;
|
|
44
|
+
const it = source[Symbol.asyncIterator] ? source[Symbol.asyncIterator]() : source[Symbol.iterator]();
|
|
45
|
+
let firstStep = await it.next();
|
|
46
|
+
const firstBatch = firstStep.done ? [] : firstStep.value;
|
|
47
|
+
|
|
48
|
+
const schema = new Dataset(fields && fields.length ? fields : null);
|
|
49
|
+
if (!schema.fields.length) {
|
|
50
|
+
if (!firstBatch.length || positional) throw new PivotError('Stream needs field definitions');
|
|
51
|
+
schema._defineFields(Object.keys(firstBatch[0]));
|
|
52
|
+
}
|
|
53
|
+
schema._inferFrom((f, i) => (i < firstBatch.length ? (positional ? firstBatch[i][f.index] : firstBatch[i][f.name]) : null), Math.min(firstBatch.length, 1000));
|
|
54
|
+
|
|
55
|
+
const ns = normalizeSpec(schema, spec);
|
|
56
|
+
for (const v of ns.allValues) {
|
|
57
|
+
if (!v.isCalc && (v.agg === 'distinct' || v.agg === 'median')) throw new PivotError(`${v.agg} is not available for streamed data: load the data into a Dataset (or a server) instead`);
|
|
58
|
+
}
|
|
59
|
+
const maxCells = opts.maxCells ?? ns.options.maxCells ?? 2_000_000;
|
|
60
|
+
const layout = buildLayout(ns.allValues);
|
|
61
|
+
const accs = layout.accs;
|
|
62
|
+
const S = layout.S;
|
|
63
|
+
|
|
64
|
+
const getter = (f) => (positional ? (r) => r[f.index] : (r) => r[f.name]);
|
|
65
|
+
const mkDim = (d) => {
|
|
66
|
+
const f = schema.getField(d.field);
|
|
67
|
+
return { spec: d, f, get: getter(f), bucket: d.bucket || null, gm: new Map([[null, 0]]), values: [null], labels: ['(blank)'], keys: [Infinity] };
|
|
68
|
+
};
|
|
69
|
+
const rowDims = ns.rows.map(mkDim), colDims = ns.cols.map(mkDim);
|
|
70
|
+
const gidOf = (dim, raw) => {
|
|
71
|
+
if (raw == null || raw === '') return 0;
|
|
72
|
+
const cv = dim.f.coerce(raw);
|
|
73
|
+
if (cv === null) return 0;
|
|
74
|
+
if (dim.bucket) {
|
|
75
|
+
const [key, label] = bucketOf(cv, dim.bucket);
|
|
76
|
+
let g = dim.gm.get(key);
|
|
77
|
+
if (g === undefined) {
|
|
78
|
+
g = dim.labels.length;
|
|
79
|
+
if (g >= R22) throw new PivotLimitError(`"${dim.spec.label}" has too many distinct values to group by`);
|
|
80
|
+
dim.labels.push(label); dim.keys.push(key); dim.gm.set(key, g);
|
|
81
|
+
}
|
|
82
|
+
return g;
|
|
83
|
+
}
|
|
84
|
+
let g = dim.gm.get(cv);
|
|
85
|
+
if (g === undefined) {
|
|
86
|
+
g = dim.values.length;
|
|
87
|
+
if (g >= R22) throw new PivotLimitError(`"${dim.spec.label}" has too many distinct values to group by`);
|
|
88
|
+
dim.values.push(cv); dim.gm.set(cv, g);
|
|
89
|
+
}
|
|
90
|
+
return g;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
// filters
|
|
94
|
+
const flt = ns.filters.filter((x) => x.include || x.exclude).map((x) => {
|
|
95
|
+
const f = schema.getField(x.field);
|
|
96
|
+
if (!f.dim) throw new PivotError(`Cannot filter on "${x.field}"`);
|
|
97
|
+
const set = new Set();
|
|
98
|
+
for (const raw of x.include || x.exclude) set.add(raw == null || raw === '' ? null : f.coerce(raw));
|
|
99
|
+
return { f, get: getter(f), set, include: !!x.include };
|
|
100
|
+
});
|
|
101
|
+
const accGet = accs.map((a) => getter(schema.getField(a.field)));
|
|
102
|
+
|
|
103
|
+
// leaf tuple interning: (parentLeafId, gid) -> leafId, so no radix is needed before cardinalities are known
|
|
104
|
+
const mkAxis = (n) => ({ n, intern: Array.from({ length: Math.max(0, n - 1) }, () => new Map()), par: Array.from({ length: n }, () => []), gd: Array.from({ length: n }, () => []) });
|
|
105
|
+
const rowAx = mkAxis(rowDims.length), colAx = mkAxis(colDims.length);
|
|
106
|
+
const leafOf = (ax, dims, row) => {
|
|
107
|
+
if (!ax.n) return 0;
|
|
108
|
+
let id = gidOf(dims[0], dims[0].get(row));
|
|
109
|
+
for (let k = 1; k < ax.n; k++) {
|
|
110
|
+
const g = gidOf(dims[k], dims[k].get(row));
|
|
111
|
+
const key = id * R22 + g;
|
|
112
|
+
let nid = ax.intern[k - 1].get(key);
|
|
113
|
+
if (nid === undefined) {
|
|
114
|
+
nid = ax.intern[k - 1].size;
|
|
115
|
+
if (nid >= R22) throw new PivotLimitError('Too many distinct row/column combinations');
|
|
116
|
+
ax.intern[k - 1].set(key, nid); ax.par[k].push(id); ax.gd[k].push(g);
|
|
117
|
+
}
|
|
118
|
+
id = nid;
|
|
119
|
+
}
|
|
120
|
+
return id;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const store = new CellStore(layout, 4096, false);
|
|
124
|
+
const slicer = new Slicer({ signal: opts.signal, sliceMs: opts.sliceMs, onProgress: opts.onProgress && ((p) => opts.onProgress(p, { rows: nRows })) });
|
|
125
|
+
let nRows = 0, matched = 0, lastKey = -1, lastSlot = 0;
|
|
126
|
+
const xs = new Float64Array(accs.length);
|
|
127
|
+
|
|
128
|
+
const consume = async (batch) => {
|
|
129
|
+
let data = store.data;
|
|
130
|
+
outer:
|
|
131
|
+
for (let r = 0; r < batch.length; r++) {
|
|
132
|
+
const row = batch[r];
|
|
133
|
+
nRows++;
|
|
134
|
+
for (let f = 0; f < flt.length; f++) {
|
|
135
|
+
const raw = flt[f].get(row);
|
|
136
|
+
const v = raw == null || raw === '' ? null : flt[f].f.coerce(raw);
|
|
137
|
+
if (flt[f].set.has(v) !== flt[f].include) continue outer;
|
|
138
|
+
}
|
|
139
|
+
const key = leafOf(rowAx, rowDims, row) * R22 + leafOf(colAx, colDims, row);
|
|
140
|
+
let slot;
|
|
141
|
+
if (key === lastKey) slot = lastSlot;
|
|
142
|
+
else {
|
|
143
|
+
slot = store.map.get(key);
|
|
144
|
+
if (slot === undefined) {
|
|
145
|
+
slot = store.slot(key);
|
|
146
|
+
data = store.data;
|
|
147
|
+
if (store.count > maxCells) throw new PivotLimitError(`Pivot would exceed ${maxCells.toLocaleString()} cells. Use fewer / coarser dimensions or add filters.`);
|
|
148
|
+
}
|
|
149
|
+
lastKey = key; lastSlot = slot;
|
|
150
|
+
}
|
|
151
|
+
const b = slot * S;
|
|
152
|
+
data[b] += 1;
|
|
153
|
+
for (let a = 0; a < accs.length; a++) {
|
|
154
|
+
const x = toNumber(accGet[a](row));
|
|
155
|
+
if (x === x) {
|
|
156
|
+
const A = accs[a];
|
|
157
|
+
if (A.sum >= 0) data[b + A.sum] += x;
|
|
158
|
+
if (A.cnt >= 0) data[b + A.cnt] += 1;
|
|
159
|
+
if (A.min >= 0 && x < data[b + A.min]) data[b + A.min] = x;
|
|
160
|
+
if (A.max >= 0 && x > data[b + A.max]) data[b + A.max] = x;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
matched++;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
const progress = () => (opts.progressFn ? opts.progressFn() : opts.totalRows ? Math.min(0.99, nRows / opts.totalRows) : 0.5);
|
|
167
|
+
|
|
168
|
+
if (!firstStep.done) {
|
|
169
|
+
await consume(firstBatch);
|
|
170
|
+
await slicer.tick(progress());
|
|
171
|
+
for (;;) {
|
|
172
|
+
const st = await it.next();
|
|
173
|
+
if (st.done) break;
|
|
174
|
+
await consume(st.value);
|
|
175
|
+
await slicer.tick(progress());
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ---- convert interned ids to final mixed-radix keys and hand over to the shared roll-up -----
|
|
180
|
+
const synth = (dim) => {
|
|
181
|
+
const card = dim.bucket ? dim.labels.length : dim.values.length;
|
|
182
|
+
const label = dim.bucket ? (g) => dim.labels[g] : (g) => schema.labelOf(dim.f, dim.values[g]);
|
|
183
|
+
const compare = dim.bucket ? (a, b) => dim.keys[a] - dim.keys[b] : (a, b) => compareValues(dim.values[a], dim.values[b]);
|
|
184
|
+
return { spec: dim.spec, field: dim.f, store: null, map: null, card, values: dim.values, labels: dim.bucket ? dim.labels : null, label, compare };
|
|
185
|
+
};
|
|
186
|
+
const rts = rowDims.map(synth), cts = colDims.map(synth);
|
|
187
|
+
const space = (dims) => dims.reduce((a, d) => a * d.card, 1);
|
|
188
|
+
const rowSpace = space(rts), colSpace = space(cts);
|
|
189
|
+
if (rowSpace * colSpace > MAX_SAFE) throw new PivotLimitError('Dimension combination is too large to index (cardinality product exceeds 2^53).');
|
|
190
|
+
|
|
191
|
+
const finalKeyer = (ax, rts_) => {
|
|
192
|
+
const memo = new Map();
|
|
193
|
+
const n = ax.n;
|
|
194
|
+
return (leaf) => {
|
|
195
|
+
if (!n) return 0;
|
|
196
|
+
let v = memo.get(leaf);
|
|
197
|
+
if (v !== undefined) return v;
|
|
198
|
+
const gids = new Array(n);
|
|
199
|
+
let id = leaf;
|
|
200
|
+
for (let k = n - 1; k >= 1; k--) { gids[k] = ax.gd[k][id]; id = ax.par[k][id]; }
|
|
201
|
+
gids[0] = id;
|
|
202
|
+
v = 0;
|
|
203
|
+
for (let k = 0; k < n; k++) v = v * rts_[k].card + gids[k];
|
|
204
|
+
memo.set(leaf, v);
|
|
205
|
+
return v;
|
|
206
|
+
};
|
|
207
|
+
};
|
|
208
|
+
const rowKey = finalKeyer(rowAx, rts), colKey = finalKeyer(colAx, cts);
|
|
209
|
+
const finalStore = new CellStore(layout, Math.max(4096, store.count), false);
|
|
210
|
+
for (const [key, slot] of store.map) {
|
|
211
|
+
const rl = Math.floor(key / R22), cl = key - rl * R22;
|
|
212
|
+
const fs = finalStore.slot(rowKey(rl) * colSpace + colKey(cl));
|
|
213
|
+
finalStore.data.set(store.data.subarray(slot * S, slot * S + S), fs * S);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return finishPivot({
|
|
217
|
+
ns, layout, rowDims: rts, colDims: cts, colSpace, store: finalStore, dense: false, cells: 0,
|
|
218
|
+
hol: null, matched, nRows, filters: [], maxCells, slicer, t0,
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* A re-readable data source for the viewer/designer that never holds the rows in memory.
|
|
224
|
+
* Same interface as Dataset (fieldInfo / compute / distinct / drill), so it plugs into PivotViewer & PivotDesigner.
|
|
225
|
+
*/
|
|
226
|
+
export class StreamSource {
|
|
227
|
+
/**
|
|
228
|
+
* @param {{open:()=>AsyncIterable<any[]>, fields:Array<object>, positional?:boolean, totalRows?:number}} o
|
|
229
|
+
* open() must return a fresh iterable of row batches every call
|
|
230
|
+
*/
|
|
231
|
+
constructor({ open, fields, positional = false, totalRows = null }) {
|
|
232
|
+
this.open = open;
|
|
233
|
+
this.fields = fields;
|
|
234
|
+
this.positional = positional;
|
|
235
|
+
this.totalRows = totalRows;
|
|
236
|
+
this.rowCount = totalRows;
|
|
237
|
+
this._distinct = new Map();
|
|
238
|
+
this._schema = new Dataset(fields);
|
|
239
|
+
this._schema._inferFrom(() => null, 0);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** CSV source. `source` may be a Blob/File/string, or a function returning one (or a stream) per read. */
|
|
243
|
+
static async fromCSV(source, opts = {}) {
|
|
244
|
+
const thunk = typeof source === 'function' ? source : () => source;
|
|
245
|
+
const { names, sample } = await csvHead(thunk(), opts);
|
|
246
|
+
const overrides = Object.fromEntries((opts.fields || []).map((f) => [f.name, f]));
|
|
247
|
+
const fields = inferFields(names, sample, overrides);
|
|
248
|
+
return new StreamSource({
|
|
249
|
+
fields,
|
|
250
|
+
positional: true,
|
|
251
|
+
totalRows: opts.totalRows ?? null,
|
|
252
|
+
open: () => csvBatches(thunk(), { delimiter: opts.delimiter, header: opts.header, batchSize: opts.batchSize }),
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
fieldInfo() { return this._schema.fieldInfo(); }
|
|
257
|
+
hasField(name) { return this._schema.hasField(name); }
|
|
258
|
+
|
|
259
|
+
compute(spec, opts = {}) {
|
|
260
|
+
return computePivotStream(this.open(), this.fields, spec, { positional: this.positional, totalRows: this.totalRows, ...opts });
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Distinct values for filter pickers (one full scan per field, cached; capped at 100k values). */
|
|
264
|
+
async distinct(name, { search = '', limit = 500 } = {}) {
|
|
265
|
+
let all = this._distinct.get(name);
|
|
266
|
+
if (!all) {
|
|
267
|
+
const f = this._schema.getField(name);
|
|
268
|
+
if (!f.dim) throw new PivotError(`"${name}" is not a dimension`);
|
|
269
|
+
const get = this.positional ? (r) => r[f.index] : (r) => r[f.name];
|
|
270
|
+
const set = new Set();
|
|
271
|
+
for await (const batch of this.open()) {
|
|
272
|
+
for (const row of batch) { const raw = get(row); set.add(raw == null || raw === '' ? null : f.coerce(raw)); if (set.size >= 100000) break; }
|
|
273
|
+
if (set.size >= 100000) break;
|
|
274
|
+
}
|
|
275
|
+
all = [...set].sort(compareValues).map((value) => ({ value, label: this._schema.labelOf(f, value) }));
|
|
276
|
+
this._distinct.set(name, all);
|
|
277
|
+
}
|
|
278
|
+
const q = search.toLowerCase();
|
|
279
|
+
const items = all.filter((x) => !q || x.label.toLowerCase().includes(q));
|
|
280
|
+
return { total: items.length, items: items.slice(0, limit) };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async drill() { throw new PivotError('Drill-through is not available for streamed sources'); }
|
|
284
|
+
memoryUsage() { return 0; }
|
|
285
|
+
}
|