@casoon/opengrid 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/loader.js ADDED
@@ -0,0 +1,1000 @@
1
+ /**
2
+ * @casoon/opengrid loader (plan point 13, plan/spezifikation/08-rendering.md
3
+ * §JavaScript-Minimum).
4
+ *
5
+ * The browser loads exactly this file plus the WASM module. `loader.js` does
6
+ * three small things and no domain logic:
7
+ *
8
+ * 1. load the WASM module (`wasm-bindgen --target web` glue),
9
+ * 2. register the custom elements (the Rust side does the rendering),
10
+ * 3. offer a DOM fallback when WASM is unavailable, so a page never breaks
11
+ * because of a missing `.wasm`.
12
+ *
13
+ * The fallback is intentionally the same empty skeleton the Rust element
14
+ * renders; point 14 replaces it once the table carries data.
15
+ *
16
+ * Point 19 adds the two providers. Both expose the same tiny shape the elements
17
+ * consume (`load`, `execute`, `terminate`), so a page switches between the
18
+ * Worker and the main thread without touching the grid:
19
+ *
20
+ * createWorkerProvider() engine in a module worker
21
+ * createLocalProvider(engine) engine on the main thread
22
+ * createRestProvider({ url, source, token }) opengrid-server über HTTP (point 27)
23
+ *
24
+ * Every provider's `execute(queryJson, mode, { signal })` may take an
25
+ * `AbortSignal` as its third argument (point 84). The providers that talk HTTP
26
+ * hand it to `fetch`, so an aborted export leaves no request running; the tab
27
+ * and the worker cannot stop a query that has started and ignore it — the
28
+ * caller drops their answer.
29
+ *
30
+ * The Worker provider starts lazily on the first `load`/`execute` and stays the
31
+ * single worker of V1 (no pool, no SharedArrayBuffer).
32
+ */
33
+
34
+ /** Default location of the wasm-bindgen glue; point 40 pins the packaged path. */
35
+ const DEFAULT_MODULE_URL = new URL("./pkg/opengrid_web_components.js", import.meta.url);
36
+
37
+ /**
38
+ * Default location of the engine module's glue, shipped under `engine/`. A
39
+ * string, not a `URL`: it travels to the worker by `postMessage`.
40
+ */
41
+ const DEFAULT_ENGINE_URL = new URL("./engine/opengrid_wasm.js", import.meta.url).href;
42
+
43
+ /** Set once the first `loadOpengrid` call has run. */
44
+ let loading;
45
+
46
+ /**
47
+ * Loads the WASM module and registers the elements.
48
+ *
49
+ * @param {object} [options]
50
+ * @param {URL|string} [options.moduleUrl] wasm-bindgen glue module (`--target web`).
51
+ * @param {string} [options.wasmUrl] explicit `.wasm` URL, if it is not next to the glue.
52
+ * @returns {Promise<{fallback: boolean, module?: object}>} whether the DOM fallback was
53
+ * installed, and the loaded WASM module so a page can call its exports —
54
+ * `set_provider` (point 14) and `set_texts` (point 48, call it first: it
55
+ * rebuilds the component).
56
+ */
57
+ export function loadOpengrid(options = {}) {
58
+ if (!loading) {
59
+ loading = start(options);
60
+ }
61
+ return loading;
62
+ }
63
+
64
+ async function start({ moduleUrl = DEFAULT_MODULE_URL, wasmUrl } = {}) {
65
+ try {
66
+ const module = await import(moduleUrl);
67
+ // wasm-bindgen `--target web` exports the initialiser as the default.
68
+ await module.default(wasmUrl);
69
+ module.register();
70
+ return { fallback: false, module };
71
+ } catch (error) {
72
+ console.warn("[opengrid] WASM unavailable, falling back to the DOM renderer", error);
73
+ installFallback();
74
+ return { fallback: true };
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Defines the elements in plain DOM, mirroring the Rust skeleton: an open
80
+ * shadow root, a native `<table>` with a `<caption>`, and `label` -> `aria-label`.
81
+ *
82
+ * Not exported: `loadOpengrid` installs it when the module fails to load, and a
83
+ * page that reaches for it directly is asking for the broken state on purpose
84
+ * (plan point 39 — an export is a promise).
85
+ *
86
+ * @param {string} [name] the element to define.
87
+ */
88
+ function installFallback(name = "opengrid-table") {
89
+ if (customElements.get(name)) {
90
+ return;
91
+ }
92
+
93
+ class OpengridTableFallback extends HTMLElement {
94
+ static get observedAttributes() {
95
+ return ["label"];
96
+ }
97
+
98
+ connectedCallback() {
99
+ if (this.shadowRoot) {
100
+ return;
101
+ }
102
+ const root = this.attachShadow({ mode: "open" });
103
+ const table = document.createElement("table");
104
+ const caption = document.createElement("caption");
105
+ table.append(caption);
106
+ root.append(table);
107
+ this.#applyLabel();
108
+ }
109
+
110
+ attributeChangedCallback() {
111
+ if (this.shadowRoot) {
112
+ this.#applyLabel();
113
+ }
114
+ }
115
+
116
+ #applyLabel() {
117
+ const table = this.shadowRoot.querySelector("table");
118
+ const caption = this.shadowRoot.querySelector("caption");
119
+ const label = this.getAttribute("label");
120
+ if (label) {
121
+ table.setAttribute("aria-label", label);
122
+ } else {
123
+ table.removeAttribute("aria-label");
124
+ }
125
+ caption.textContent = label ?? "";
126
+ }
127
+ }
128
+
129
+ customElements.define(name, OpengridTableFallback);
130
+ }
131
+
132
+ /**
133
+ * A provider that runs the engine inside a module worker.
134
+ *
135
+ * The provider is attached to a host with `set_provider`; the worker itself is
136
+ * started lazily and only once. The returned object matches the local provider
137
+ * shape, so the page code is the same for both paths.
138
+ *
139
+ * @param {object} [options]
140
+ * @param {string} [options.moduleUrl] wasm-bindgen glue of the engine module;
141
+ * defaults to the packaged one under `engine/`. A string, not a `URL`: it
142
+ * travels to the worker by `postMessage`.
143
+ * @param {string} [options.wasmUrl] explicit `.wasm` URL, if it is not next to the glue.
144
+ * @param {URL|string} [options.workerUrl] the worker entry; defaults to `worker.js` next to this file.
145
+ * @returns {{load: Function, execute: Function, terminate: Function, worker?: Worker}}
146
+ */
147
+ export function createWorkerProvider({
148
+ moduleUrl = DEFAULT_ENGINE_URL,
149
+ wasmUrl,
150
+ workerUrl,
151
+ } = {}) {
152
+ const workerScript = workerUrl ?? new URL("./worker.js", import.meta.url);
153
+ let worker;
154
+ let ready;
155
+ let nextId = 1;
156
+ /** Pending replies by request id: id -> {resolve, reject}. */
157
+ const pending = new Map();
158
+
159
+ function onMessage(message) {
160
+ const waiter = pending.get(message.id);
161
+ if (!waiter) {
162
+ return;
163
+ }
164
+ pending.delete(message.id);
165
+ if (message.type === "error") {
166
+ waiter.reject(new Error(message.message));
167
+ } else if (message.type === "loaded") {
168
+ waiter.resolve();
169
+ } else {
170
+ waiter.resolve(message.result);
171
+ }
172
+ }
173
+
174
+ function request(message, transfer = []) {
175
+ const id = nextId++;
176
+ return new Promise((resolve, reject) => {
177
+ pending.set(id, { resolve, reject });
178
+ worker.postMessage({ ...message, id }, transfer);
179
+ });
180
+ }
181
+
182
+ function start() {
183
+ if (!worker) {
184
+ worker = new Worker(workerScript, { type: "module" });
185
+ worker.onmessage = ({ data }) => onMessage(data);
186
+ ready = request({ type: "init", moduleUrl, wasmUrl });
187
+ }
188
+ return ready;
189
+ }
190
+
191
+ return {
192
+ /** Loads CSV bytes against a schema, starting the worker on first use. */
193
+ async load(name, bytes, schema) {
194
+ await start();
195
+ const buffer = toTransferable(bytes);
196
+ await request({ type: "load", name, bytes: buffer, schema }, [buffer]);
197
+ },
198
+
199
+ /** Runs a query JSON and resolves with the result JSON. */
200
+ async execute(queryJson) {
201
+ await start();
202
+ return request({ type: "query", query: queryJson });
203
+ },
204
+
205
+ /** Stops the worker and rejects everything still in flight. */
206
+ terminate() {
207
+ worker?.terminate();
208
+ worker = undefined;
209
+ ready = undefined;
210
+ for (const waiter of pending.values()) {
211
+ waiter.reject(new Error("worker terminated"));
212
+ }
213
+ pending.clear();
214
+ },
215
+
216
+ get worker() {
217
+ return worker;
218
+ },
219
+ };
220
+ }
221
+
222
+ /**
223
+ * A provider over an engine that is already initialised on the main thread.
224
+ *
225
+ * The fallback path of the elements (point 14): no worker, the same shape as
226
+ * `createWorkerProvider`, so a page can swap the two without changing the grid.
227
+ *
228
+ * @param {object} engine the loaded `Engine` from the engine module.
229
+ * @returns {{load: Function, execute: Function, terminate: Function}}
230
+ */
231
+ export function createLocalProvider(engine) {
232
+ return {
233
+ async load(name, bytes, schema) {
234
+ engine.load_csv(
235
+ name,
236
+ bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes),
237
+ schema,
238
+ );
239
+ },
240
+ execute(queryJson) {
241
+ return engine.execute(queryJson);
242
+ },
243
+ terminate() {},
244
+ };
245
+ }
246
+
247
+ /**
248
+ * A provider that talks to an `opengrid-server` over HTTP (plan point 27).
249
+ *
250
+ * The same shape as `createLocalProvider` and `createWorkerProvider`, so a page
251
+ * swaps local for remote without touching the grid: `set_provider` sees one
252
+ * `execute(queryJson)` either way. The difference is only where the work
253
+ * happens — and that the answer can fail for reasons a local engine never has.
254
+ *
255
+ * The server's error form (point 23) is unwrapped here: a failed request
256
+ * rejects with the server's own sentence, so the grid's status line shows
257
+ * "unknown source …" rather than "HTTP 404". The `Error` also carries the
258
+ * HTTP `status` and the form's `code` and `path` (issue #16), so a page can
259
+ * tell a `busy` server from a request that is too big without reading the
260
+ * sentence.
261
+ *
262
+ * No request follows a redirect (`redirect: "error"`): the bearer token goes
263
+ * to the URL the page configured, and nowhere a response points to.
264
+ *
265
+ * @param {object} options
266
+ * @param {string} options.url base URL of the server, e.g. `http://127.0.0.1:8081`.
267
+ * @param {string} options.source the configured data source name.
268
+ * @param {string} [options.token] bearer token; the server refuses without one.
269
+ * @returns {{execute: Function, describe: Function, export: Function}}
270
+ */
271
+ export function createRestProvider({ url, source, token } = {}) {
272
+ const base = String(url).replace(/\/$/, "");
273
+ const endpoint = `${base}/query/${encodeURIComponent(source)}`;
274
+ const headers = { "Content-Type": "application/json" };
275
+ if (token) {
276
+ headers.Authorization = `Bearer ${token}`;
277
+ }
278
+
279
+ return {
280
+ /**
281
+ * What the server says this source is: `{ name, schema, capabilities }`.
282
+ *
283
+ * A planner needs both halves before it can split anything (point 28) — the
284
+ * schema to validate against, the capabilities to know what may be pushed.
285
+ * The schema is the one this token is allowed to see.
286
+ */
287
+ async describe() {
288
+ const response = await fetch(`${base}/source/${encodeURIComponent(source)}`, {
289
+ headers: token ? { Authorization: headers.Authorization } : {},
290
+ redirect: "error",
291
+ });
292
+ const text = await response.text();
293
+ if (!response.ok) {
294
+ throw refusal(text, response.status);
295
+ }
296
+ return JSON.parse(text);
297
+ },
298
+
299
+ async execute(queryJson, _mode, { signal } = {}) {
300
+ const response = await fetch(endpoint, {
301
+ method: "POST",
302
+ headers,
303
+ body: queryJson,
304
+ signal,
305
+ redirect: "error",
306
+ });
307
+ const text = await response.text();
308
+ if (response.ok) {
309
+ return text;
310
+ }
311
+ throw refusal(text, response.status);
312
+ },
313
+
314
+ /**
315
+ * `POST /export/{source}`: every row of `query` in **one** streamed request,
316
+ * as a `Blob` (issue #2). The server reads its source through a cursor
317
+ * and writes the rows in the notation `exportRows` writes in the tab, so
318
+ * the file is the same byte for byte — one request instead of pieces, and
319
+ * against PostgreSQL no `OFFSET` that gets dearer with every piece.
320
+ *
321
+ * The server's rules are `/query`'s: the token, `allowed_fields`, the
322
+ * mandatory row filter. Its own bound is `max_export_rows`; more is an
323
+ * error with the server's sentence before the first byte. The row count
324
+ * arrives before the rows (`X-Total-Count`), so `maxRows` refuses without
325
+ * reading the body, and `onProgress` hears `{ rows, total }` once, at the
326
+ * end. `signal` aborts the request, the download included; the server
327
+ * notices at its next piece and ends the query.
328
+ *
329
+ * @param {object} query the query, as an object — as `exportRows` takes it.
330
+ * @param {object} [options] `format`, `signal`, `maxRows`, `onProgress`
331
+ * and the CSV options (`delimiter`, `bom`, `protectFormulas`, `null`).
332
+ * @returns {Promise<Blob>} `text/csv;charset=utf-8` or `application/json`.
333
+ */
334
+ async export(query, { format = "csv", signal, maxRows, onProgress, ...csv } = {}) {
335
+ for (const key of Object.keys(csv)) {
336
+ if (!CSV_OPTIONS.includes(key)) {
337
+ throw new TypeError(`export: unknown option "${key}"`);
338
+ }
339
+ }
340
+ // The server checks the options (a wrong one is its 400, with a
341
+ // sentence); here they only become parameters, under their own names.
342
+ const parameters = new URLSearchParams({ format });
343
+ for (const key of CSV_OPTIONS) {
344
+ if (csv[key] !== undefined) {
345
+ parameters.set(key, String(csv[key]));
346
+ }
347
+ }
348
+ const response = await fetch(`${base}/export/${encodeURIComponent(source)}?${parameters}`, {
349
+ method: "POST",
350
+ headers,
351
+ body: JSON.stringify(query),
352
+ signal,
353
+ redirect: "error",
354
+ });
355
+ if (!response.ok) {
356
+ throw refusal(await response.text(), response.status);
357
+ }
358
+ // The count is the server's promise about the rows that follow; without
359
+ // it there is nothing to hold `maxRows` or the progress against, and a
360
+ // missing one read as 0 would pass any bound.
361
+ const counted = response.headers.get("X-Total-Count");
362
+ if (counted === null || !/^\d+$/.test(counted.trim())) {
363
+ await response.body?.cancel();
364
+ throw new Error("export: the server did not say how many rows follow (X-Total-Count)");
365
+ }
366
+ const total = Number(counted);
367
+ if (maxRows !== undefined && total > maxRows) {
368
+ // Not one row more than needed: the body is dropped unread.
369
+ await response.body?.cancel();
370
+ throw coded(
371
+ "too_many_rows",
372
+ `export: ${total} rows match, more than the ${maxRows} an export may have (maxRows)`,
373
+ );
374
+ }
375
+ const blob = await response.blob();
376
+ onProgress?.({ rows: total, total });
377
+ // The type `exportRows` gives its Blob, whatever the header's spelling.
378
+ return new Blob([blob], {
379
+ type: format === "json" ? "application/json" : "text/csv;charset=utf-8",
380
+ });
381
+ },
382
+ };
383
+ }
384
+
385
+ /**
386
+ * A failed request as the `Error` it rejects with (issue #16). The message is
387
+ * the server's own sentence, or the status when the body is not the error
388
+ * form of point 23. The fields are what a page branches on without reading
389
+ * the sentence: `status` always, `code` and `path` when the error form has
390
+ * them.
391
+ */
392
+ function refusal(body, status) {
393
+ let form;
394
+ try {
395
+ form = JSON.parse(body)?.error;
396
+ } catch {
397
+ // A body that is not the error form: the status is all there is.
398
+ }
399
+ let message = `HTTP ${status}`;
400
+ if (form?.message) {
401
+ message = form.path ? `${form.message} (${form.path})` : form.message;
402
+ }
403
+ const error = new Error(message);
404
+ error.status = status;
405
+ if (typeof form?.code === "string") {
406
+ error.code = form.code;
407
+ }
408
+ if (typeof form?.path === "string") {
409
+ error.path = form.path;
410
+ }
411
+ return error;
412
+ }
413
+
414
+ /**
415
+ * An `Error` of the loader's own with a `code` a page can branch on (issue
416
+ * #16), in the style of the server's: the sentence is for the developer, the
417
+ * code for the page. The codes are frozen in
418
+ * crates/opengrid-web-components/src/api.rs, which reads them from the calls
419
+ * of this function.
420
+ */
421
+ function coded(code, message) {
422
+ const error = new Error(message);
423
+ error.code = code;
424
+ return error;
425
+ }
426
+
427
+ /**
428
+ * A provider that asks an `opengrid-server` for a whole **pivot** (point 53).
429
+ *
430
+ * The same shape as every other provider — `execute(json)` in, JSON out — so
431
+ * `set_provider` is unchanged; only the endpoint and the body differ. What comes
432
+ * back is the pivot wire form: the ordinary result under `result`, plus the
433
+ * level of each row and what each generated column stands for.
434
+ *
435
+ * @param {object} options
436
+ * @param {string} options.url base URL of the server.
437
+ * @param {string} options.source the configured data source name.
438
+ * @param {string} [options.token] bearer token.
439
+ * @returns {{execute: Function}}
440
+ */
441
+ export function createPivotProvider({ url, source, token } = {}) {
442
+ const endpoint = `${String(url).replace(/\/$/, "")}/pivot/${encodeURIComponent(source)}`;
443
+ const headers = { "Content-Type": "application/json" };
444
+ if (token) {
445
+ headers.Authorization = `Bearer ${token}`;
446
+ }
447
+
448
+ return {
449
+ async execute(pivotJson, _mode, { signal } = {}) {
450
+ const response = await fetch(endpoint, {
451
+ method: "POST",
452
+ headers,
453
+ body: pivotJson,
454
+ signal,
455
+ redirect: "error",
456
+ });
457
+ const text = await response.text();
458
+ if (response.ok) {
459
+ return text;
460
+ }
461
+ throw refusal(text, response.status);
462
+ },
463
+ };
464
+ }
465
+
466
+ /**
467
+ * A provider that splits each query between a remote source and the engine in
468
+ * this tab (plan point 28, plan/spezifikation/05-planner.md).
469
+ *
470
+ * Three steps, all of them JSON:
471
+ *
472
+ * 1. the `Planner` splits the query into the half the source can answer and the
473
+ * half that is left,
474
+ * 2. the remote provider answers its half,
475
+ * 3. the engine finishes the rest over that answer.
476
+ *
477
+ * When the source can answer everything, step 3 does not happen and the remote
478
+ * answer is passed through untouched — so a capable server costs nothing.
479
+ *
480
+ * The plan is handed to `onPlan` before anything is sent: that is how it becomes
481
+ * "offengelegt für Debugging, Performance-Analyse und Developer-Tools", and it
482
+ * is a plain object (`{ mode, describe, steps, source, client }`).
483
+ *
484
+ * @param {object} options
485
+ * @param {{execute: Function}} options.remote the source-side provider, usually
486
+ * `createRestProvider(...)`.
487
+ * @param {{plan: Function, finish: Function}} options.planner a `Planner` from
488
+ * the WASM module, built with the source's schema and capabilities.
489
+ * @param {string} [options.mode] `local`, `remote`, `hybrid` or `auto`; the
490
+ * element's `mode` attribute overrides it per query.
491
+ * @param {Function} [options.onPlan] called with each plan.
492
+ * @returns {{execute: Function}}
493
+ */
494
+ export function createHybridProvider({ remote, planner, mode = "auto", onPlan } = {}) {
495
+ return {
496
+ async execute(queryJson, elementMode, { signal } = {}) {
497
+ // The element's attribute wins when it has one: the page sets the default,
498
+ // the markup can override it per grid.
499
+ const plan = JSON.parse(planner.plan(queryJson, elementMode || mode));
500
+ if (onPlan) {
501
+ onPlan(plan);
502
+ }
503
+ // The remote half is the one that can be stopped; the engine's half runs
504
+ // after it and is synchronous. The source half has no element mode of
505
+ // its own: the plan already decided where it runs.
506
+ const partial = await remote.execute(JSON.stringify(plan.source), "", { signal });
507
+ if (!plan.client) {
508
+ return partial;
509
+ }
510
+ return planner.finish(JSON.stringify(plan.client), partial);
511
+ },
512
+ };
513
+ }
514
+
515
+ /** The options of `exportRows` that are its own. */
516
+ const EXPORT_OPTIONS = ["format", "chunkSize", "maxRows", "onProgress", "signal"];
517
+ /**
518
+ * The options handed to `export_csv` — only these, whatever else is passed.
519
+ * The same list as `CSV_OPTION_KEYS` in
520
+ * crates/opengrid-web-components/src/export.rs, which reads them; the two
521
+ * must stay in step (a test in that crate's api.rs compares them).
522
+ */
523
+ const CSV_OPTIONS = ["delimiter", "bom", "protectFormulas", "null"];
524
+ /** A result without rows or columns: enough for `export_csv` to read its options. */
525
+ const NO_ROWS = '{"total_count":0,"columns":[]}';
526
+
527
+ /**
528
+ * Every match of `query`, fetched through `provider` in pieces, as a `Blob` of
529
+ * CSV or JSON (plan point 84).
530
+ *
531
+ * The browser half of exporting the view: `get_query(host)` says what the
532
+ * reader sees, this fetches all of it and writes it in the notation the server
533
+ * uses too (`opengrid-export`, through the element module's `export_csv` and
534
+ * `export_json`). The grid has no export button; the button, the file name and
535
+ * what to say afterwards are the page's.
536
+ *
537
+ * **Stable pieces.** The pieces are `offset`/`limit` windows, and a window is
538
+ * only stable under a total order: the grid's sort has at least one key but may
539
+ * tie, and against PostgreSQL a row can then repeat or go missing across two
540
+ * `OFFSET`s. So every selected column not yet in the sort is appended to it,
541
+ * ascending. Rows equal in every selected column look the same whichever copy
542
+ * comes — and within a tie the export follows the columns, not the order the
543
+ * grid happened to show.
544
+ *
545
+ * **A source that changes is refused, not exported.** The tie-breaker fixes
546
+ * ties; it cannot fix rows that come or go between two pieces — they would
547
+ * shift the windows, and a row would repeat or go missing. So every piece has
548
+ * to report the first piece's `total_count`, and a piece that ends before
549
+ * `total` is an error too. A change that keeps the count and moves a row is not
550
+ * visible from here.
551
+ *
552
+ * **Bounded.** `total` is the first piece's `total_count`; a total above
553
+ * `maxRows` is an error before anything else is fetched, never a truncated
554
+ * file.
555
+ *
556
+ * **Errors a page can tell apart** (issue #16): its own carry a `code` —
557
+ * `too_many_rows`, `source_changed`, `module_not_loaded` — and a provider's
558
+ * rejection passes through as it came, the server's `status` and `code`
559
+ * included. A wrong option is a `TypeError`, an abort an `AbortError`.
560
+ *
561
+ * **Cancellable.** `signal` reaches the provider as `execute(json, mode,
562
+ * { signal })`; an abort rejects with an `AbortError` at once, leaves no request
563
+ * running where the provider can stop one, and produces no `Blob`.
564
+ *
565
+ * **One request where the provider can.** A provider with an `export(query,
566
+ * options)` method — `createRestProvider` — gets the whole export in one
567
+ * streamed request (issue #2): the same query, the same options checked here
568
+ * first, `signal`, `maxRows` and `onProgress` handed on. `chunkSize` does not
569
+ * apply, and `onProgress` hears the end.
570
+ *
571
+ * @param {{execute: Function}} provider any provider — the one the grid uses.
572
+ * @param {object} query a query without a window, as `get_query(host)` gives it.
573
+ * @param {object} [options] see `ExportOptions` in `loader.d.ts`.
574
+ * @returns {Promise<Blob>} `text/csv;charset=utf-8` or `application/json`.
575
+ */
576
+ export async function exportRows(provider, query, options = {}) {
577
+ for (const key of Object.keys(options)) {
578
+ if (!EXPORT_OPTIONS.includes(key) && !CSV_OPTIONS.includes(key)) {
579
+ throw new TypeError(`exportRows: unknown option "${key}"`);
580
+ }
581
+ }
582
+ const {
583
+ format = "csv",
584
+ chunkSize = 10_000,
585
+ maxRows = 1_000_000,
586
+ onProgress,
587
+ signal,
588
+ delimiter,
589
+ bom,
590
+ protectFormulas,
591
+ null: nullText,
592
+ } = options;
593
+ if (format !== "csv" && format !== "json") {
594
+ throw new TypeError(`exportRows: format is "csv" or "json", not ${JSON.stringify(format)}`);
595
+ }
596
+ if (format === "json") {
597
+ // A CSV option on a JSON export would do nothing, and do it silently.
598
+ const stray = CSV_OPTIONS.find((key) => options[key] !== undefined);
599
+ if (stray) {
600
+ throw new TypeError(`exportRows: "${stray}" is a CSV option, and this export is JSON`);
601
+ }
602
+ }
603
+ if (!Number.isSafeInteger(chunkSize) || chunkSize < 1) {
604
+ throw new TypeError("exportRows: chunkSize is a whole number of rows, at least 1");
605
+ }
606
+ if (!Number.isSafeInteger(maxRows) || maxRows < 0) {
607
+ throw new TypeError("exportRows: maxRows is a whole number of rows");
608
+ }
609
+ if (!query || typeof query !== "object") {
610
+ throw new TypeError("exportRows: no query — get_query answers null when there is nothing to export");
611
+ }
612
+ if (!Array.isArray(query.select) || query.select.length === 0) {
613
+ // The tie-breaker sorts by the selected columns, so it has to know them.
614
+ throw new TypeError("exportRows: the query names no columns in `select`");
615
+ }
616
+ if ("offset" in query || "limit" in query) {
617
+ throw new TypeError("exportRows: the query has a window; exportRows fetches every match itself");
618
+ }
619
+ if ("group" in query || "aggregate" in query) {
620
+ // Its output columns are aliases `select` does not name, so the
621
+ // tie-breaker could not make its order total. A view's query has neither.
622
+ throw new TypeError("exportRows: the query groups or aggregates; an export is of a view's rows");
623
+ }
624
+ if (signal?.aborted) {
625
+ throw aborted();
626
+ }
627
+
628
+ const loaded = await loadOpengrid();
629
+ if (loaded.fallback) {
630
+ throw coded(
631
+ "module_not_loaded",
632
+ "exportRows: the WebAssembly module did not load, and the export notation is in it",
633
+ );
634
+ }
635
+ const { module } = loaded;
636
+ const csvOptions = { delimiter, bom, protectFormulas, null: nullText };
637
+ if (format === "csv") {
638
+ // Read the options now: a wrong one should cost no request.
639
+ module.export_csv(NO_ROWS, csvOptions, false);
640
+ }
641
+
642
+ const sort = [...(query.sort ?? [])];
643
+ for (const field of query.select) {
644
+ if (!sort.some((key) => key.field === field)) {
645
+ sort.push({ field, direction: "asc" });
646
+ }
647
+ }
648
+
649
+ if (typeof provider.export === "function") {
650
+ // A provider that exports by itself — `createRestProvider` — does it in
651
+ // one request. The query is the same, tie-breaker included, so the file
652
+ // is the one the pieces would have made; one cursor needs no tie-breaker,
653
+ // but the order within a tie is then the same whichever way was taken.
654
+ const blob = await unlessAborted(
655
+ provider.export(
656
+ { ...query, sort },
657
+ { format, signal, maxRows, onProgress, ...(format === "csv" ? csvOptions : {}) },
658
+ ),
659
+ signal,
660
+ );
661
+ // An abort during `onProgress` still means no file.
662
+ if (signal?.aborted) {
663
+ throw aborted();
664
+ }
665
+ return blob;
666
+ }
667
+
668
+ // Each piece becomes a Blob of its own as soon as it is written, so its text
669
+ // can leave the JS heap; the browser may keep a Blob's bytes elsewhere.
670
+ const parts = format === "json" ? [new Blob(["["])] : [];
671
+ let rows = 0;
672
+ let total;
673
+ for (;;) {
674
+ if (signal?.aborted) {
675
+ throw aborted();
676
+ }
677
+ // After the first piece nothing past `total` is asked for.
678
+ const limit = total === undefined ? chunkSize : Math.min(chunkSize, total - rows);
679
+ const piece = JSON.stringify({ ...query, sort, offset: rows, limit });
680
+ const answer = await unlessAborted(ask(provider, piece, signal), signal);
681
+ const result = JSON.parse(answer);
682
+ const count = result.columns[0]?.values.length ?? 0;
683
+ const first = total === undefined;
684
+ if (first) {
685
+ total = result.total_count;
686
+ if (total > maxRows) {
687
+ throw coded(
688
+ "too_many_rows",
689
+ `exportRows: ${total} rows match, more than the ${maxRows} an export may have (maxRows)`,
690
+ );
691
+ }
692
+ } else if (result.total_count !== total) {
693
+ throw changed(`${total} rows matched at first, ${result.total_count} at row ${rows + 1}`);
694
+ }
695
+ if (count < limit && rows + count < total) {
696
+ throw changed(`the rows ended at ${rows + count} of ${total}`);
697
+ }
698
+ parts.push(
699
+ new Blob([
700
+ format === "csv"
701
+ ? module.export_csv(answer, csvOptions, first)
702
+ : // `first` here is "no row written yet", not "first piece": after an
703
+ // empty first piece the next one still leads without a comma.
704
+ module.export_json(answer, rows === 0),
705
+ ]),
706
+ );
707
+ rows += count;
708
+ onProgress?.({ rows, total });
709
+ if (rows >= total) {
710
+ break;
711
+ }
712
+ }
713
+ // An abort during the last `onProgress` still means no file.
714
+ if (signal?.aborted) {
715
+ throw aborted();
716
+ }
717
+ if (format === "json") {
718
+ parts.push(new Blob(["]"]));
719
+ }
720
+ return new Blob(parts, {
721
+ type: format === "csv" ? "text/csv;charset=utf-8" : "application/json",
722
+ });
723
+ }
724
+
725
+ /** One piece from the provider; a synchronous throw becomes a rejection. */
726
+ async function ask(provider, queryJson, signal) {
727
+ return provider.execute(queryJson, "", { signal });
728
+ }
729
+
730
+ /**
731
+ * `promise`, unless `signal` aborts first — then an `AbortError` at once. The
732
+ * tab and the worker cannot stop a query that has started; their answer is not
733
+ * waited for.
734
+ */
735
+ function unlessAborted(promise, signal) {
736
+ if (!signal) {
737
+ return promise;
738
+ }
739
+ return new Promise((resolve, reject) => {
740
+ const onAbort = () => reject(aborted());
741
+ signal.addEventListener("abort", onAbort, { once: true });
742
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
743
+ });
744
+ }
745
+
746
+ /**
747
+ * What an export rejects with when the source changed under it: the pieces no
748
+ * longer add up to one result, and a file of them would be wrong without
749
+ * saying so.
750
+ */
751
+ function changed(detail) {
752
+ return coded(
753
+ "source_changed",
754
+ `exportRows: the source changed during the export (${detail}); export again`,
755
+ );
756
+ }
757
+
758
+ /** What an aborted export rejects with, whatever reason `abort()` was given. */
759
+ function aborted() {
760
+ return new DOMException("The export was aborted.", "AbortError");
761
+ }
762
+
763
+ /**
764
+ * Supplies an element from one options object, and keeps it supplied (plan
765
+ * point 76).
766
+ *
767
+ * Every page — and every framework adapter — would otherwise have to know the
768
+ * rules of the module functions itself: wait for the module; set the texts
769
+ * before the provider, or the first paint is in English and the grid rebuilds;
770
+ * set the view before the provider, or the grid asks twice and announces
771
+ * twice; and write a controlled view back without looping. They live here,
772
+ * once.
773
+ *
774
+ * `update` applies only what changed. A key left out of an update keeps its
775
+ * value; a key given as `undefined` resets it (texts to English, no formats, no
776
+ * presentation, no choices) — except `provider`, which has no "none", and
777
+ * `view`, where `undefined` (or `null`) means the grid leads. Attributes
778
+ * (`label`, `columns`, `group-by`, …) are not options: the page or the
779
+ * framework sets them on the element as usual.
780
+ *
781
+ * **The view is controlled.** It is written whenever it differs from what the
782
+ * grid shows: after the reader sorted, passing the same saved view again puts
783
+ * it back. Writing back what the grid just reported costs nothing. `defaultView`
784
+ * is the uncontrolled form: applied once, then the grid leads.
785
+ *
786
+ * The view needs the element in the document (before that it has no view to
787
+ * set). On an element that is not, the view **and the provider** wait for the
788
+ * next `update` — together, so the first query still asks for the view.
789
+ *
790
+ * `connect` loads the module with `loadOpengrid()`, whose first call decides
791
+ * the URLs: a page that needs its own calls `loadOpengrid(options)` first.
792
+ *
793
+ * @param {HTMLElement} host an `<opengrid-grid>`, `-table` or `-pivot`.
794
+ * @param {object} options see `ConnectOptions` in `loader.d.ts`.
795
+ * @returns {{ready: Promise<{fallback: boolean, module?: object}>, update: Function, disconnect: Function}}
796
+ */
797
+ export function connect(host, options = {}) {
798
+ let current = { ...options };
799
+ let module;
800
+ let connected = true;
801
+ /** What was last written to the element, per option, as a comparable key. */
802
+ const applied = new Map();
803
+ /** The whole view the element last reported, as a key. */
804
+ let reported;
805
+ /** The view this connection last wrote, and what the grid reported for it. */
806
+ let written;
807
+ let writtenResult;
808
+ /** True while this connection's own `set_view` runs. */
809
+ let writing = false;
810
+ let defaultApplied = false;
811
+ let deferred = false;
812
+
813
+ const listeners = [
814
+ [
815
+ "opengrid-view-change",
816
+ (event) => {
817
+ reported = stableKey(event.detail.view);
818
+ if (writing) {
819
+ // The report of our own write: the grid took the view.
820
+ writtenResult = reported;
821
+ return;
822
+ }
823
+ current.onViewChange?.(event.detail.view);
824
+ },
825
+ ],
826
+ ["opengrid-selection-change", (event) => current.onSelectionChange?.(event.detail)],
827
+ ["opengrid-cell-change", (event) => current.onCellChange?.(event.detail)],
828
+ ];
829
+ for (const [type, listener] of listeners) {
830
+ host.addEventListener(type, listener);
831
+ }
832
+
833
+ /** Writes one option if it differs from what the element has. */
834
+ function write(name, value, key, apply) {
835
+ if (applied.has(name) && applied.get(name) === key) {
836
+ return;
837
+ }
838
+ applied.set(name, key);
839
+ apply(value);
840
+ }
841
+
842
+ /**
843
+ * Writes `view` unless the grid shows it already: it just reported exactly
844
+ * this, or this connection wrote it and the grid has not moved since. Only a
845
+ * view the grid took counts as written — one it refused (a column it does
846
+ * not have yet) is tried again on the next update.
847
+ */
848
+ function writeView(view) {
849
+ const key = stableKey(view);
850
+ if (key === reported || (key === written && writtenResult === reported)) {
851
+ return;
852
+ }
853
+ writing = true;
854
+ writtenResult = undefined;
855
+ try {
856
+ module.set_view(host, view);
857
+ } finally {
858
+ writing = false;
859
+ }
860
+ if (writtenResult !== undefined) {
861
+ written = key;
862
+ } else {
863
+ written = undefined;
864
+ }
865
+ // The view the element now has, whether or not it changed.
866
+ reported = stableKey(module.get_view(host));
867
+ if (written !== undefined) {
868
+ writtenResult = reported;
869
+ }
870
+ }
871
+
872
+ function apply(changed) {
873
+ if (!module || !connected) {
874
+ return;
875
+ }
876
+ // The order is the point: texts first (they are in the skeleton), then
877
+ // what the rows are drawn with, then the view, then the provider — so the
878
+ // first query is the only one and asks for the right thing.
879
+ if ("texts" in changed) {
880
+ const texts = changed.texts ?? {};
881
+ write("texts", texts, stableKey(texts), (value) => module.set_texts(host, value));
882
+ }
883
+ if ("formats" in changed) {
884
+ const formats = changed.formats ?? {};
885
+ write("formats", formats, formatsKey(formats), (value) => module.set_formats(host, value));
886
+ }
887
+ if ("presentation" in changed) {
888
+ const presentation = changed.presentation ?? {};
889
+ write("presentation", presentation, stableKey(presentation), (value) =>
890
+ module.set_columns(host, value),
891
+ );
892
+ }
893
+ if ("choices" in changed) {
894
+ const choices = changed.choices ?? {};
895
+ write("choices", choices, stableKey(choices), (value) => module.set_choices(host, value));
896
+ }
897
+
898
+ const wantsView =
899
+ current.view != null ? "view" in changed || deferred : !defaultApplied && current.defaultView != null;
900
+ if (wantsView && !host.isConnected) {
901
+ // Nothing to set a view on yet; the provider waits with it, or the grid
902
+ // would ask for its default order first.
903
+ if (!deferred) {
904
+ console.warn("[opengrid] connect: the element is not in the document; call update() once it is");
905
+ }
906
+ deferred = true;
907
+ return;
908
+ }
909
+ if (wantsView) {
910
+ deferred = false;
911
+ if (reported === undefined) {
912
+ reported = stableKey(module.get_view(host));
913
+ }
914
+ if (current.view != null) {
915
+ writeView(current.view);
916
+ } else {
917
+ defaultApplied = true;
918
+ writeView(current.defaultView);
919
+ }
920
+ }
921
+ if (("provider" in changed || "provider" in current) && current.provider) {
922
+ write("provider", current.provider, current.provider, (value) =>
923
+ module.set_provider(host, value),
924
+ );
925
+ }
926
+ }
927
+
928
+ const ready = loadOpengrid().then((loaded) => {
929
+ if (!loaded.fallback) {
930
+ module = loaded.module;
931
+ apply(current);
932
+ }
933
+ return loaded;
934
+ });
935
+
936
+ return {
937
+ ready,
938
+ update(next = {}) {
939
+ if (!connected) {
940
+ return;
941
+ }
942
+ current = { ...current, ...next };
943
+ apply(next);
944
+ },
945
+ disconnect() {
946
+ connected = false;
947
+ for (const [type, listener] of listeners) {
948
+ host.removeEventListener(type, listener);
949
+ }
950
+ },
951
+ };
952
+ }
953
+
954
+ /** A JSON key that does not depend on the order an object's keys were written in. */
955
+ function stableKey(value) {
956
+ return JSON.stringify(value, (_, inner) =>
957
+ inner && typeof inner === "object" && !Array.isArray(inner)
958
+ ? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
959
+ : inner,
960
+ );
961
+ }
962
+
963
+ /**
964
+ * Formats compare by identity where they are functions and by value where
965
+ * they are `Intl` options. Function identities are numbered per call site so
966
+ * two different functions never compare equal.
967
+ */
968
+ const functionIds = new WeakMap();
969
+ let nextFunctionId = 1;
970
+ function formatsKey(formats) {
971
+ return stableKey(
972
+ Object.fromEntries(
973
+ Object.entries(formats).map(([column, format]) => {
974
+ if (typeof format !== "function") {
975
+ return [column, format];
976
+ }
977
+ if (!functionIds.has(format)) {
978
+ functionIds.set(format, nextFunctionId++);
979
+ }
980
+ return [column, { function: functionIds.get(format) }];
981
+ }),
982
+ ),
983
+ );
984
+ }
985
+
986
+ /**
987
+ * The CSV bytes as a transferable `ArrayBuffer`.
988
+ *
989
+ * A view into a larger buffer is copied first, so transferring never detaches
990
+ * data the caller still owns; a plain `ArrayBuffer` is transferred as is.
991
+ */
992
+ function toTransferable(bytes) {
993
+ if (bytes instanceof ArrayBuffer) {
994
+ return bytes;
995
+ }
996
+ if (ArrayBuffer.isView(bytes)) {
997
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
998
+ }
999
+ throw new TypeError("bytes must be an ArrayBuffer or a typed array");
1000
+ }