@arqlet/engine-client 0.7.0 → 0.9.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/arqlet.wasm CHANGED
Binary file
package/elk.d.ts CHANGED
@@ -49,11 +49,37 @@ export interface ElkLayoutOptions {
49
49
  /** Runs the refinement after the layout. Default `false`. It removes conflicts (routes through nodes, shared lines);
50
50
  * a drawing without them comes back the same, a little later. */
51
51
  refine?: boolean;
52
+ /** Reports where each call's time went in `timings` (#152). Default `false`. */
53
+ timings?: boolean;
54
+ }
55
+
56
+ /** Where a call's time went, in ms (#152). The phases below `layout` are parts of it; 0 where the engine has no clock. */
57
+ export interface ElkTimings {
58
+ total: number;
59
+ layout: number;
60
+ placement: number;
61
+ organicStress: number;
62
+ separation: number;
63
+ repair: number;
64
+ portResolution: number;
65
+ routing: number;
66
+ /** Single pass, parts of `routing`. */
67
+ plan: number;
68
+ channelGrowth: number;
69
+ construction: number;
70
+ fallbackRouting: number;
71
+ finalization: number;
72
+ buses: number;
73
+ /** Outside `layout`: the ELK translation in and out, and a refinement on request. */
74
+ elkTranslation: number;
75
+ refinement: number;
52
76
  }
53
77
 
54
78
  export interface ElkLayout {
55
79
  /** ELK options without an Arqlet counterpart, reported by the last `layout` call. */
56
80
  diagnostics: string[];
81
+ /** With `timings: true`, where the last `layout` call's time went; otherwise `null`. */
82
+ timings: ElkTimings | null;
57
83
  /** Resolves with a copy of `graph`, laid out: positions, sizes, ports, labels and edge `sections`. */
58
84
  layout(graph: ElkNode): Promise<ElkNode>;
59
85
  }
package/elk.js CHANGED
@@ -2,14 +2,17 @@
2
2
  // `createEngine`, a worker or a backend): `layout(graph)` resolves with the graph in ELK's JSON form laid out (`x`, `y`,
3
3
  // sizes, ports, labels and edge `sections`), as `elk.layout(graph)` does. Not a 1:1 ELK: the options without a counterpart are
4
4
  // listed in `diagnostics` after each call (see crates/elk). `options` are Arqlet options that win over the translated
5
- // ones; `refine` runs the refinement after the layout.
6
- export function createElkLayout(run,{options,refine=false}={}) {
5
+ // ones; `refine` runs the refinement after the layout; with `timings` each call reports where its time went in `timings`
6
+ // (ms by phase; all 0 when the engine has no clock).
7
+ export function createElkLayout(run,{options,refine=false,timings=false}={}) {
7
8
  return {
8
9
  diagnostics:[],
10
+ timings:null,
9
11
  async layout(graph) {
10
- const response=await run({op:'elkLayout',graph,...(options?{options}:{}),refine});
12
+ const response=await run({op:'elkLayout',graph,...(options?{options}:{}),refine,...(timings?{timings:true}:{})});
11
13
  if(!response.ok) throw new Error(response.error);
12
14
  this.diagnostics=response.diagnostics;
15
+ this.timings=response.timings??null;
13
16
  return response.graph;
14
17
  },
15
18
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arqlet/engine-client",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "The Arqlet graph-layout engine as WebAssembly, with a loader, a worker protocol, an ELK-style layout call and preset sequencing. Provisional.",
5
5
  "keywords": [
6
6
  "graph",
@@ -47,6 +47,10 @@
47
47
  "types": "./session.d.ts",
48
48
  "default": "./session.js"
49
49
  },
50
+ "./view-controller.js": {
51
+ "types": "./view-controller.d.ts",
52
+ "default": "./view-controller.js"
53
+ },
50
54
  "./columns.js": {
51
55
  "types": "./columns.d.ts",
52
56
  "default": "./columns.js"
@@ -60,24 +64,27 @@
60
64
  "presets.js",
61
65
  "elk.js",
62
66
  "session.js",
67
+ "view-controller.js",
63
68
  "columns.js",
64
69
  "engine.d.ts",
65
70
  "wasm-client.d.ts",
66
71
  "presets.d.ts",
67
72
  "elk.d.ts",
68
73
  "session.d.ts",
74
+ "view-controller.d.ts",
69
75
  "columns.d.ts",
70
76
  "worker.js",
71
77
  "arqlet.wasm",
72
78
  "README.md",
73
79
  "LICENSE-APACHE",
74
- "LICENSE-MIT"
80
+ "LICENSE-MIT",
81
+ "THIRD_PARTY_NOTICES.md"
75
82
  ],
76
83
  "publishConfig": {
77
84
  "access": "public"
78
85
  },
79
86
  "dependencies": {
80
- "@arqlet/contracts": "^0.7.0"
87
+ "@arqlet/contracts": "^0.9.0"
81
88
  },
82
89
  "scripts": {
83
90
  "test": "node --test"
package/session.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type {Graph, GraphNeighbourhood, GraphPatch, GraphTrace, Hidden, NeighbourhoodAnswer, Overview, OverviewRequest, Scene, Snapshot, TraceAnswer} from '@arqlet/contracts';
1
+ import type {DetailsAnswer, FindAnswer, Graph, GraphNeighbourhood, GraphPatch, GraphTrace, Hidden, NeighbourhoodAnswer, Overview, OverviewRequest, Scene, Snapshot, TraceAnswer} from '@arqlet/contracts';
2
2
  import type {SceneColumns} from './columns.js';
3
3
  import type {EngineRequest, EngineResponse, Run} from './wasm-client.js';
4
4
 
@@ -37,7 +37,95 @@ export interface SessionResult {
37
37
  unchanged?: boolean;
38
38
  }
39
39
 
40
+ /** Provisional (ADR 0023, R1): one change of a session's content. Values are JSON; an integer stays an integer. */
41
+ export interface PayloadChange {
42
+ set?: {nodes?: Record<string, Record<string, unknown>>; edges?: Record<string, Record<string, unknown>>};
43
+ unset?: {nodes?: Record<string, string[]>; edges?: Record<string, string[]>};
44
+ clear?: boolean;
45
+ expectedContentRevision?: number;
46
+ }
47
+
48
+ /** Provisional (ADR 0023, R7): what a session holds, in estimated heap bytes per part. */
49
+ export interface SessionMemory {
50
+ ok: true;
51
+ estimated: true;
52
+ parts: Record<string, number>;
53
+ total: number;
54
+ nodes: number;
55
+ perNode: number;
56
+ /** From the WASM engine: the module's live heap, counted. */
57
+ heapBytes?: number;
58
+ /** From the WASM engine: the size of its linear memory, which is never given back. */
59
+ linearMemoryBytes?: number;
60
+ }
61
+
62
+ /** Provisional (ADR 0023, R2): one change group: a patch of the structure, a payload of the content, or both. */
63
+ export interface ChangeGroup {
64
+ patch?: GraphPatch;
65
+ payload?: Omit<PayloadChange, 'expectedContentRevision'>;
66
+ expectedSequence?: number;
67
+ }
68
+
69
+ /** The content's revision and counts after a change; ids the structure does not have are kept and counted. */
70
+ export interface PayloadAnswer {
71
+ ok: true;
72
+ contentRevision: number;
73
+ nodes: number;
74
+ edges: number;
75
+ keys: string[];
76
+ unknownNodes: number;
77
+ unknownEdges: number;
78
+ }
79
+
80
+ /** Provisional: a look into a container (`peek`): its contents as a scene, and the border edges per child shown. */
81
+ export interface PeekAnswer {
82
+ nodeId: string;
83
+ children: number;
84
+ shown: number;
85
+ omitted: number;
86
+ external: Record<string, {incoming: number; outgoing: number}>;
87
+ scene: Scene;
88
+ }
89
+
90
+ /** What `details` asks about: a node, or an edge (a drawn line or an edge of the source graph). */
91
+ export type DetailTarget = {nodeId: string; edgeId?: never} | {edgeId: string; nodeId?: never};
92
+
40
93
  /** The answer of a read-only request (`trace`, `neighbourhood`): its fields beside `ok: true`, or the error. */
94
+ /** Provisional (ADR 0021, M5b): what a query is given besides its text. */
95
+ export interface QueryInit {
96
+ /** The values of the `$name` parameters (JSON values; a map is refused). */
97
+ params?: Record<string, unknown>;
98
+ /** Also map the answer onto the current view (`shown`); costs a few milliseconds on a large view. */
99
+ view?: boolean;
100
+ /** Execution limits (steps of work, rows held, hops of an unbounded `*`). */
101
+ maxSteps?: number;
102
+ maxRows?: number;
103
+ maxHops?: number;
104
+ }
105
+
106
+ /** A value in a row of a query answer: a JSON value, a node as `{node: id}`, an edge as `{edge: id}`, or a list. */
107
+ export type QueryValue = null | boolean | number | string | {node: string} | {edge: string} | QueryValue[];
108
+
109
+ /** Provisional (ADR 0021, M5b): the answer of a query. */
110
+ export interface QueryAnswer {
111
+ columns: string[];
112
+ rows: QueryValue[][];
113
+ rowCount: number;
114
+ /** The ids of the nodes and edges in the rows, once each, in the order they first appear. */
115
+ nodes: string[];
116
+ edges: string[];
117
+ /** What the query could see: the session's source graph (resolved edges only). */
118
+ graph: {nodes: number; edges: number};
119
+ /** The content's revision, when the session has content. */
120
+ contentRevision?: number;
121
+ /** Content for ids the graph does not have (kept, ignored by the query). */
122
+ ignoredContent?: number;
123
+ /** Content values the query layer has no type for (a map), read as null. */
124
+ skippedValues?: number;
125
+ /** With `view: true`: the box that shows each node and the drawn line that carries each edge (null when none). */
126
+ shown?: {nodes: Record<string, string | null>; edges: Record<string, string | null>};
127
+ }
128
+
41
129
  export type ReadAnswer<T> = ({ok: true} & T) | {ok: false; error: string};
42
130
 
43
131
  /** Provisional: one graph, its current snapshot, and changes applied in order with revision checks. */
@@ -54,6 +142,18 @@ export interface Session {
54
142
  */
55
143
  import(graph: Graph, init?: {limit?: number; options?: Record<string, unknown>}): Promise<SessionResult>;
56
144
  /** Drops the snapshot; changes still under way resolve as stale. */
145
+ /**
146
+ * Provisional: continues from `snapshot` (made by the host), after the changes queued before; with `reset` (another
147
+ * view) at once, the changes still under way resolving as stale.
148
+ */
149
+ load(snapshot: Snapshot, options?: {reset?: boolean}): Promise<SessionResult>;
150
+ /** Provisional (#148): keeps the current snapshot under a mark (the same mark while it is unchanged); at most `limit` (default 32). */
151
+ keep(options?: {limit?: number}): Promise<{ok: boolean; mark?: number; error?: string}>;
152
+ /**
153
+ * Provisional (#148): the snapshot kept under `mark` becomes current again with its geometry (next layout version);
154
+ * `evicted` when it is no longer kept, `changed` when the graph changed since.
155
+ */
156
+ recall(mark: number): Promise<SessionResult & {evicted?: boolean; changed?: boolean}>;
57
157
  reset(): void;
58
158
  /** Whether container `id` is collapsed in the current snapshot. */
59
159
  isCollapsed(id: string): boolean;
@@ -80,6 +180,43 @@ export interface Session {
80
180
  nodeId: string | string[],
81
181
  init?: {hops?: number; direction?: 'out' | 'in' | 'both'; edgeKinds?: string[]},
82
182
  ): Promise<ReadAnswer<NeighbourhoodAnswer>>;
183
+ /**
184
+ * Provisional (read only): what the engine knows about a node or an edge (a drawn line or an edge of the source graph):
185
+ * the containers above a node and the box that shows it, what a collapsed box holds, the edges a line stands for.
186
+ */
187
+ details(target: DetailTarget, init?: {limit?: number}): Promise<ReadAnswer<DetailsAnswer>>;
188
+ /**
189
+ * Provisional (read only): the nodes whose label or id contains `query` (ignoring case), best first, with the box that
190
+ * shows each; at most `limit` (default 20), only `nodeKinds` if given.
191
+ */
192
+ find(query: string, init?: {limit?: number; nodeKinds?: string[]; key?: string}): Promise<ReadAnswer<FindAnswer>>;
193
+ /**
194
+ * Provisional (ADR 0021, M5b; read only): an openCypher query over the session's source graph and its content. Needs an
195
+ * engine built with the cargo feature `query`; otherwise `{ok: false, error}` says so. See {@link QueryAnswer}.
196
+ */
197
+ query(text: string, init?: QueryInit): Promise<ReadAnswer<QueryAnswer>>;
198
+ /**
199
+ * Provisional (ADR 0023, R1): sets, unsets or clears properties in the session's content (beside the snapshot, never in
200
+ * it). Needs a resident session.
201
+ */
202
+ payload(change: PayloadChange): Promise<PayloadAnswer | {ok: false; error?: string; stale?: true}>;
203
+ /** Provisional (ADR 0023, R2): structure and content changed as one group; the answer has its `sequence`. */
204
+ change(group: ChangeGroup): Promise<SessionResult & {sequence?: number; contentRevision?: number}>;
205
+ /** Provisional (ADR 0023, R2): the change groups after `sequence`, or `resync` when the log no longer has them. */
206
+ changesSince(sequence: number): Promise<{ok: true; sequence: number; changes?: Array<ChangeGroup & {sequence: number}>; resync?: true} | {ok: false; error?: string}>;
207
+ /**
208
+ * Provisional (ADR 0023, R7): moves a resident session to another engine (a new worker) so that the old one can be
209
+ * ended and its memory comes back; the view, the content and the change log's number move with it.
210
+ */
211
+ recycle(newEngine: Run): Promise<{ok: true; unchanged: true; sequence: number; contentRevision: number} | {ok: false; error?: string; stale?: true}>;
212
+ /** Provisional (ADR 0023, R7): what the session holds, part by part (estimated), and from WASM the module's heap. */
213
+ memory(): Promise<SessionMemory | {ok: false; error?: string}>;
214
+ /** Provisional (ADR 0023, R7): gives parts back; the snapshot stays. */
215
+ release(parts: Array<'content' | 'changeLog' | 'columns' | 'overview'>, init?: {keys?: string[]}): Promise<(SessionMemory & {released: number}) | {ok: false; error?: string; stale?: true}>;
216
+ /** Provisional (ADR 0023, R2): the whole content and the log's sequence (for a resync). */
217
+ content(): Promise<{ok: true; contentRevision: number; sequence: number; nodes: Record<string, Record<string, unknown>>; edges: Record<string, Record<string, unknown>>} | {ok: false; error?: string}>;
218
+ /** Provisional (read only): a look into a collapsed container without opening it. */
219
+ peek(nodeId: string, init?: {limit?: number}): Promise<ReadAnswer<PeekAnswer>>;
83
220
  /**
84
221
  * Provisional: changes the graph without a new import (removals first; a removed node takes what it holds and its
85
222
  * edges along); the view keeps its state and is laid out as a toggle lays it out (abstracting views) or again from
@@ -150,6 +287,15 @@ export function createSession(
150
287
  * Wraps a worker of `createEngineWorker` as an asynchronous run. `onPublication` receives the progressive publications
151
288
  * of a running request.
152
289
  */
290
+ /** Provisional: what `createViewController({refine})` runs refinements with. */
291
+ export type RefineRun = (
292
+ request: EngineRequest,
293
+ init?: {onPublication?: (publication: {jobId: string; sequence: number; snapshot: Snapshot}) => void; signal?: AbortSignal},
294
+ ) => Promise<EngineResponse>;
295
+
296
+ /** Provisional: a refinement engine on its own worker, with each progressive request's intermediate results. */
297
+ export function workerRefineRun(worker: Worker): RefineRun;
298
+
153
299
  export function workerRun(
154
300
  worker: Worker,
155
301
  init?: {onPublication?: (requestId: number, message: unknown) => void},
package/session.js CHANGED
@@ -12,6 +12,34 @@ import {columnsOfScene} from './columns.js';
12
12
  * Wraps a worker of `createEngineWorker` as an asynchronous `run`: each request gets an id, and the answer with that id
13
13
  * resolves it. Progressive publications are passed to `onPublication(requestId, message)`.
14
14
  */
15
+ /**
16
+ * Provisional: a refinement engine for `createViewController({refine})` on its own worker (`createEngineWorker`), so that
17
+ * refinement never waits behind the interactive steps: `(request, {onPublication, signal}) => Promise<answer>`, with the
18
+ * intermediate results of a progressive request (`refineProgressive`) handed to that request's `onPublication`. An
19
+ * aborted request resolves at once as cancelled; the worker finishes it in the background and its answer is dropped.
20
+ */
21
+ export function workerRefineRun(worker) {
22
+ let next = 0;
23
+ const waiting = new Map();
24
+ worker.addEventListener('message', ({data}) => {
25
+ const pending = waiting.get(data?.requestId);
26
+ if (!pending) return;
27
+ if (data.publication !== undefined) { pending.onPublication?.(data.publication); return; }
28
+ waiting.delete(data.requestId);
29
+ const {requestId, ...response} = data;
30
+ pending.resolve(response);
31
+ });
32
+ return (request, {onPublication, signal} = {}) => new Promise(resolve => {
33
+ const requestId = ++next;
34
+ if (signal?.aborted) { resolve({ok: false, cancelled: true}); return; }
35
+ waiting.set(requestId, {resolve, onPublication});
36
+ signal?.addEventListener('abort', () => {
37
+ if (waiting.delete(requestId)) resolve({ok: false, cancelled: true});
38
+ }, {once: true});
39
+ worker.postMessage({requestId, request});
40
+ });
41
+ }
42
+
15
43
  export function workerRun(worker, {onPublication} = {}) {
16
44
  let next = 0;
17
45
  const waiting = new Map();
@@ -87,14 +115,19 @@ export function httpRun(base = '/api', {fetchImpl = globalThis.fetch} = {}) {
87
115
  */
88
116
  let dragCounter = 0;
89
117
 
90
- export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
118
+ export function createSession(engine, {onChange, resident: wanted = 'auto'} = {}) {
119
+ // The engine and, when resident, its session: replaced by `recycle` (a new worker, ADR 0023 R7).
120
+ let run = engine;
91
121
  let snapshot = null;
92
122
  let generation = 0;
123
+ // Snapshots kept by mark when the session is not resident (#148); a resident session keeps them in the engine.
124
+ let kept = [];
125
+ let marks = 0;
93
126
  let queue = Promise.resolve();
94
127
  const scenes = new WeakMap();
95
128
  if (wanted === true && !run.openSession) throw Error('This engine has no resident sessions');
96
129
  const resident = wanted === true || (wanted === 'auto' && typeof run.openSession === 'function');
97
- const opened = resident ? Promise.resolve(run.openSession()) : null;
130
+ let opened = resident ? Promise.resolve(run.openSession()) : null;
98
131
  // The engine call: with a resident session, the request goes to it and its answer is turned into the shape of an
99
132
  // answer with a snapshot (the state), its scene remembered for that state.
100
133
  const call = async request => {
@@ -104,7 +137,9 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
104
137
  if (!answer.ok || answer.revision === undefined) return answer;
105
138
  const state = {revision: answer.revision, layoutVersion: answer.layoutVersion, collapsedIds: answer.collapsedIds};
106
139
  if (answer.scene) scenes.set(state, answer.scene);
107
- return {ok: true, snapshot: state};
140
+ // The change log's number and the content's revision of a source change (ADR 0023, R1 and R2), when the answer has them.
141
+ return {ok: true, snapshot: state, ...(answer.sequence !== undefined ? {sequence: answer.sequence} : {}),
142
+ ...(answer.contentRevision !== undefined ? {contentRevision: answer.contentRevision} : {})};
108
143
  };
109
144
 
110
145
  // Runs `step` after every change before it; its answer counts only if no import or reset came in between.
@@ -152,14 +187,68 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
152
187
  * Any change still under way is dropped.
153
188
  */
154
189
  import(graph, {limit = Math.min(graph.nodes.length, MAX_VIEW_LIMIT), options} = {}) {
190
+ // A new view does not wait for the changes still under way: they resolve as stale.
155
191
  generation++;
192
+ queue = Promise.resolve();
193
+ kept = [];
156
194
  return enqueue(() => call({op: 'import', graph, limit, ...(options ? {options} : {})}));
157
195
  },
158
196
 
197
+ /**
198
+ * Provisional: continues from `snapshot` (a host made it: a drag, a refinement, a document it loaded), after the changes
199
+ * queued before; with a resident session the engine takes it over (`load`).
200
+ */
201
+ load(snapshot, {reset = false} = {}) {
202
+ // With `reset` (another view) it does not wait for the changes still under way: they resolve as stale.
203
+ // The same graph keeps the snapshots kept for `recall` (#148); another one (`reset`) drops them.
204
+ if (reset) {
205
+ generation++;
206
+ queue = Promise.resolve();
207
+ kept = [];
208
+ }
209
+ return enqueue(() => (resident ? call({op: 'load', snapshot, keep: !reset}) : {ok: true, snapshot}));
210
+ },
211
+
212
+ /**
213
+ * Provisional (#148): keeps the current snapshot under a mark, `{ok, mark}` (the same mark while it is unchanged), at
214
+ * most `limit` (default 32) of them, the oldest dropped first. With a resident session the engine keeps them (only the
215
+ * mark crosses); otherwise this session does. A new import drops them.
216
+ */
217
+ keep({limit = 32} = {}) {
218
+ return enqueue(async () => {
219
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
220
+ if (resident) return call({op: 'keep', limit});
221
+ const last = kept.at(-1);
222
+ if (last && last.snapshot === snapshot) return {ok: true, mark: last.mark};
223
+ kept.push({mark: ++marks, snapshot});
224
+ if (kept.length > limit) kept.splice(0, kept.length - limit);
225
+ return {ok: true, mark: marks};
226
+ });
227
+ },
228
+
229
+ /**
230
+ * Provisional (#148): makes the snapshot kept under `mark` current again (its geometry as it was) under the next layout
231
+ * version. `{ok: false, evicted: true}` when it is no longer kept, `{ok: false, changed: true}` when the graph changed
232
+ * since (another revision); then lay out again from the decisions (`restore`).
233
+ */
234
+ recall(mark) {
235
+ return enqueue(async () => {
236
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
237
+ if (resident) return call({op: 'recall', mark});
238
+ const entry = kept.find(k => k.mark === mark);
239
+ if (!entry) return {ok: false, evicted: true, error: `The snapshot of mark ${mark} is no longer kept`};
240
+ if (entry.snapshot.revision !== snapshot.revision) {
241
+ return {ok: false, changed: true, error: `The graph changed since mark ${mark}`};
242
+ }
243
+ return {ok: true, snapshot: {...entry.snapshot, layoutVersion: snapshot.layoutVersion + 1}};
244
+ });
245
+ },
246
+
159
247
  /** Drops the snapshot; changes still under way resolve as stale. */
160
248
  reset() {
161
249
  generation++;
162
250
  snapshot = null;
251
+ kept = [];
163
252
  },
164
253
 
165
254
  /** Whether container `id` is collapsed in the current snapshot. */
@@ -195,6 +284,108 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
195
284
  * `{ok, nodes, edges, hops, visible: {nodes, routes}, distance}` as for `trace`; `nodes` can go to `reveal`.
196
285
  * `direction`: `out`, `in` or `both` (default); `edgeKinds`: follow only edges of these kinds.
197
286
  */
287
+ /**
288
+ * Provisional (search, read only): the nodes of the source graph whose label or id contains `query` (ignoring case),
289
+ * best first, with the containers above each and the box that shows it (also inside collapsed groups); at most
290
+ * `limit` (default 20), only `nodeKinds` if given; `total` counts them all.
291
+ */
292
+ /**
293
+ * Provisional (ADR 0023, R1): sets, unsets or clears properties of nodes and edges in the session's content, as one
294
+ * change: `{set: {nodes: {id: {key: value}}, edges: {…}}, unset: {nodes: {id: [key]}}, clear, expectedContentRevision}`.
295
+ * Kept beside the snapshot (never in it; layout never reads it); `details` answers the properties, `find` with `key`
296
+ * searches one. Needs a resident session; a new import starts the content empty.
297
+ */
298
+ payload(change = {}) {
299
+ if (!resident) return Promise.resolve({ok: false, error: 'payload needs a resident session'});
300
+ return enqueue(() => call({op: 'payload', ...change}));
301
+ },
302
+
303
+ /**
304
+ * Provisional (ADR 0023, R2): a change of structure and content as one group, all of it or nothing:
305
+ * `{patch: {nodes, edges, removeNodes, removeEdges, memberships}, payload: {set, unset, clear}, expectedSequence}`.
306
+ * The answer carries the group's `sequence` in the session's change log. Needs a resident session.
307
+ */
308
+ change(group = {}) {
309
+ if (!resident) return Promise.resolve({ok: false, error: 'change needs a resident session'});
310
+ return enqueue(() => call({op: 'change', ...group}));
311
+ },
312
+
313
+ /**
314
+ * Provisional (ADR 0023, R2, read only): the change groups after `sequence` (`{sequence, changes}`), or `{resync: true}`
315
+ * when some of them are no longer in the log (then take a new snapshot and the `content`).
316
+ */
317
+ async changesSince(sequence) {
318
+ if (!resident) return {ok: false, error: 'changesSince needs a resident session'};
319
+ return call({op: 'changesSince', sequence});
320
+ },
321
+
322
+ /**
323
+ * Provisional (ADR 0023, R7, read only): what the session holds, part by part, in estimated heap bytes (`parts`,
324
+ * `total`, `perNode`); from the WASM engine also the module's live heap (`heapBytes`) and its linear memory
325
+ * (`linearMemoryBytes`), which WebAssembly never gives back (only a new worker does).
326
+ */
327
+ async memory() {
328
+ if (!resident) return {ok: false, error: 'memory needs a resident session'};
329
+ return call({op: 'memory'});
330
+ },
331
+
332
+ /**
333
+ * Provisional (ADR 0023, R7): gives parts back: `content` (all, or only `keys`), `changeLog` (a replica behind it then
334
+ * resyncs), `columns`, `overview`. The snapshot stays; the answer is `memory` after it, with `released`.
335
+ */
336
+ release(parts, {keys} = {}) {
337
+ if (!resident) return Promise.resolve({ok: false, error: 'release needs a resident session'});
338
+ return enqueue(() => call({op: 'release', parts, ...(keys ? {keys} : {})}));
339
+ },
340
+
341
+ /** Provisional (ADR 0023, R2, read only): the whole content and the log's sequence, for a replica that resyncs. */
342
+ async content() {
343
+ if (!resident) return {ok: false, error: 'content needs a resident session'};
344
+ return call({op: 'content'});
345
+ },
346
+
347
+ /**
348
+ * Provisional (read only): a look into the collapsed container `nodeId` without opening it: its contents laid out on
349
+ * their own as a small scene (the containers inside collapsed, at most `limit` direct children, default 50), and per
350
+ * child shown the edges that cross the container's border (`external`).
351
+ */
352
+ async peek(nodeId, {limit} = {}) {
353
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
354
+ return call({op: 'peek', snapshot, nodeId, ...(limit !== undefined ? {limit} : {})});
355
+ },
356
+
357
+ async find(query, {limit, nodeKinds, key} = {}) {
358
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
359
+ return call({op: 'find', snapshot, query, ...(limit !== undefined ? {limit} : {}), ...(nodeKinds ? {nodeKinds} : {}),
360
+ ...(key ? {key} : {})});
361
+ },
362
+
363
+ /**
364
+ * Provisional (ADR 0021, M5b; read only, needs an engine built with the cargo feature `query`): an openCypher query over
365
+ * the session's source graph and its content (`payload`): `{ok, columns, rows, rowCount, nodes, edges, graph, ...}`.
366
+ * Nodes and edges in `rows` are `{node: id}` and `{edge: id}`; `nodes` and `edges` list the ids once each. `params`
367
+ * are the `$name` values; `maxSteps`, `maxRows` and `maxHops` lower or raise the execution limits; with `view: true`
368
+ * the answer also has `shown`, the box that shows each node and the line that carries each edge. A failure is
369
+ * `{ok: false, error: 'query <class>: ...'}` with the class `syntax`, `unsupported`, `runtime` or `limit`. A query
370
+ * sees the source graph the engine kept (for a bounded import the selection; `graph` gives its size).
371
+ */
372
+ async query(text, {params, view, maxSteps, maxRows, maxHops} = {}) {
373
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
374
+ return call({op: 'query', snapshot, query: text, ...(params ? {params} : {}), ...(view ? {view: true} : {}),
375
+ ...(maxSteps !== undefined ? {maxSteps} : {}), ...(maxRows !== undefined ? {maxRows} : {}),
376
+ ...(maxHops !== undefined ? {maxHops} : {})});
377
+ },
378
+
379
+ /**
380
+ * Provisional (view details, read only): what the engine knows about a node (`{nodeId}`) or an edge (`{edgeId}`, a
381
+ * drawn line or an edge of the source graph): the containers above a node and the box that shows it, what a collapsed
382
+ * box holds, the edges a line stands for in either direction (at most `limit` ids each, counts complete).
383
+ */
384
+ async details(target, {limit} = {}) {
385
+ if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
386
+ return call({op: 'details', snapshot, ...target, ...(limit !== undefined ? {limit} : {})});
387
+ },
388
+
198
389
  async neighbourhood(nodeId, {hops, direction, edgeKinds} = {}) {
199
390
  if (!snapshot) return {ok: false, error: 'Nothing imported yet.'};
200
391
  return call({op: 'neighbourhood', snapshot, ...(Array.isArray(nodeId) ? {nodeIds: nodeId} : {nodeId}),
@@ -332,6 +523,39 @@ export function createSession(run, {onChange, resident: wanted = 'auto'} = {}) {
332
523
  /** Whether the snapshot stays in the engine (see `createSession`). */
333
524
  get resident() { return resident; },
334
525
 
526
+ /**
527
+ * Provisional (ADR 0023, R7): moves a resident session to another engine (`newEngine`, typically a new worker), so that
528
+ * the old one can be ended and its memory comes back: WebAssembly never shrinks its linear memory, a new worker starts
529
+ * small. The snapshot, the content (with its revision) and the change log's number move; the log's groups do not, so
530
+ * a replica behind that number resyncs. The engines give identical results, so the view does not change. Runs after
531
+ * the changes queued before it; on a refusal the session stays on the old engine. The host ends the old worker after.
532
+ */
533
+ recycle(newEngine) {
534
+ if (!resident) return Promise.resolve({ok: false, error: 'recycle needs a resident session'});
535
+ if (typeof newEngine?.openSession !== 'function') {
536
+ return Promise.resolve({ok: false, error: 'recycle needs an engine with resident sessions'});
537
+ }
538
+ return enqueue(async () => {
539
+ const old = await opened;
540
+ const exported = await old.run({op: 'export'});
541
+ if (!exported.ok) return exported;
542
+ const content = await old.run({op: 'content'});
543
+ if (!content.ok) return content;
544
+ const fresh = await newEngine.openSession();
545
+ // No scene in the answer: the host has it already, and writing it would grow the new engine's memory.
546
+ const loaded = await fresh.run({op: 'load', scene: false, snapshot: exported.snapshot, sequence: content.sequence,
547
+ content: {contentRevision: content.contentRevision, nodes: content.nodes, edges: content.edges}});
548
+ if (!loaded.ok) {
549
+ await fresh.close?.();
550
+ return loaded;
551
+ }
552
+ await old.close?.();
553
+ run = newEngine;
554
+ opened = Promise.resolve(fresh);
555
+ return {ok: true, unchanged: true, sequence: content.sequence, contentRevision: content.contentRevision};
556
+ });
557
+ },
558
+
335
559
  /** Ends a resident session in the engine (frees its snapshot). The session object is not usable afterwards. */
336
560
  async close() {
337
561
  generation++;