@tinyactors/node 0.1.0 → 0.3.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.
Files changed (43) hide show
  1. package/README.md +648 -154
  2. package/docs/guide/browser.md +494 -0
  3. package/docs/guide/capacity.md +202 -0
  4. package/docs/guide/charts.md +578 -0
  5. package/docs/guide/hibernation.md +201 -0
  6. package/docs/guide/inspection.md +381 -0
  7. package/docs/guide/io-processors.md +269 -0
  8. package/docs/guide/migration.md +323 -0
  9. package/docs/guide/other-systems.md +275 -0
  10. package/docs/guide/quickjs.md +135 -0
  11. package/docs/guide/services.md +317 -0
  12. package/docs/guide/snapshots.md +186 -0
  13. package/docs/guide/telemetry.md +265 -0
  14. package/docs/guide/testing.md +272 -0
  15. package/docs/values.md +107 -0
  16. package/index.d.ts +1166 -1820
  17. package/index.mjs +6 -0
  18. package/lib/convenience.mjs +162 -0
  19. package/lib/direct.mjs +65 -0
  20. package/package.json +29 -16
  21. package/index.js +0 -34
  22. package/lib/actor.js +0 -85
  23. package/lib/debug/breakpoints.js +0 -349
  24. package/lib/debug/console.js +0 -149
  25. package/lib/debug/expressions.js +0 -133
  26. package/lib/debug/frames.js +0 -119
  27. package/lib/debug/labels.js +0 -142
  28. package/lib/debug/macrosteps.js +0 -207
  29. package/lib/debug/protocol.js +0 -186
  30. package/lib/debug/sources.js +0 -218
  31. package/lib/debug/variables.js +0 -265
  32. package/lib/debug.js +0 -1434
  33. package/lib/definition.js +0 -139
  34. package/lib/errors.js +0 -24
  35. package/lib/events.js +0 -56
  36. package/lib/image.js +0 -90
  37. package/lib/loader.js +0 -68
  38. package/lib/metrics.js +0 -333
  39. package/lib/native.js +0 -8
  40. package/lib/otlp.js +0 -332
  41. package/lib/statechart.js +0 -768
  42. package/lib/system.js +0 -2183
  43. package/lib/tracing.js +0 -164
@@ -1,349 +0,0 @@
1
- 'use strict';
2
-
3
- // Breakpoints: function breakpoints by name, line breakpoints on the
4
- // element a source line holds (core ADR 0085), the exception filters, and
5
- // data breakpoints on data-model locations. Each is found in the records of
6
- // a macrostep that ended (lib/debug/macrosteps). A live actor is never
7
- // stopped, so every breakpoint is a tracepoint: the session says where it
8
- // would have stopped. A line breakpoint with a log message is a logpoint:
9
- // it writes its message instead.
10
-
11
- const { TinyactorsError } = require('../errors');
12
-
13
- const EXCEPTION_FILTERS = Object.freeze([
14
- { filter: 'error.execution', label: 'error.execution',
15
- description: 'An action, a guard or a <data> failed, and core raised error.execution' },
16
- { filter: 'error.communication', label: 'error.communication',
17
- description: 'A <send> or an invocation could not reach its target' },
18
- { filter: 'error.platform', label: 'error.platform', description: 'The platform raised an error event' },
19
- { filter: 'ignored', label: 'Ignored events',
20
- description: 'An event was taken and enabled no transition (core ADR 0072)' },
21
- { filter: 'stopped', label: 'Out of memory', description: 'A run stopped because an allocation failed (core ADR 0070)' },
22
- { filter: 'runaway', label: 'Runaway macrosteps',
23
- description: 'A macrostep ran its microstep limit, and the actor was quarantined (core ADR 0075)' },
24
- ]);
25
- const FILTERS = EXCEPTION_FILTERS.map((entry) => entry.filter);
26
- const ERRORS = FILTERS.slice(0, 3);
27
-
28
- // SCXML event descriptors match by prefix at dot boundaries (SCXML 3.12.1).
29
- function matchesEvent(descriptor, name) {
30
- if (typeof name !== 'string') return false;
31
- const bare = descriptor.replace(/\.\*$/, '').replace(/\.$/, '');
32
- return bare === '*' || name === bare || name.startsWith(`${bare}.`);
33
- }
34
-
35
- const normalize = (text) => text.replaceAll('->', '→').replace(/\s+/g, ' ').trim();
36
-
37
- // `5` and `>= 5` stop from the fifth hit on, `== 5` only at it, `% 5` at
38
- // every fifth.
39
- function hitConditionMet(text, hits) {
40
- if (text === undefined || text === null || String(text).trim() === '') return true;
41
- const match = /^\s*(>=|>|==|<=|<|%)?\s*(\d+)\s*$/.exec(String(text));
42
- if (match === null) return true;
43
- const count = Number(match[2]);
44
- switch (match[1]) {
45
- case '>': return hits > count;
46
- case '==': return hits === count;
47
- case '<=': return hits <= count;
48
- case '<': return hits < count;
49
- case '%': return count > 0 && hits % count === 0;
50
- default: return hits >= count;
51
- }
52
- }
53
-
54
- function parseFunction(name) {
55
- let match = /^exit:\s*(\S+)$/.exec(name);
56
- if (match !== null) return { kind: 'exit', target: match[1] };
57
- match = /^on:\s*(\S+)$/.exec(name);
58
- if (match !== null) return { kind: 'on', target: match[1] };
59
- if (/(→|->)/.test(name)) return { kind: 'transition', target: normalize(name) };
60
- return { kind: 'entry', target: name };
61
- }
62
-
63
- function describe(breakpoint) {
64
- switch (breakpoint.kind) {
65
- case 'entry': return `entered ${breakpoint.target}`;
66
- case 'exit': return `exited ${breakpoint.target}`;
67
- case 'on': return `took ${breakpoint.target}`;
68
- default: return breakpoint.target;
69
- }
70
- }
71
-
72
- // A line breakpoint's element, as the breakpoint's description names it.
73
- function describeLine(breakpoint) {
74
- const { element } = breakpoint;
75
- return `line ${breakpoint.line} (${element.kind} ${element.name ?? element.id})`;
76
- }
77
-
78
- // The line breakpoints of one DAP Source are kept under its path, or its
79
- // sourceReference for a virtual source (napi ADR 0026).
80
- const sourceKey = (source) => (source.path !== undefined ? `path ${source.path}` : `reference ${source.sourceReference}`);
81
-
82
- // A condition that is not blank.
83
- function hasCondition(breakpoint) {
84
- return breakpoint.condition !== undefined && breakpoint.condition !== null && String(breakpoint.condition).trim() !== '';
85
- }
86
-
87
- class Breakpoints {
88
- #functions = [];
89
- #data = [];
90
- #lines = new Map();
91
- #filters = new Set();
92
-
93
- /** Whether the client asked to stop for the exception filter `filter`. */
94
- wants(filter) {
95
- return this.#filters.has(filter);
96
- }
97
- #next = 0;
98
-
99
- #allLines() {
100
- return [...this.#lines.values()].flatMap(({ entries }) => entries).filter((entry) => entry.element !== undefined);
101
- }
102
-
103
- /**
104
- * setBreakpoints for one source, { path } or { sourceReference } (napi
105
- * ADR 0026): replaces that source's breakpoints. `resolve(line)` answers
106
- * the element the line stands for, as { element: { kind, id, name },
107
- * line, column, source }, or a string saying why there is none. Answers
108
- * DAP Breakpoint objects.
109
- */
110
- setLines(source, specs, resolve) {
111
- const entries = [];
112
- const answered = specs.map((spec) => {
113
- const id = (this.#next += 1);
114
- const found = resolve(Number(spec?.line));
115
- if (typeof found === 'string' || found === undefined) {
116
- entries.push({ id, spec });
117
- return { id, verified: false, message: found ?? `no state, transition or action at line ${spec?.line}` };
118
- }
119
- const breakpoint = { id, kind: 'line', spec, line: found.line, element: found.element, condition: spec.condition,
120
- hitCondition: spec.hitCondition, logMessage: spec.logMessage, hits: 0 };
121
- entries.push(breakpoint);
122
- return { id, verified: true, line: found.line, column: found.column, source: found.source };
123
- });
124
- this.#lines.set(sourceKey(source), { source, entries });
125
- return answered;
126
- }
127
-
128
- /** The placed breakpoints of every kind that have a condition. */
129
- get conditioned() {
130
- const lines = [...this.#lines.values()].flatMap(({ entries }) => entries.filter((entry) => entry.kind === 'line'));
131
- return [...lines, ...this.#functions, ...this.#data].filter((breakpoint) => hasCondition(breakpoint));
132
- }
133
-
134
- /** The sources with line breakpoints and what the client asked for, to resolve again later. */
135
- get lineRequests() {
136
- return [...this.#lines.values()].map(({ source, entries }) => ({ source, specs: entries.map((entry) => entry.spec),
137
- ids: entries.map((entry) => entry.id) }));
138
- }
139
-
140
- /**
141
- * Resolves a source's line breakpoints again (after attaching), keeping
142
- * their IDs. Answers the DAP Breakpoint objects, for `breakpoint` events.
143
- */
144
- relocate(source, resolve) {
145
- const entries = this.#lines.get(sourceKey(source))?.entries ?? [];
146
- const answered = [];
147
- this.#lines.set(sourceKey(source), { source, entries: entries.map((entry) => {
148
- const found = resolve(Number(entry.spec?.line));
149
- if (typeof found === 'string' || found === undefined) {
150
- answered.push({ id: entry.id, verified: false,
151
- message: found ?? `no state, transition or action at line ${entry.spec?.line}` });
152
- return { id: entry.id, spec: entry.spec };
153
- }
154
- answered.push({ id: entry.id, verified: true, line: found.line, column: found.column, source: found.source });
155
- return { ...entry, kind: 'line', line: found.line, element: found.element, condition: entry.spec.condition,
156
- hitCondition: entry.spec.hitCondition, logMessage: entry.spec.logMessage, hits: entry.hits ?? 0 };
157
- }) });
158
- return answered;
159
- }
160
-
161
- /**
162
- * setFunctionBreakpoints: replaces them all. `check(breakpoint)` answers
163
- * undefined or why the breakpoint cannot be verified. Answers DAP
164
- * Breakpoint objects.
165
- */
166
- setFunctions(specs, check) {
167
- this.#functions = [];
168
- return specs.map((spec) => {
169
- const name = String(spec?.name ?? '').trim();
170
- const breakpoint = { id: (this.#next += 1), name, ...parseFunction(name), condition: spec?.condition,
171
- hitCondition: spec?.hitCondition, hits: 0 };
172
- const problem = name === '' ? 'a function breakpoint needs a name' : check(breakpoint);
173
- if (problem !== undefined) {
174
- return { id: breakpoint.id, verified: false, message: problem };
175
- }
176
- this.#functions.push(breakpoint);
177
- return { id: breakpoint.id, verified: true };
178
- });
179
- }
180
-
181
- setFilters(filters) {
182
- const unknown = filters.filter((filter) => !FILTERS.includes(filter));
183
- if (unknown.length > 0) {
184
- throw new TinyactorsError(`unknown exception filter(s): ${unknown.join(', ')}`, 'invalid');
185
- }
186
- this.#filters = new Set(filters);
187
- }
188
-
189
- /**
190
- * setDataBreakpoints: replaces them all. A dataId is the thread's label
191
- * and a path of keys as JSON: `acct_1 ["failures"]`. `check(breakpoint)`
192
- * as for functions.
193
- */
194
- setData(specs, check) {
195
- this.#data = [];
196
- return specs.map((spec) => {
197
- const parsed = Breakpoints.parseDataID(spec?.dataId);
198
- const id = (this.#next += 1);
199
- if (parsed === undefined) {
200
- return { id, verified: false, message: `${JSON.stringify(spec?.dataId)} is not a data-model location` };
201
- }
202
- if (spec.accessType !== undefined && spec.accessType !== 'write') {
203
- return { id, verified: false, message: 'only writes can be watched: core traces assignments, not reads' };
204
- }
205
- const breakpoint = { id, ...parsed, dataId: spec.dataId, condition: spec.condition,
206
- hitCondition: spec.hitCondition, hits: 0 };
207
- const problem = check(breakpoint);
208
- if (problem !== undefined) {
209
- return { id, verified: false, message: problem };
210
- }
211
- this.#data.push(breakpoint);
212
- return { id, verified: true };
213
- });
214
- }
215
-
216
- static dataID(label, path) {
217
- return `${label} ${JSON.stringify(path)}`;
218
- }
219
-
220
- // A label can have spaces (`renewal/r1 invocation kid`), so the path is what
221
- // follows the first ` [` that starts a JSON array.
222
- static parseDataID(text) {
223
- if (typeof text !== 'string') return undefined;
224
- for (let at = text.indexOf(' ['); at > 0; at = text.indexOf(' [', at + 1)) {
225
- let path;
226
- try {
227
- path = JSON.parse(text.slice(at + 1));
228
- } catch {
229
- continue;
230
- }
231
- return Array.isArray(path) && path.length > 0 ? { label: text.slice(0, at), path } : undefined;
232
- }
233
- return undefined;
234
- }
235
-
236
- /**
237
- * The hits in a macrostep that ended, of the actor labelled `label`:
238
- * [{ kind: 'function' | 'exception' | 'data', breakpoints, description,
239
- * exception }]. `location(expressionID)` names an <assign>'s location;
240
- * `fires(breakpoint)` confirms a condition.
241
- */
242
- hits(macrostep, { label, location, fires, log }) {
243
- const out = [];
244
- const exception = this.#exception(macrostep);
245
- if (exception !== undefined) out.push(exception);
246
- const lines = this.#allLines().filter((breakpoint) => lineRan(breakpoint.element, macrostep))
247
- .filter((breakpoint) => this.#fire(breakpoint, fires))
248
- .filter((breakpoint) => (breakpoint.logMessage ? (log(breakpoint), false) : true));
249
- if (lines.length > 0) {
250
- out.push({ kind: 'line', breakpoints: lines.map((entry) => entry.id),
251
- description: lines.map(describeLine).join(', ') });
252
- }
253
- const functions = this.#functions.filter((breakpoint) => {
254
- switch (breakpoint.kind) {
255
- case 'on': return macrostep.event !== null && matchesEvent(breakpoint.target, macrostep.event.name);
256
- case 'entry': return macrostep.microsteps.some((micro) => micro.entered.includes(breakpoint.target));
257
- case 'exit': return macrostep.microsteps.some((micro) => micro.exited.includes(breakpoint.target));
258
- default: return macrostep.microsteps.some((micro) => micro.transitions.some((text) => {
259
- const shown = normalize(text);
260
- return shown === breakpoint.target || shown.startsWith(`${breakpoint.target} on `);
261
- }));
262
- }
263
- }).filter((breakpoint) => this.#fire(breakpoint, fires));
264
- if (functions.length > 0) {
265
- out.push({ kind: 'function', breakpoints: functions.map((entry) => entry.id),
266
- description: functions.map(describe).join(', ') });
267
- }
268
- const written = macrostep.records.filter((entry) => entry.name === 'scxml.assign')
269
- .map((entry) => ({ location: location(entry.attributes['scxml.expression.id']),
270
- value: entry.attributes['scxml.value'] }))
271
- .filter((entry) => entry.location !== undefined);
272
- const data = this.#data.filter((breakpoint) => breakpoint.label === label &&
273
- written.some((entry) => overlap(breakpoint.path, entry.location)))
274
- .filter((breakpoint) => this.#fire(breakpoint, fires));
275
- if (data.length > 0) {
276
- const writes = written.filter((entry) => data.some((breakpoint) => overlap(breakpoint.path, entry.location)));
277
- out.push({ kind: 'data', breakpoints: data.map((entry) => entry.id),
278
- description: writes.map((entry) => `${entry.location.join('.')}${entry.value === undefined ? ' written'
279
- : ` = ${entry.value}`}`).join(', ') });
280
- }
281
- return out;
282
- }
283
-
284
- #fire(breakpoint, fires) {
285
- if (hasCondition(breakpoint) && !fires(breakpoint)) {
286
- return false;
287
- }
288
- breakpoint.hits += 1;
289
- return hitConditionMet(breakpoint.hitCondition, breakpoint.hits);
290
- }
291
-
292
- #exception(macrostep) {
293
- if (this.#filters.size === 0) return undefined;
294
- const candidates = [];
295
- if (macrostep.event !== null) {
296
- const filter = ERRORS.find((name) => matchesEvent(name, macrostep.event.name));
297
- if (filter !== undefined) candidates.push({ filter, name: macrostep.event.name, data: macrostep.event.data });
298
- }
299
- let fault;
300
- for (const entry of macrostep.records) {
301
- const a = entry.attributes;
302
- if (entry.name === 'scxml.error') {
303
- fault = faultText(a);
304
- } else if (entry.name === 'scxml.raise') {
305
- const filter = ERRORS.find((name) => matchesEvent(name, a['scxml.event.name']));
306
- if (filter !== undefined) candidates.push({ filter, name: a['scxml.event.name'], fault });
307
- } else if (entry.name === 'scxml.ignored') {
308
- candidates.push({ filter: 'ignored', name: a['scxml.event.name'] });
309
- } else if (entry.name === 'scxml.stopped') {
310
- candidates.push({ filter: 'stopped', name: undefined });
311
- }
312
- }
313
- const hit = candidates.find((candidate) => this.#filters.has(candidate.filter));
314
- if (hit === undefined) return undefined;
315
- const description = hit.filter === 'ignored' ? `${hit.name} enabled no transition`
316
- : hit.filter === 'stopped' ? 'an allocation failed; the run stopped where it stood'
317
- : [hit.name, hit.fault].filter((part) => part !== undefined).join(': ');
318
- return { kind: 'exception', breakpoints: [], description, exception: hit };
319
- }
320
- }
321
-
322
- // What faulted and why, from a record's attributes: the action (or the
323
- // transition whose guard failed) and the fault's message, as the test
324
- // host's adapter says it too.
325
- function faultText(a) {
326
- const parts = [a['scxml.action'] ?? a['scxml.transition'], a['scxml.fault.message']]
327
- .filter((part) => part !== undefined && part !== '');
328
- return parts.length === 0 ? a['scxml.fault.detail'] : parts.join(': ');
329
- }
330
-
331
- // Whether a macrostep ran the element a line breakpoint stands for.
332
- function lineRan(element, macrostep) {
333
- switch (element.kind) {
334
- case 'state': return macrostep.microsteps.some((micro) => micro.entered.includes(element.name));
335
- case 'transition': return macrostep.microsteps.some((micro) => micro.transitionIDs.includes(element.id));
336
- default: return macrostep.records.some((entry) => entry.attributes['scxml.action.id'] === element.id);
337
- }
338
- }
339
-
340
- // A write to `written` touches `watched` when one path is a prefix of the other.
341
- function overlap(watched, written) {
342
- const length = Math.min(watched.length, written.length);
343
- for (let at = 0; at < length; at += 1) {
344
- if (String(watched[at]) !== String(written[at])) return false;
345
- }
346
- return true;
347
- }
348
-
349
- module.exports = { Breakpoints, EXCEPTION_FILTERS, matchesEvent };
@@ -1,149 +0,0 @@
1
- 'use strict';
2
-
3
- // The debug console: what a client sends as `evaluate` with context
4
- // `repl`, and the completions it offers there.
5
- //
6
- // send <event> [json] deliver through the actor's mailbox, with the console as origin
7
- // goto <state…> [from <state>] an operator transition (core ADR 0082)
8
- // abandon abandon a macrostep that never ends (core ADR 0082)
9
- // cancel <send ID> withdraw one pending delayed send (core ADR 0084)
10
- // replace <revision> hot-replace the actor with another revision of its family
11
- // <expression> JavaScript over the data model (lib/debug/expressions)
12
- //
13
- // The console is a sender an actor can answer (core ADR 0068): the adapter
14
- // registers an I/O processor of type `debug` once per system and opens one
15
- // scope per session, so a chart's reply to `event.origin` reaches the
16
- // session that sent the message.
17
-
18
- const { TinyactorsError } = require('../errors');
19
- const { locations } = require('./expressions');
20
-
21
- const TYPE = 'debug';
22
- const COMMANDS = ['send', 'goto', 'abandon', 'cancel', 'replace', 'help'];
23
-
24
- const HELP = [
25
- 'send <event> [json] deliver an event, queued behind the actor\'s mail; replies show here',
26
- 'goto <state…> [from <state>] an operator transition: exits, entries and history as a transition\'s',
27
- 'abandon abandon a macrostep that never ends; the actor keeps its last configuration',
28
- 'cancel <send ID> withdraw a pending delayed send, by the ID the Timers scope shows',
29
- 'replace <revision> replace the actor with another registered revision of its family',
30
- '<expression> JavaScript over the data model: `failures`, `.items[0]`, `inState("busy")`',
31
- ];
32
-
33
- /**
34
- * Splits a console line into a command and its arguments, or answers
35
- * { command: 'expression', text } for anything else.
36
- */
37
- function parse(line) {
38
- const text = String(line).trim();
39
- const [word, ...rest] = text.split(/\s+/);
40
- const tail = text.slice(word.length).trim();
41
- switch (word) {
42
- case 'send': {
43
- if (rest.length === 0) throw new TinyactorsError('send <event> [json]', 'invalid');
44
- const event = rest[0];
45
- const json = tail.slice(event.length).trim();
46
- let data;
47
- if (json !== '') {
48
- try {
49
- data = JSON.parse(json);
50
- } catch (error) {
51
- throw new TinyactorsError(`the event data is not JSON: ${error.message}`, 'invalid');
52
- }
53
- }
54
- return { command: 'send', event, data };
55
- }
56
- case 'goto': {
57
- const at = rest.indexOf('from');
58
- const targets = at < 0 ? rest : rest.slice(0, at);
59
- const from = at < 0 ? undefined : rest[at + 1];
60
- if (targets.length === 0 || (at >= 0 && (from === undefined || rest.length > at + 2))) {
61
- throw new TinyactorsError('goto <state…> [from <state>]', 'invalid');
62
- }
63
- return { command: 'goto', targets, from };
64
- }
65
- case 'abandon':
66
- case 'help':
67
- return { command: word };
68
- case 'cancel':
69
- if (rest.length !== 1) throw new TinyactorsError('cancel <send ID>: the ID the Timers scope shows', 'invalid');
70
- return { command: 'cancel', id: rest[0] };
71
- case 'replace':
72
- if (rest.length !== 1) {
73
- throw new TinyactorsError('replace <revision>: a registered revision of the actor\'s family', 'invalid');
74
- }
75
- return { command: 'replace', revision: rest[0] };
76
- default:
77
- return { command: 'expression', text };
78
- }
79
- }
80
-
81
- /**
82
- * Completion targets for `text` with the cursor at `column` (0-based).
83
- * `context` gives events(), states(), sendIDs() and data() of the actor.
84
- */
85
- function completions(text, column, context) {
86
- const before = String(text).slice(0, column);
87
- const target = (label, start, type) => ({ label, text: label, start, length: column - start, type });
88
- let match = /^\s*send\s+(\S*)$/.exec(before);
89
- if (match !== null) {
90
- const prefix = match[1];
91
- return context.events().filter((name) => name.startsWith(prefix))
92
- .map((name) => target(name, column - prefix.length, 'event'));
93
- }
94
- match = /^\s*goto\s+(?:\S+\s+)*(\S*)$/.exec(before);
95
- if (match !== null) {
96
- const prefix = match[1];
97
- return context.states().filter((name) => name.startsWith(prefix))
98
- .map((name) => target(name, column - prefix.length, 'value'));
99
- }
100
- match = /^\s*cancel\s+(\S*)$/.exec(before);
101
- if (match !== null) {
102
- const prefix = match[1];
103
- return context.sendIDs().filter((id) => id.startsWith(prefix))
104
- .map((id) => target(id, column - prefix.length, 'value'));
105
- }
106
- match = /^\s*(\w*)$/.exec(before);
107
- if (match !== null && match[1] !== '') {
108
- const words = COMMANDS.filter((word) => word.startsWith(match[1]));
109
- if (words.length > 0) return words.map((word) => target(word, column - match[1].length, 'keyword'));
110
- }
111
- return locations(before, context.data()).map(({ label, start }) => target(label, start, 'property'));
112
- }
113
-
114
- // One `debug` I/O processor per system; replies find their session by the
115
- // scope URI they are sent to.
116
- const registries = new WeakMap();
117
-
118
- /**
119
- * Registers the `debug` I/O processor on `system` (once), opens a scope
120
- * for `uri`, and routes replies sent to it to `onReply(request)`. Answers
121
- * { scope, close() }.
122
- */
123
- function openConsole(system, uri, onReply) {
124
- let registry = registries.get(system);
125
- if (registry === undefined) {
126
- registry = new Map();
127
- registries.set(system, registry);
128
- system.registerIO(TYPE, {
129
- send(request) {
130
- const listener = registry.get(String(request.target));
131
- if (listener === undefined) {
132
- throw new TinyactorsError(`no debug session listens at ${request.target}`, 'not-found');
133
- }
134
- listener(request);
135
- },
136
- });
137
- }
138
- const scope = system.openScope(TYPE, uri);
139
- registry.set(uri, onReply);
140
- return {
141
- scope,
142
- close() {
143
- registry.delete(uri);
144
- if (!system.closed) system.closeScope(scope);
145
- },
146
- };
147
- }
148
-
149
- module.exports = { parse, completions, openConsole, HELP, TYPE };
@@ -1,133 +0,0 @@
1
- 'use strict';
2
-
3
- // Expressions over an actor's data model. The JavaScript data model's data
4
- // is plain JavaScript objects (napi ADR 0001), so an expression is
5
- // JavaScript: the data's properties are in scope by name, `this` and `data`
6
- // are the data root, and `event`, `sessionID`, `name` and `inState(state)`
7
- // are what a chart's own expressions see in their context. A leading dot is
8
- // the data root, as in the jq form the test host uses: `.failures`.
9
- //
10
- // Evaluating an expression runs arbitrary code in the process that hosts
11
- // the actor. The debug session lets it only with the `evaluate` permission;
12
- // reading and writing a location by path (the Variables pane, setVariable
13
- // with a JSON value, completions) runs no code of the operator's.
14
-
15
- const { TinyactorsError } = require('../errors');
16
-
17
- const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
18
-
19
- // `.a.b` → `data.a.b`; anything else is left as it is.
20
- function source(text) {
21
- const trimmed = text.trim();
22
- return /^\.[A-Za-z_$]/.test(trimmed) ? `data${trimmed}` : trimmed;
23
- }
24
-
25
- function compile(parameters, body) {
26
- try {
27
- // A function the Function constructor makes is not strict, so `with`
28
- // puts the data's properties in scope.
29
- return new Function(...parameters, body);
30
- } catch (error) {
31
- throw new TinyactorsError(`the expression does not parse: ${error.message}`, 'invalid');
32
- }
33
- }
34
-
35
- const SCOPE = ['data', 'event', 'sessionID', 'name', 'inState'];
36
-
37
- function argumentsOf(scope) {
38
- const data = scope.data ?? {};
39
- return [data, scope.event, scope.sessionID, scope.name, (state) => scope.activeStates?.includes(state) ?? false];
40
- }
41
-
42
- /**
43
- * Evaluates `text` against `scope`: { data, event, sessionID, name,
44
- * activeStates }. Throws `invalid` when it does not parse, and rethrows what
45
- * the expression throws, as `invalid` with its message.
46
- */
47
- function evaluate(text, scope) {
48
- const fn = compile(SCOPE, `with (data) { return (${source(text)}\n); }`);
49
- const args = argumentsOf(scope);
50
- try {
51
- return fn.apply(args[0], args);
52
- } catch (error) {
53
- throw new TinyactorsError(`the expression threw: ${error?.message ?? error}`, 'invalid');
54
- }
55
- }
56
-
57
- /** Assigns `value` to the location expression `text` (`failures`, `.items[0].qty`). */
58
- function assign(text, value, scope) {
59
- const fn = compile([...SCOPE, '__value'], `with (data) { (${source(text)}) = __value; }`);
60
- const args = argumentsOf(scope);
61
- try {
62
- fn.apply(args[0], [...args, value]);
63
- } catch (error) {
64
- throw new TinyactorsError(`the assignment threw: ${error?.message ?? error}`, 'invalid');
65
- }
66
- }
67
-
68
- /**
69
- * A location as a path of keys, without running code: `failures`,
70
- * `.items[0].qty`, `data.items[0]`. Undefined when `text` is not a plain
71
- * path.
72
- */
73
- function pathOf(text) {
74
- let rest = text.trim();
75
- if (rest.startsWith('data.') || rest.startsWith('data[')) rest = rest.slice(4);
76
- else if (rest.startsWith('this.') || rest.startsWith('this[')) rest = rest.slice(4);
77
- if (!rest.startsWith('.') && !rest.startsWith('[')) rest = `.${rest}`;
78
- const path = [];
79
- const step = /^(?:\.([A-Za-z_$][\w$]*)|\[(\d+)\]|\[("(?:[^"\\]|\\.)*")\])/;
80
- while (rest !== '') {
81
- const match = step.exec(rest);
82
- if (match === null) return undefined;
83
- if (match[1] !== undefined) path.push(match[1]);
84
- else if (match[2] !== undefined) path.push(Number(match[2]));
85
- else path.push(JSON.parse(match[3]));
86
- rest = rest.slice(match[0].length);
87
- }
88
- return path.length === 0 ? undefined : path;
89
- }
90
-
91
- /** `.a.b[0]` for a path of keys. */
92
- function locationText(path) {
93
- return path.map((key) => (typeof key === 'number' ? `[${key}]`
94
- : IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`)).join('');
95
- }
96
-
97
- /** The value at `path` in `root`, or undefined. */
98
- function valueAt(root, path) {
99
- let value = root;
100
- for (const key of path) {
101
- if (value === null || typeof value !== 'object') return undefined;
102
- value = value[key];
103
- }
104
- return value;
105
- }
106
-
107
- /**
108
- * Completions for the data location that ends `text`: the keys of the
109
- * object it names that start with what was typed. [{ label, start }] with
110
- * `start` the column the typed prefix starts at.
111
- */
112
- function locations(text, root) {
113
- // `.a.b` or `a.b` (the object, then what was typed of a key), or a bare name.
114
- const dotted = /((?:\.?[A-Za-z_$][\w$]*)(?:\.[A-Za-z_$][\w$]*)*)?\.([A-Za-z_$][\w$]*)?$/;
115
- const bare = /(?:^|[^\w$.])([A-Za-z_$][\w$]*)$/;
116
- const match = new RegExp(`${dotted.source}|${bare.source}`).exec(text);
117
- if (match === null || root === null || typeof root !== 'object') return [];
118
- let container = root;
119
- let prefix;
120
- if (match[3] !== undefined) {
121
- prefix = match[3];
122
- } else {
123
- prefix = match[2] ?? '';
124
- const parent = match[1] === undefined ? [] : pathOf(match[1]);
125
- if (parent === undefined) return [];
126
- container = parent.length === 0 ? root : valueAt(root, parent);
127
- }
128
- if (container === null || typeof container !== 'object') return [];
129
- const start = text.length - prefix.length;
130
- return Object.keys(container).filter((key) => key.startsWith(prefix)).map((label) => ({ label, start }));
131
- }
132
-
133
- module.exports = { evaluate, assign, pathOf, locationText, valueAt, locations };