@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/src/remote.js ADDED
@@ -0,0 +1,164 @@
1
+ // Client side of the PivotJet server: RemoteDataset has the same interface as Dataset / StreamSource, so
2
+ // PivotViewer and PivotDesigner work against data that lives on a server (100M+ rows) unchanged.
3
+ // Also holds the (de)serialisation of pivot results, shared with the server.
4
+
5
+ import { PivotResult, AxisNode, PivotError } from './engine.js';
6
+ import { RestReportStore } from './reportstore.js';
7
+ import { RestAdapter } from './layouts.js';
8
+
9
+ // ---- binary <-> base64 (works in Node and browsers) -------------------------------------
10
+ function toB64(typed) {
11
+ const bytes = new Uint8Array(typed.buffer, typed.byteOffset, typed.byteLength);
12
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64');
13
+ let s = '';
14
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
15
+ return btoa(s);
16
+ }
17
+ function fromB64(str, Type) {
18
+ let bytes;
19
+ if (typeof Buffer !== 'undefined') { const b = Buffer.from(str, 'base64'); bytes = new Uint8Array(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)); }
20
+ else { const bin = atob(str); bytes = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); }
21
+ return new Type(bytes.buffer, 0, bytes.byteLength / Type.BYTES_PER_ELEMENT);
22
+ }
23
+
24
+ /** Turn a PivotResult into a JSON-safe payload (what the server sends). */
25
+ export function serializeResult(res) {
26
+ const axis = (ax) => ({
27
+ parents: toB64(Int32Array.from(ax.nodes, (n) => (n.parent ? n.parent.id : -1))),
28
+ labels: ax.nodes.map((n) => (n.level < 0 ? '' : n.label)),
29
+ });
30
+ const nv = res.values.length, st = res.store, nCol = res.nCol, S = st ? st.S : 0;
31
+ const rid = [], cid = [];
32
+ const push = (key) => { const r = Math.floor(key / nCol); rid.push(r); cid.push(key - r * nCol); };
33
+ if (!st) { for (const k of res._pairs.keys()) push(k); } // a result that itself came from deserializeResult
34
+ else if (st.dense) { const total = res.rowAxis.nodes.length * nCol; for (let k = 0; k < total; k++) if (st.data[k * S] > 0) push(k); }
35
+ else for (const k of st.map.keys()) push(k);
36
+ const vals = new Float64Array(rid.length * nv);
37
+ for (let i = 0; i < rid.length; i++) {
38
+ const rn = res.rowAxis.nodes[rid[i]], cn = res.colAxis.nodes[cid[i]];
39
+ for (let j = 0; j < nv; j++) { const x = res.base(rn, cn, j); vals[i * nv + j] = x === null ? NaN : x; }
40
+ }
41
+ const dim = (d) => ({ field: d.field, label: d.label, bucket: d.bucket || null, sort: d.sort });
42
+ return {
43
+ v: 1,
44
+ rows: res.rowDims.map(dim), cols: res.colDims.map(dim),
45
+ values: res.values.map((v) => ({ field: v.field || '*', agg: v.agg || null, label: v.label, format: v.format ?? null, showAs: v.showAs, calc: v.calc || null })),
46
+ nCol, rowAxis: axis(res.rowAxis), colAxis: axis(res.colAxis),
47
+ rid: toB64(Int32Array.from(rid)), cid: toB64(Int32Array.from(cid)), vals: toB64(vals),
48
+ stats: res.stats,
49
+ };
50
+ }
51
+
52
+ class RemoteResult extends PivotResult {
53
+ base(r, c, j) {
54
+ const i = this._pairs.get(r.id * this.nCol + c.id);
55
+ if (i === undefined) return null;
56
+ const x = this._vals[i * this.values.length + j];
57
+ return x === x ? x : null;
58
+ }
59
+ has(r, c) { return this._pairs.has(r.id * this.nCol + c.id); }
60
+ }
61
+
62
+ function buildAxis(payload, dims) {
63
+ const parents = fromB64(payload.parents, Int32Array), labels = payload.labels;
64
+ const nodes = new Array(parents.length);
65
+ for (let i = 0; i < parents.length; i++) {
66
+ const p = parents[i] < 0 ? null : nodes[parents[i]];
67
+ const n = new AxisNode(i, p ? p.level + 1 : -1, 0, p, null);
68
+ n._label = i === 0 ? 'Grand Total' : labels[i];
69
+ n.dim = p ? dims[n.level] : null;
70
+ if (p) p.children.push(n);
71
+ nodes[i] = n;
72
+ }
73
+ return { root: nodes[0], nodes, leafByKey: new Map(), dims };
74
+ }
75
+
76
+ /** Rebuild a PivotResult from a server payload. */
77
+ export function deserializeResult(p) {
78
+ if (!p || p.v !== 1) throw new PivotError('Unsupported result payload');
79
+ const rowAxis = buildAxis(p.rowAxis, p.rows), colAxis = buildAxis(p.colAxis, p.cols);
80
+ const rid = fromB64(p.rid, Int32Array), cid = fromB64(p.cid, Int32Array);
81
+ const pairs = new Map();
82
+ for (let i = 0; i < rid.length; i++) pairs.set(rid[i] * p.nCol + cid[i], i);
83
+ const res = new RemoteResult({
84
+ spec: { rows: p.rows, cols: p.cols, values: p.values, filters: [], options: {} },
85
+ layout: { vref: [] }, store: null, rowAxis, colAxis, hol: null, stats: { ...p.stats, remote: true }, _ctx: null,
86
+ });
87
+ res._pairs = pairs;
88
+ res._vals = fromB64(p.vals, Float64Array);
89
+ return res;
90
+ }
91
+
92
+ /** Connect to a PivotJet server dataset. */
93
+ export class RemoteDataset {
94
+ /**
95
+ * @param {string} baseUrl e.g. 'http://localhost:8080'
96
+ * @param {string} [name] dataset name (default: the first one the server exposes)
97
+ * @param {{headers?:object, token?:string, fetch?:Function}} [opts]
98
+ */
99
+ static async connect(baseUrl, name, opts = {}) {
100
+ const rd = new RemoteDataset(baseUrl, name, opts);
101
+ if (!name) {
102
+ const list = await rd._get('/api/sources');
103
+ if (!list.length) throw new PivotError('Server exposes no datasets');
104
+ rd.name = list[0].name;
105
+ }
106
+ const schema = await rd._get(`/api/${encodeURIComponent(rd.name)}/schema`);
107
+ rd.rowCount = schema.rowCount;
108
+ rd._fields = schema.fields;
109
+ rd.supportsDrill = !!schema.supportsDrill;
110
+ rd.supportsLayouts = !!schema.supportsLayouts;
111
+ rd.supportsReports = !!schema.supportsReports;
112
+ return rd;
113
+ }
114
+ constructor(baseUrl, name, opts = {}) {
115
+ this.base = baseUrl.replace(/\/+$/, '');
116
+ this.name = name;
117
+ this.opts = opts;
118
+ this.rowCount = null;
119
+ this._fields = [];
120
+ }
121
+ _headers() {
122
+ const h = { 'content-type': 'application/json', ...(this.opts.headers || {}) };
123
+ if (this.opts.token) h.authorization = `Bearer ${this.opts.token}`;
124
+ return h;
125
+ }
126
+ async _req(path, init) {
127
+ const f = this.opts.fetch || globalThis.fetch;
128
+ const r = await f(this.base + path, { ...init, headers: { ...this._headers(), ...(init && init.headers) } });
129
+ const body = await r.json().catch(() => null);
130
+ if (!r.ok) {
131
+ const e = new PivotError((body && body.error && body.error.message) || `Server error ${r.status}`);
132
+ if (body && body.error && body.error.name) e.name = body.error.name;
133
+ throw e;
134
+ }
135
+ return body;
136
+ }
137
+ _get(path) { return this._req(path); }
138
+ _post(path, data, signal) { return this._req(`/api/${encodeURIComponent(this.name)}${path}`, { method: 'POST', body: JSON.stringify(data), signal }); }
139
+
140
+ fieldInfo() { return this._fields; }
141
+ hasField(n) { return this._fields.some((f) => f.name === n); }
142
+ async compute(spec, opts = {}) {
143
+ if (opts.onProgress) opts.onProgress(0.05);
144
+ const payload = await this._post('/pivot', { spec, maxCells: opts.maxCells }, opts.signal);
145
+ const res = deserializeResult(payload);
146
+ res._remoteSpec = spec;
147
+ if (opts.onProgress) opts.onProgress(1);
148
+ return res;
149
+ }
150
+ distinct(field, o = {}) { return this._post('/distinct', { field, search: o.search || '', limit: o.limit || 500 }); }
151
+ async drill(result, rowNode, colNode, o = {}) {
152
+ if (!this.supportsDrill) throw new PivotError('Drill-through is not available for this server dataset');
153
+ return this._post('/drill', { spec: result._remoteSpec, rowPath: rowNode.path(), colPath: colNode.path(), limit: o.limit || 200 }, o.signal);
154
+ }
155
+ memoryUsage() { return 0; }
156
+ /** Report store on the server (versioned; needs the server's `reports` option). */
157
+ reportStore() {
158
+ return new RestReportStore(`${this.base}/api/${encodeURIComponent(this.name)}/reports`, { headers: this.opts.headers, token: this.opts.token, fetch: this.opts.fetch });
159
+ }
160
+ /** Layout adapter that stores saved layouts on the server (server must run with `layouts` enabled). */
161
+ layoutAdapter() {
162
+ return new RestAdapter(`${this.base}/api/${encodeURIComponent(this.name)}/layouts`, { headers: this.opts.headers, token: this.opts.token, fetch: this.opts.fetch });
163
+ }
164
+ }
@@ -0,0 +1,31 @@
1
+ import { PivotViewer } from './viewer.js';
2
+ import { parseReport, applyReportFields } from './report.js';
3
+ import { deserializeResult } from './remote.js';
4
+ import { PivotError } from './errors.js';
5
+
6
+ /**
7
+ * Render a saved report into a container.
8
+ * @param {HTMLElement|string} container
9
+ * @param {object|string} report a report document (or its JSON text)
10
+ * @param {{dataset?:object, mode?:'auto'|'live'|'snapshot'} & object} [options] extra PivotViewer options
11
+ * mode 'auto' (default): live when a dataset is given, otherwise the embedded snapshot.
12
+ * live recomputes the spec against `dataset` (fresh numbers, drill-through); snapshot shows the frozen numbers offline.
13
+ * @returns {PivotViewer}
14
+ */
15
+ export function renderReport(container, report, options = {}) {
16
+ const r = parseReport(report);
17
+ const { dataset, mode = 'auto', ...viewerOpts } = options;
18
+ const withState = { state: r.state || undefined, locale: r.locale || viewerOpts.locale };
19
+ const live = mode === 'live' || (mode === 'auto' && !!dataset);
20
+ const o = (r.spec && r.spec.options) || {};
21
+ const base = { ...viewerOpts, ...withState, view: o.view || viewerOpts.view, chart: o.chart || viewerOpts.chart };
22
+ if (live) {
23
+ if (!dataset) throw new PivotError('renderReport: live mode needs a dataset');
24
+ applyReportFields(dataset, r); // re-creates the report's formula columns on the dataset when missing
25
+ return new PivotViewer(container, { ...base, dataset, spec: r.spec });
26
+ }
27
+ if (!r.snapshot) throw new PivotError('This report has no snapshot. Pass a dataset to render it live.');
28
+ const viewer = new PivotViewer(container, { ...base, drill: false, spec: r.spec });
29
+ viewer.setResult(deserializeResult(r.snapshot.result));
30
+ return viewer;
31
+ }
package/src/report.js ADDED
@@ -0,0 +1,103 @@
1
+ // Portable reports: a pivot spec (+ optional frozen snapshot of the result) as one JSON document that can be
2
+ // stored, published, and rendered later - live against a data source, or offline from the snapshot.
3
+ import { serializeResult } from './remote.js';
4
+ import { PivotError } from './errors.js';
5
+ import { cleanRules } from './cellfmt.js';
6
+
7
+ export const REPORT_FORMAT = 'pivotjet-report';
8
+ export const REPORT_VERSION = 1;
9
+
10
+ /**
11
+ * Build a report document (plain JSON-safe object).
12
+ * @param {{title?:string, description?:string, author?:string, spec:object, result?:object, snapshot?:boolean,
13
+ * source?:{name?:string, url?:string}, fields?:{name:string,label?:string,formula:string}[], schema?:object[],
14
+ * state?:object, locale?:string}} o
15
+ * The spec carries everything about the pivot itself (dimensions, values incl. calculated values, filters, number
16
+ * formats, per-cell rules in options.cellRules, print setup in options.print). `fields` are the calculated
17
+ * (formula) columns that live on the dataset; `state` is expansion/sort/sizing; `schema` documents the source columns.
18
+ * result + snapshot (default true when a result is given) embeds the computed numbers so the report renders
19
+ * without any data source. Without a snapshot the report is "live": renderReport() recomputes it from a dataset.
20
+ */
21
+ export function createReport(o = {}) {
22
+ if (!o.spec || typeof o.spec !== 'object') throw new PivotError('createReport: spec is required');
23
+ const withSnap = o.result && o.snapshot !== false;
24
+ return {
25
+ format: REPORT_FORMAT,
26
+ version: REPORT_VERSION,
27
+ title: o.title || 'Pivot report',
28
+ description: o.description || '',
29
+ author: o.author || '',
30
+ created: new Date().toISOString(),
31
+ source: o.source || null,
32
+ locale: o.locale || null,
33
+ spec: JSON.parse(JSON.stringify(o.spec)),
34
+ fields: (o.fields || []).map((f) => ({ name: f.name, label: f.label || f.name, formula: f.formula })),
35
+ schema: o.schema ? JSON.parse(JSON.stringify(o.schema)) : null,
36
+ state: o.state ? JSON.parse(JSON.stringify(o.state)) : null,
37
+ snapshot: withSnap ? { at: new Date().toISOString(), result: serializeResult(o.result) } : null,
38
+ };
39
+ }
40
+
41
+ /** Validate and return a report from a JSON string or object. Throws PivotError when it is not a report. */
42
+ export function parseReport(input) {
43
+ let r = input;
44
+ if (typeof input === 'string') {
45
+ try { r = JSON.parse(input); } catch { throw new PivotError('Not a valid report: invalid JSON'); }
46
+ }
47
+ if (!r || r.format !== REPORT_FORMAT) throw new PivotError('Not a PivotJet report (missing format marker)');
48
+ if (!Number.isInteger(r.version) || r.version > REPORT_VERSION) throw new PivotError(`Unsupported report version ${r.version} (this build reads up to ${REPORT_VERSION})`);
49
+ if (!r.spec || typeof r.spec !== 'object') throw new PivotError('Report has no spec');
50
+ if (r.snapshot && !(r.snapshot.result && r.snapshot.result.v === 1)) throw new PivotError('Report snapshot is corrupt');
51
+ if (r.fields != null) {
52
+ if (!Array.isArray(r.fields) || r.fields.some((f) => !f || typeof f.name !== 'string' || typeof f.formula !== 'string')) throw new PivotError('Report fields must be [{ name, formula }]');
53
+ }
54
+ // throws a clear, numbered message for a malformed per-cell rule
55
+ if (r.spec.options && r.spec.options.cellRules != null) cleanRules(r.spec.options.cellRules);
56
+ return r;
57
+ }
58
+
59
+ const escHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
60
+
61
+ /**
62
+ * A single self-contained .html file that renders the report offline (snapshot required).
63
+ * @param {object} report
64
+ * @param {{bundle:string, theme?:'light'|'dark'|'auto', chartToggle?:boolean}} opts bundle = source of dist/pivotjet.min.js
65
+ */
66
+ export function reportToHTML(report, opts = {}) {
67
+ const r = parseReport(report);
68
+ if (!r.snapshot) throw new PivotError('Only reports with a snapshot can be exported as standalone HTML (create the report with a result)');
69
+ if (!opts.bundle) throw new PivotError('reportToHTML: opts.bundle (the pivotjet browser bundle source) is required');
70
+ const json = JSON.stringify(r).replace(/</g, '\\u003c').replace(new RegExp(String.fromCharCode(0x2028), 'g'), '\\u2028').replace(new RegExp(String.fromCharCode(0x2029), 'g'), '\\u2029');
71
+ const bundle = String(opts.bundle).replace(/<\/script/gi, '<\\/script').replace(/\/\/# sourceMappingURL=.*$/m, '');
72
+ const when = r.snapshot.at ? new Date(r.snapshot.at).toUTCString() : '';
73
+ return `<!doctype html>
74
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
75
+ <title>${escHtml(r.title)}</title>
76
+ <style>html,body{height:100%;margin:0}body{display:flex;flex-direction:column;font-family:system-ui,-apple-system,Segoe UI,sans-serif;padding:14px 16px;box-sizing:border-box;gap:10px}
77
+ h1{margin:0;font-size:20px}.meta{font-size:12px;color:#6b7280}#app{flex:1;min-height:0}#app .mp-root{height:100%}
78
+ @media print{body{padding:0}.meta{color:#000}#pj-print{display:none}}</style></head>
79
+ <body><div><h1>${escHtml(r.title)}</h1>${r.description ? `<div class="meta">${escHtml(r.description)}</div>` : ''}<div class="meta"><button id="pj-print" style="float:right">Print</button>Snapshot${when ? ' of ' + escHtml(when) : ''}${r.author ? ' · ' + escHtml(r.author) : ''}</div></div>
80
+ <div id="app"></div>
81
+ <script>${bundle}</script>
82
+ <script>const v = PivotJet.renderReport('#app', ${json}, { theme: ${JSON.stringify(opts.theme || 'auto')} });document.getElementById('pj-print').onclick = () => v.print();</script>
83
+ </body></html>`;
84
+ }
85
+
86
+ /**
87
+ * Make sure a data source has the report's calculated (formula) columns. Existing fields are left alone.
88
+ * Only an in-memory Dataset can add fields; for a server or streamed source the fields must already exist there.
89
+ * @returns {string[]} names of the fields that were added
90
+ */
91
+ export function applyReportFields(dataset, report) {
92
+ const r = parseReport(report);
93
+ const added = [];
94
+ for (const f of r.fields || []) {
95
+ if (dataset.hasField(f.name)) continue;
96
+ if (typeof dataset.addCalculatedField !== 'function') {
97
+ throw new PivotError(`This report needs the calculated field "${f.name}" (${f.formula}), but this data source does not have it and cannot add fields. Define it where the data is loaded.`);
98
+ }
99
+ dataset.addCalculatedField({ name: f.name, label: f.label, formula: f.formula });
100
+ added.push(f.name);
101
+ }
102
+ return added;
103
+ }
@@ -0,0 +1,135 @@
1
+ // Saved-report stores: versioned, with optimistic concurrency.
2
+ //
3
+ // const store = new ReportStore(new MemoryReportAdapter()); // server side / tests
4
+ // const store = new LocalStorageReportStore('mine'); // browser only (small reports: localStorage is ~5 MB)
5
+ // const store = new RestReportStore('http://host/api/sales/reports', { token }); // a pivotjet server
6
+ //
7
+ // All stores share one async API: list() load(id, {version}) save(report, {id, baseVersion}) versions(id) remove(id).
8
+ import { PivotError } from './errors.js';
9
+
10
+ export class ConflictError extends PivotError {
11
+ constructor(message, current) { super(message); this.name = 'ConflictError'; this.status = 409; this.current = current; }
12
+ }
13
+ export class NotFoundError extends PivotError {
14
+ constructor(message) { super(message); this.name = 'NotFoundError'; this.status = 404; }
15
+ }
16
+
17
+ export const REPORT_ID = /^[\w-]{1,64}$/;
18
+ const newId = () => (globalThis.crypto && globalThis.crypto.randomUUID ? globalThis.crypto.randomUUID() : 'r' + Math.random().toString(36).slice(2) + Date.now().toString(36));
19
+ const clone = (x) => JSON.parse(JSON.stringify(x));
20
+
21
+ function summary(doc) {
22
+ const last = doc.versions[doc.versions.length - 1];
23
+ const r = last.report;
24
+ return { id: doc.id, title: r.title || 'Untitled', description: r.description || '', author: r.author || '', created: doc.created, updated: last.updated, version: last.version, hasSnapshot: !!r.snapshot };
25
+ }
26
+
27
+ /** Wraps a document adapter { get(id), put(id, doc), del(id), all() } with versioning and concurrency control. */
28
+ export class ReportStore {
29
+ constructor(adapter, { keepVersions = 20, validate } = {}) {
30
+ this.adapter = adapter; this.keep = keepVersions; this.validate = validate; this._q = new Map();
31
+ }
32
+ _serial(id, fn) {
33
+ const prev = this._q.get(id) || Promise.resolve();
34
+ const run = prev.then(fn);
35
+ this._q.set(id, run.catch(() => {}));
36
+ return run;
37
+ }
38
+ async list() {
39
+ return (await this.adapter.all()).map(summary).sort((a, b) => b.updated - a.updated);
40
+ }
41
+ async load(id, { version } = {}) {
42
+ const doc = await this.adapter.get(id);
43
+ if (!doc) return null;
44
+ const v = version == null ? doc.versions[doc.versions.length - 1] : doc.versions.find((x) => x.version === Number(version));
45
+ return v ? clone(v.report) : null;
46
+ }
47
+ async versions(id) {
48
+ const doc = await this.adapter.get(id);
49
+ if (!doc) return [];
50
+ return doc.versions.map((v) => ({ version: v.version, updated: v.updated, title: v.report.title || 'Untitled', hasSnapshot: !!v.report.snapshot })).reverse();
51
+ }
52
+ /** Creates (no id) or adds a new version (id). `baseVersion`: the version you edited; a newer one on the store throws ConflictError. */
53
+ async save(report, { id, baseVersion } = {}) {
54
+ if (this.validate) this.validate(report);
55
+ if (id !== undefined && !REPORT_ID.test(id)) throw new PivotError('Invalid report id (letters, digits, - and _ only)');
56
+ const rid = id || newId();
57
+ return this._serial(rid, async () => {
58
+ let doc = await this.adapter.get(rid);
59
+ const now = Date.now();
60
+ if (!doc) {
61
+ if (baseVersion) throw new NotFoundError(`Report ${rid} no longer exists`);
62
+ doc = { id: rid, created: now, versions: [] };
63
+ }
64
+ const cur = doc.versions.length ? doc.versions[doc.versions.length - 1].version : 0;
65
+ if (baseVersion != null && Number(baseVersion) !== cur) throw new ConflictError(`Report was changed by someone else (now version ${cur}, you edited version ${baseVersion})`, cur);
66
+ doc.versions.push({ version: cur + 1, updated: now, report: clone(report) });
67
+ if (doc.versions.length > this.keep) doc.versions.splice(0, doc.versions.length - this.keep);
68
+ await this.adapter.put(rid, doc);
69
+ return { id: rid, version: cur + 1, updated: now };
70
+ });
71
+ }
72
+ async remove(id) {
73
+ return this._serial(id, async () => { if (!(await this.adapter.get(id))) throw new NotFoundError(`No report ${id}`); await this.adapter.del(id); });
74
+ }
75
+ }
76
+
77
+ export class MemoryReportAdapter {
78
+ constructor() { this.m = new Map(); }
79
+ async get(id) { const d = this.m.get(id); return d ? clone(d) : null; }
80
+ async put(id, doc) { this.m.set(id, clone(doc)); }
81
+ async del(id) { this.m.delete(id); }
82
+ async all() { return [...this.m.values()].map(clone); }
83
+ }
84
+
85
+ /** Browser storage. Snapshots count against the ~5 MB quota; saving throws a clear error when it is full. */
86
+ export class LocalStorageReportAdapter {
87
+ constructor(namespace = 'default', storage) { this.ns = `pivotjet.reports.${namespace}`; this.st = storage || globalThis.localStorage; }
88
+ _idx() { try { return JSON.parse(this.st.getItem(this.ns + '.index') || '[]'); } catch { return []; } }
89
+ async get(id) { try { const t = this.st.getItem(`${this.ns}.${id}`); return t ? JSON.parse(t) : null; } catch { return null; } }
90
+ async put(id, doc) {
91
+ try { this.st.setItem(`${this.ns}.${id}`, JSON.stringify(doc)); } catch { throw new PivotError('Browser storage is full: save the report without a snapshot, delete old reports, or use a server store.'); }
92
+ const idx = this._idx(); if (!idx.includes(id)) { idx.push(id); this.st.setItem(this.ns + '.index', JSON.stringify(idx)); }
93
+ }
94
+ async del(id) { this.st.removeItem(`${this.ns}.${id}`); this.st.setItem(this.ns + '.index', JSON.stringify(this._idx().filter((x) => x !== id))); }
95
+ async all() { const out = []; for (const id of this._idx()) { const d = await this.get(id); if (d) out.push(d); } return out; }
96
+ }
97
+ export class LocalStorageReportStore extends ReportStore {
98
+ constructor(namespace, opts) { super(new LocalStorageReportAdapter(namespace, opts && opts.storage), opts); }
99
+ }
100
+
101
+ /** Client for the server's /api/:dataset/reports endpoints (same API as ReportStore). */
102
+ export class RestReportStore {
103
+ /** @param {string} url e.g. 'http://host:8080/api/sales/reports' */
104
+ constructor(url, { headers = {}, token, fetch: f } = {}) {
105
+ this.url = url.replace(/\/+$/, ''); this.headers = headers; this.token = token; this._fetch = f;
106
+ }
107
+ _h(extra) { const h = { ...this.headers, ...extra }; if (this.token) h.authorization = `Bearer ${this.token}`; return h; }
108
+ async _req(path, init = {}) {
109
+ const f = this._fetch || globalThis.fetch;
110
+ const res = await f(this.url + path, { ...init, headers: this._h(init.headers) });
111
+ if (res.status === 404 && init.method !== 'DELETE' && path.startsWith('/') && path.length > 1 && !path.includes('/versions')) return null;
112
+ if (!res.ok) {
113
+ let msg = `Server returned ${res.status}`, body = null;
114
+ try { body = await res.json(); msg = (body && body.error && body.error.message) || msg; } catch { /* not json */ }
115
+ throw res.status === 409 ? new ConflictError(msg, body && body.error && body.error.current) : res.status === 404 ? new NotFoundError(msg) : new PivotError(msg);
116
+ }
117
+ return res;
118
+ }
119
+ async list() { return (await this._req('')).json(); }
120
+ async load(id, { version } = {}) { const r = await this._req(`/${encodeURIComponent(id)}${version != null ? `?version=${version}` : ''}`); return r ? r.json() : null; }
121
+ async versions(id) { return (await this._req(`/${encodeURIComponent(id)}/versions`)).json(); }
122
+ async save(report, { id, baseVersion } = {}) {
123
+ return (await this._req('', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ report, id, baseVersion }) })).json();
124
+ }
125
+ async remove(id) { await this._req(`/${encodeURIComponent(id)}`, { method: 'DELETE' }); }
126
+ /** Fetch a server-rendered export (uses the Authorization header, so the token never appears in a URL). */
127
+ async exportBytes(id, format = 'pdf', { live } = {}) {
128
+ const q = `format=${encodeURIComponent(format)}${live === undefined ? '' : `&live=${live ? 1 : 0}`}`;
129
+ const r = await this._req(`/${encodeURIComponent(id)}/export?${q}`);
130
+ if (!r) throw new NotFoundError(`No report ${id}`);
131
+ return new Uint8Array(await r.arrayBuffer());
132
+ }
133
+ /** A link people can open in a browser: the server renders the report. A token-protected server asks for the token. */
134
+ shareUrl(id) { return this.url.replace(/\/api\/([^/]+)\/reports$/, (m, n) => `/report/${n}/${encodeURIComponent(id)}`); }
135
+ }
@@ -0,0 +1,20 @@
1
+ import type { Server } from 'node:http';
2
+ import type { PivotSource } from './core.js';
3
+
4
+ export interface PivotServerOptions {
5
+ /** name -> Dataset | StreamSource */
6
+ sources: Record<string, PivotSource>;
7
+ /** require "Authorization: Bearer <token>" */
8
+ token?: string;
9
+ /** true = allow any origin, or a specific origin string */
10
+ cors?: boolean | string;
11
+ maxCells?: number;
12
+ /** persist saved designer layouts per dataset: in memory (true) or as JSON files in `dir` */
13
+ layouts?: boolean | { dir?: string };
14
+ /** saved, versioned reports per dataset with server-rendered PDF/Excel/HTML and a share page: in memory (true) or JSON files in `dir` */
15
+ reports?: boolean | { dir?: string; keepVersions?: number };
16
+ /** PDF fonts: family -> { regular, bold, italic, boldItalic } as file paths or bytes */
17
+ fonts?: Record<string, Partial<Record<'regular' | 'bold' | 'italic' | 'boldItalic', string | Uint8Array>>>;
18
+ }
19
+ /** HTTP server exposing pivot/distinct/drill/layouts endpoints plus a ready-made designer page. Call `.listen(port)`. */
20
+ export function createPivotServer(opts: PivotServerOptions): Server;