@tsplc/tmp-debug 0.0.0-stage → 0.6.2

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 (78) hide show
  1. package/README.md +38 -2
  2. package/dist/api.js +744 -0
  3. package/dist/api.js.map +12 -0
  4. package/dist/constant.js +33 -0
  5. package/dist/constant.js.map +10 -0
  6. package/dist/explain-file.js +468 -0
  7. package/dist/explain-file.js.map +11 -0
  8. package/dist/explain.js +1310 -0
  9. package/dist/explain.js.map +19 -0
  10. package/dist/format.js +214 -0
  11. package/dist/format.js.map +12 -0
  12. package/dist/index.js +4066 -0
  13. package/dist/index.js.map +44 -0
  14. package/dist/manifest.js +240 -0
  15. package/dist/manifest.js.map +10 -0
  16. package/dist/paths.js +242 -0
  17. package/dist/paths.js.map +10 -0
  18. package/package.json +72 -4
  19. package/src/adapter.ts +77 -0
  20. package/src/api.ts +446 -0
  21. package/src/app-server.ts +151 -0
  22. package/src/build-files.ts +46 -0
  23. package/src/constant.ts +41 -0
  24. package/src/debugger.ts +237 -0
  25. package/src/errors.ts +13 -0
  26. package/src/explain-expressions.ts +484 -0
  27. package/src/explain-file.ts +325 -0
  28. package/src/explain-frames.ts +155 -0
  29. package/src/explain-loops.ts +151 -0
  30. package/src/explain-operations.ts +232 -0
  31. package/src/explain-tables.ts +345 -0
  32. package/src/explain-value.ts +203 -0
  33. package/src/explain-verdicts.ts +548 -0
  34. package/src/explain.ts +82 -0
  35. package/src/hardware.ts +159 -0
  36. package/src/http.ts +218 -0
  37. package/src/index.ts +44 -0
  38. package/src/jobs.ts +139 -0
  39. package/src/login-value.ts +165 -0
  40. package/src/login.ts +315 -0
  41. package/src/manifest.ts +328 -0
  42. package/src/opcua.ts +80 -0
  43. package/src/paths.ts +363 -0
  44. package/src/requests.ts +99 -0
  45. package/src/server-cursor.ts +22 -0
  46. package/src/shown.ts +229 -0
  47. package/src/telemetry.ts +125 -0
  48. package/src/timeline.ts +148 -0
  49. package/src/trace.ts +62 -0
  50. package/src/ui/bits.ts +48 -0
  51. package/src/ui/client.ts +87 -0
  52. package/src/ui/dom.ts +61 -0
  53. package/src/ui/explain-read.ts +105 -0
  54. package/src/ui/format.ts +261 -0
  55. package/src/ui/hardware.ts +425 -0
  56. package/src/ui/header.ts +207 -0
  57. package/src/ui/health.ts +64 -0
  58. package/src/ui/index.ts +27 -0
  59. package/src/ui/jobs.ts +263 -0
  60. package/src/ui/links.ts +59 -0
  61. package/src/ui/live-value.ts +85 -0
  62. package/src/ui/main.ts +76 -0
  63. package/src/ui/overview.ts +178 -0
  64. package/src/ui/page.ts +286 -0
  65. package/src/ui/pages.ts +64 -0
  66. package/src/ui/recent-window.ts +49 -0
  67. package/src/ui/recent.ts +355 -0
  68. package/src/ui/request-trace.ts +38 -0
  69. package/src/ui/requests.ts +80 -0
  70. package/src/ui/routes.ts +98 -0
  71. package/src/ui/store.ts +295 -0
  72. package/src/ui/success-cache.ts +11 -0
  73. package/src/ui/tree.ts +162 -0
  74. package/src/ui/variables.ts +597 -0
  75. package/src/ui/why-watch.ts +11 -0
  76. package/src/ui/why.ts +694 -0
  77. package/src/values.ts +170 -0
  78. package/src/watch.ts +32 -0
package/src/paths.ts ADDED
@@ -0,0 +1,363 @@
1
+ import { isWithin } from "@tsplc/iec/st";
2
+ import {
3
+ arrayIndex,
4
+ joinPath,
5
+ symbolPathSegments,
6
+ } from "@tsplc/opcua/contract";
7
+ import type { DebugManifest, DebugType, SourceRange } from "./manifest";
8
+
9
+ /**
10
+ * TypeScript paths over a manifest: `bench.instruments[10].phase` names a root
11
+ * (`program.benchs`), then record fields and array indexes. Pure, so the browser UI can use it.
12
+ */
13
+
14
+ /** A path that reads a target, or a constant the compiler folded. */
15
+ export type ResolvedPath =
16
+ | {
17
+ kind: "target";
18
+ path: string;
19
+ target: string;
20
+ type: string;
21
+ readable: boolean;
22
+ generated?: true;
23
+ declaration?: SourceRange;
24
+ }
25
+ | {
26
+ kind: "constant";
27
+ path: string;
28
+ type: string;
29
+ value: unknown;
30
+ declaration?: SourceRange;
31
+ };
32
+
33
+ type TargetPath = Extract<ResolvedPath, { kind: "target" }>;
34
+
35
+ /** Roots or constants that share a prefix, such as `program` above `program.benchs`. */
36
+ interface GroupPath {
37
+ kind: "group";
38
+ path: string;
39
+ }
40
+
41
+ /** A child in the instance tree. */
42
+ export type PathNode = { name: string } & (ResolvedPath | GroupPath);
43
+
44
+ /** In a pattern, every index of an array. */
45
+ export const anyIndex = "[*]";
46
+
47
+ /** Whether `path` is a pattern: `*` stands for any one segment and `[*]` for any index. */
48
+ export const isPattern = (path: string) => path.includes("*");
49
+
50
+ /** Thrown by `expand` when more paths match than its limit. */
51
+ export class TooManyMatches extends RangeError {
52
+ constructor(limit: number) {
53
+ super(`More than ${limit} values match`);
54
+ }
55
+ }
56
+
57
+ /** Names and indexes as the controller's symbol paths split them, and `[*]` in patterns. */
58
+ export const pathSegments = (path: string) =>
59
+ path
60
+ .split(anyIndex)
61
+ .flatMap((part, index) => [
62
+ ...(index > 0 ? [anyIndex] : []),
63
+ ...symbolPathSegments(part),
64
+ ]);
65
+
66
+ /** `path` with every index as `[*]`, so a pattern and each of its elements compare equal. */
67
+ export const patternOf = (path: string) =>
68
+ pathSegments(path)
69
+ .map((segment) => (arrayIndex(segment) === undefined ? segment : anyIndex))
70
+ .reduce(joinPath, "");
71
+
72
+ /** Scalar type ids are their IEC names, and may have no entry in `types`. */
73
+ export const typeOf = (
74
+ manifest: Pick<DebugManifest, "types">,
75
+ id: string,
76
+ ): DebugType => manifest.types[id] ?? { kind: "scalar", iec: id };
77
+
78
+ /** What resolving and expanding paths needs from a manifest. */
79
+ export type PathManifest = Pick<
80
+ DebugManifest,
81
+ "roots" | "io" | "constants" | "types"
82
+ >;
83
+
84
+ export const createPaths = (manifest: PathManifest) => {
85
+ const typeOfId = (id: string) => typeOf(manifest, id);
86
+ const constants = new Map(
87
+ manifest.constants.map(({ path, ...constant }) => [
88
+ path,
89
+ { kind: "constant" as const, path, ...constant },
90
+ ]),
91
+ );
92
+ const roots = new Map<string, TargetPath>(
93
+ manifest.roots.map(({ path, ...root }) => [
94
+ path,
95
+ { kind: "target", path, ...root },
96
+ ]),
97
+ );
98
+ /** `path` walked from the longest prefix in `bases` through record fields and array indexes. */
99
+ const walk = (
100
+ bases: ReadonlyMap<string, TargetPath>,
101
+ path: string,
102
+ ): TargetPath | undefined => {
103
+ const segments = pathSegments(path);
104
+ for (let length = segments.length; length > 0; length--) {
105
+ const base = bases.get(segments.slice(0, length).reduce(joinPath, ""));
106
+ if (!base) {
107
+ continue;
108
+ }
109
+ let resolved = base;
110
+ for (const segment of segments.slice(length)) {
111
+ const type = typeOfId(resolved.type);
112
+ if (type.kind === "record") {
113
+ const field = type.fields.find(({ name }) => name === segment);
114
+ if (!field) {
115
+ return;
116
+ }
117
+ resolved = {
118
+ kind: "target",
119
+ path: joinPath(resolved.path, segment),
120
+ target: `${resolved.target}.${field.target}`,
121
+ type: field.type,
122
+ readable: resolved.readable,
123
+ ...(field.generated && { generated: true }),
124
+ ...(field.declaration && { declaration: field.declaration }),
125
+ };
126
+ } else if (type.kind === "array") {
127
+ const index = arrayIndex(segment);
128
+ if (
129
+ index === undefined ||
130
+ index < type.lower ||
131
+ index >= type.lower + type.length
132
+ ) {
133
+ return;
134
+ }
135
+ resolved = {
136
+ kind: "target",
137
+ path: joinPath(resolved.path, segment),
138
+ target: `${resolved.target}${segment}`,
139
+ type: type.element,
140
+ readable: resolved.readable,
141
+ ...(resolved.declaration && { declaration: resolved.declaration }),
142
+ };
143
+ } else {
144
+ return;
145
+ }
146
+ }
147
+ return resolved;
148
+ }
149
+ };
150
+ // A logical input's or output's path is its root's too, and the root declares it.
151
+ const bases = new Map<string, TargetPath>([
152
+ ...roots,
153
+ ...manifest.io.map(({ path, target, type }): [string, TargetPath] => {
154
+ const declared = walk(roots, path);
155
+ return [
156
+ path,
157
+ {
158
+ kind: "target",
159
+ path,
160
+ target,
161
+ type,
162
+ readable: true,
163
+ ...(declared?.generated && { generated: true }),
164
+ ...(declared?.declaration && { declaration: declared.declaration }),
165
+ },
166
+ ];
167
+ }),
168
+ ]);
169
+ /** Children of the prefixes of every root and constant path, which are groups unless they resolve. */
170
+ const groups = new Map<string, Set<string>>();
171
+ for (const path of [...bases.keys(), ...constants.keys()]) {
172
+ let prefix = "";
173
+ for (const segment of pathSegments(path)) {
174
+ let children = groups.get(prefix);
175
+ if (!children) {
176
+ children = new Set();
177
+ groups.set(prefix, children);
178
+ }
179
+ children.add(segment);
180
+ prefix = joinPath(prefix, segment);
181
+ }
182
+ }
183
+
184
+ const resolve = (path: string): ResolvedPath | undefined =>
185
+ constants.get(path) ?? walk(bases, path);
186
+
187
+ const typedChildren = (resolved: ResolvedPath | undefined) => {
188
+ const type =
189
+ resolved?.kind === "target" ? typeOfId(resolved.type) : undefined;
190
+ if (type?.kind === "record") {
191
+ return type.fields.map(({ name }) => name);
192
+ }
193
+ if (type?.kind === "array") {
194
+ return Array.from(
195
+ { length: type.length },
196
+ (_, index) => `[${type.lower + index}]`,
197
+ );
198
+ }
199
+ return [];
200
+ };
201
+
202
+ /** A path's fields or indexes, and the roots and constants below it. */
203
+ const children = (path: string): PathNode[] => {
204
+ const names = [
205
+ ...typedChildren(resolve(path)),
206
+ ...(groups.get(path) ?? []),
207
+ ];
208
+ return [...new Set(names)].map((name) => {
209
+ const child = joinPath(path, name);
210
+ return { name, ...(resolve(child) ?? { kind: "group", path: child }) };
211
+ });
212
+ };
213
+
214
+ const isLeaf = (node: ResolvedPath | GroupPath) =>
215
+ node.kind === "constant" ||
216
+ (node.kind === "target" &&
217
+ ["scalar", "enum"].includes(typeOfId(node.type).kind));
218
+
219
+ /**
220
+ * Leaf paths matching `patterns`, where `*` stands for one segment. A pattern naming a record,
221
+ * array or group stands for all its leaves; wildcards and expansion skip compiler-made fields.
222
+ * Paths that don't resolve are kept, so callers can report them.
223
+ */
224
+ const expand = (patterns: readonly string[], limit = 2000) => {
225
+ const leaves = new Set<string>();
226
+ const add = (path: string) => {
227
+ leaves.add(path);
228
+ if (leaves.size > limit) {
229
+ throw new TooManyMatches(limit);
230
+ }
231
+ };
232
+ const below = (node: ResolvedPath | GroupPath) => {
233
+ if (isLeaf(node)) {
234
+ return add(node.path);
235
+ }
236
+ for (const child of children(node.path)) {
237
+ if (!(child.kind === "target" && child.generated)) {
238
+ below(child);
239
+ }
240
+ }
241
+ };
242
+ const match = (
243
+ prefix: string,
244
+ rest: readonly string[],
245
+ wildcard: boolean,
246
+ ) => {
247
+ const [head, ...tail] = rest;
248
+ if (head === undefined) {
249
+ const node: ResolvedPath | GroupPath | undefined =
250
+ resolve(prefix) ??
251
+ (groups.has(prefix) ? { kind: "group", path: prefix } : undefined);
252
+ if (node) {
253
+ below(node);
254
+ } else if (!wildcard) {
255
+ add(prefix);
256
+ }
257
+ return;
258
+ }
259
+ if (head === "*" || head === anyIndex) {
260
+ for (const child of children(prefix)) {
261
+ if (
262
+ !(child.kind === "target" && child.generated) &&
263
+ (head === "*" || child.name.startsWith("["))
264
+ ) {
265
+ match(child.path, tail, true);
266
+ }
267
+ }
268
+ } else {
269
+ match(joinPath(prefix, head), tail, wildcard);
270
+ }
271
+ };
272
+ for (const pattern of patterns) {
273
+ match("", pathSegments(pattern), false);
274
+ }
275
+ return [...leaves];
276
+ };
277
+
278
+ /** A value as TypeScript shows it: enum members by name, BOOL as a boolean. */
279
+ const decode = (typeId: string, raw: unknown) => {
280
+ const type = typeOfId(typeId);
281
+ if (type.kind === "enum") {
282
+ return (
283
+ Object.entries(type.members).find(([, value]) => value === raw)?.[0] ??
284
+ raw
285
+ );
286
+ }
287
+ if (
288
+ type.kind === "scalar" &&
289
+ type.iec === "BOOL" &&
290
+ typeof raw === "number"
291
+ ) {
292
+ return raw !== 0;
293
+ }
294
+ return raw;
295
+ };
296
+
297
+ /**
298
+ * The TypeScript path an IEC symbol path names: an I/O binding by its target or address, or a
299
+ * storage root's target followed by its fields' targets and indexes. IEC names are
300
+ * case-insensitive. Undefined for one that names nothing the manifest knows.
301
+ */
302
+ const fromTarget = (expression: string): string | undefined => {
303
+ const upper = expression.trim().toUpperCase();
304
+ const whole = targets.get(upper);
305
+ if (whole) {
306
+ return whole;
307
+ }
308
+ const root = manifest.roots
309
+ .filter((item) => isWithin(item.target, upper))
310
+ .sort((a, b) => b.target.length - a.target.length)[0];
311
+ if (!root) {
312
+ return undefined;
313
+ }
314
+ let path = root.path;
315
+ let type = root.type;
316
+ for (const segment of pathSegments(
317
+ expression.trim().slice(root.target.length).replace(/^\./, ""),
318
+ )) {
319
+ const declared = typeOfId(type);
320
+ if (segment.startsWith("[")) {
321
+ if (declared.kind !== "array") {
322
+ return undefined;
323
+ }
324
+ path = joinPath(path, segment);
325
+ type = declared.element;
326
+ continue;
327
+ }
328
+ const field =
329
+ declared.kind === "record"
330
+ ? declared.fields.find(
331
+ (item) => item.target.toUpperCase() === segment.toUpperCase(),
332
+ )
333
+ : undefined;
334
+ if (!field) {
335
+ return undefined;
336
+ }
337
+ path = joinPath(path, field.name);
338
+ type = field.type;
339
+ }
340
+ return path;
341
+ };
342
+ const targets = new Map<string, string>([
343
+ ...manifest.io.flatMap((io) => [
344
+ [io.target.toUpperCase(), io.path] as const,
345
+ ...(io.address ? [[io.address.toUpperCase(), io.path] as const] : []),
346
+ ]),
347
+ ...manifest.roots.map(
348
+ (root) => [root.target.toUpperCase(), root.path] as const,
349
+ ),
350
+ ]);
351
+
352
+ return {
353
+ typeOf: typeOfId,
354
+ resolve,
355
+ children,
356
+ isLeaf,
357
+ expand,
358
+ decode,
359
+ fromTarget,
360
+ };
361
+ };
362
+
363
+ export type Paths = ReturnType<typeof createPaths>;
@@ -0,0 +1,99 @@
1
+ import type { RequestsReply } from "@tsplc/server/requests";
2
+ import type { RequestTrace } from "./api";
3
+ import { createServerCursor } from "./server-cursor";
4
+ import { type Entry, timelineEntries } from "./timeline";
5
+
6
+ /** Traces kept for jobs to find their calls by; older ones are forgotten. */
7
+ const callsRemembered = 1000;
8
+
9
+ /** A call that started or ended, with its timeline entry; `added` when the entry is new. */
10
+ interface RequestChange {
11
+ request: RequestTrace;
12
+ entry: Entry<"request">;
13
+ added: boolean;
14
+ }
15
+
16
+ /** What the PLC tags a call with: its job and the call site's count. */
17
+ interface TaggedCall {
18
+ job: number;
19
+ service: string;
20
+ sequence: number;
21
+ }
22
+
23
+ /** The tags of a call the PLC made from a job; undefined for any other call. */
24
+ export const taggedCall = ({
25
+ job,
26
+ service,
27
+ sequence,
28
+ }: RequestTrace): TaggedCall | undefined =>
29
+ job === undefined || sequence === undefined
30
+ ? undefined
31
+ : { job, service, sequence };
32
+
33
+ const callKey = ({ job, service, sequence }: TaggedCall) =>
34
+ `${job}:${service}:${sequence}`;
35
+
36
+ /**
37
+ * Follows the app server's request trace (`GET /tsplc/debug/requests`), asking again from before
38
+ * the oldest call still pending, so each call is seen when it starts and again when it ends.
39
+ */
40
+ export const createRequestFollower = () => {
41
+ const cursor = createServerCursor();
42
+ const pending = new Map<number, Entry<"request">>();
43
+ const calls = new Map<string, RequestTrace>();
44
+
45
+ return {
46
+ /** Where the next pull starts. */
47
+ since: () =>
48
+ pending.size ? Math.min(...pending.keys()) - 1 : cursor.newest(),
49
+ /** Takes a reply to `?since=<since()>`, telling `changed` of each call as it is taken. */
50
+ accept: (
51
+ reply: RequestsReply,
52
+ changed: (change: RequestChange) => void,
53
+ ) => {
54
+ if (!cursor.continues(reply.latest)) {
55
+ pending.clear();
56
+ return;
57
+ }
58
+ const oldest = reply.requests[0]?.seq;
59
+ if (oldest !== undefined) {
60
+ for (const seq of pending.keys()) {
61
+ if (seq < oldest) {
62
+ pending.delete(seq);
63
+ }
64
+ }
65
+ }
66
+ for (const request of reply.requests) {
67
+ const waiting = pending.get(request.seq);
68
+ if (waiting && request.status === "pending") {
69
+ continue;
70
+ }
71
+ if (!waiting && request.seq <= cursor.newest()) {
72
+ continue;
73
+ }
74
+ const entry = waiting ?? timelineEntries.request(request);
75
+ entry.request = request;
76
+ cursor.take(request.seq);
77
+ if (request.status === "pending") {
78
+ pending.set(request.seq, entry);
79
+ } else {
80
+ pending.delete(request.seq);
81
+ }
82
+ const tagged = taggedCall(request);
83
+ if (tagged) {
84
+ calls.set(callKey(tagged), request);
85
+ for (const key of [...calls.keys()].slice(0, -callsRemembered)) {
86
+ calls.delete(key);
87
+ }
88
+ }
89
+ changed({ request, entry, added: !waiting });
90
+ }
91
+ },
92
+ /** The server's trace of a call by its tags. */
93
+ call: (call: TaggedCall) => calls.get(callKey(call)),
94
+ };
95
+ };
96
+
97
+ export type ServiceCallLookup = ReturnType<
98
+ typeof createRequestFollower
99
+ >["call"];
@@ -0,0 +1,22 @@
1
+ /**
2
+ * How far a follower has taken one of the app server's logs, whose entries count from 1. A
3
+ * restarted server counts from 1 again, so a reply whose `latest` is below the newest entry taken
4
+ * means starting over.
5
+ */
6
+ export const createServerCursor = () => {
7
+ let newest = 0;
8
+ return {
9
+ newest: () => newest,
10
+ /** False, and back at the start, when the server restarted since the entries taken. */
11
+ continues: (latest: number) => {
12
+ if (latest < newest) {
13
+ newest = 0;
14
+ return false;
15
+ }
16
+ return true;
17
+ },
18
+ take: (seq: number) => {
19
+ newest = Math.max(newest, seq);
20
+ },
21
+ };
22
+ };
package/src/shown.ts ADDED
@@ -0,0 +1,229 @@
1
+ import type { TargetAdapter, TargetRead, TargetSample } from "./adapter";
2
+ import type { Interest, JobState, Session, StreamEvent } from "./api";
3
+ import { deviceReads, deviceState, healthReads } from "./hardware";
4
+ import {
5
+ busyOf,
6
+ busyRead,
7
+ detailReads,
8
+ jobState,
9
+ type TracedJob,
10
+ } from "./jobs";
11
+ import type { DebugDevice, DebugJob, DebugManifest } from "./manifest";
12
+ import type { Paths } from "./paths";
13
+ import type { ServiceCallLookup } from "./requests";
14
+
15
+ /** Device health, raw bytes and channels change rarely enough for this. */
16
+ const hardwareMs = 5000;
17
+ /** Busy jobs whose details each poll reads; the rest show as busy only. */
18
+ const detailedJobs = 16;
19
+
20
+ /** Counts how many streams show each key. */
21
+ const countShown = <Key>() => {
22
+ const counts = new Map<Key, number>();
23
+ return {
24
+ has: (key: Key) => counts.has(key),
25
+ add: (keys: readonly Key[]) => {
26
+ for (const key of keys) {
27
+ counts.set(key, (counts.get(key) ?? 0) + 1);
28
+ }
29
+ return () => {
30
+ for (const key of keys) {
31
+ const count = (counts.get(key) ?? 1) - 1;
32
+ if (count) {
33
+ counts.set(key, count);
34
+ } else {
35
+ counts.delete(key);
36
+ }
37
+ }
38
+ };
39
+ },
40
+ };
41
+ };
42
+
43
+ /**
44
+ * The jobs and devices the pages show: each is read only while a stream shows it, and its state
45
+ * is sent to the streams when it changes.
46
+ */
47
+ export const createShownReads = ({
48
+ manifest,
49
+ paths,
50
+ adapter,
51
+ emit,
52
+ clock,
53
+ request,
54
+ }: {
55
+ manifest: DebugManifest;
56
+ paths: Paths;
57
+ adapter: TargetAdapter;
58
+ emit: (event: StreamEvent) => void;
59
+ clock: () => Session["clock"];
60
+ request: ServiceCallLookup;
61
+ }) => {
62
+ const latest = new Map<string, TargetSample>();
63
+ const traced = new Map<number, TracedJob>();
64
+ const failures = new Map<number, NonNullable<JobState["failure"]>>();
65
+ let unread = new Set<number>();
66
+ const shownJobs = countShown<number>();
67
+ const shownHealth = countShown<string>();
68
+ const shownDevices = countShown<string>();
69
+ /** The JSON of what each stream last got, so unchanged states aren't sent again. */
70
+ const sent = new Map<string, string>();
71
+ const value = (target: string) => latest.get(target);
72
+
73
+ const jobOf = (job: DebugJob) =>
74
+ jobState(job, {
75
+ value,
76
+ traced: traced.get(job.id),
77
+ failure: failures.get(job.id),
78
+ unread: unread.has(job.id),
79
+ clock: clock(),
80
+ now: Date.now(),
81
+ request,
82
+ });
83
+ const deviceOf = (device: DebugDevice) =>
84
+ deviceState(device, manifest.io, value);
85
+ const send = (key: string, event: StreamEvent) => {
86
+ const json = JSON.stringify(event.data);
87
+ if (sent.get(key) === json) {
88
+ return;
89
+ }
90
+ sent.set(key, json);
91
+ emit(event);
92
+ };
93
+ const updateJob = (job: DebugJob) =>
94
+ send(`job:${job.id}`, { name: "job", data: jobOf(job) });
95
+ const updateDevice = (device: DebugDevice) =>
96
+ send(`device:${device.id}`, { name: "device", data: deviceOf(device) });
97
+
98
+ /** Re-subscribes `reads` when they change, telling `update` which owners each sample is for. */
99
+ const reader = <Owner>(
100
+ intervalMs: number,
101
+ update: (owner: Owner) => void,
102
+ ) => {
103
+ let current = { key: "", stop: () => {} };
104
+ return (reads: { owner: Owner; read: TargetRead }[]) => {
105
+ const key = reads.map(({ read }) => read.target).join("\n");
106
+ if (key === current.key) {
107
+ return;
108
+ }
109
+ current.stop();
110
+ const owners = new Map<string, Owner[]>();
111
+ for (const { owner, read } of reads) {
112
+ owners.set(read.target, [...(owners.get(read.target) ?? []), owner]);
113
+ }
114
+ current = {
115
+ key,
116
+ stop: reads.length
117
+ ? adapter.subscribe(
118
+ [
119
+ ...new Map(
120
+ reads.map(({ read }) => [read.target, read]),
121
+ ).values(),
122
+ ],
123
+ (target, sample) => {
124
+ latest.set(target, sample);
125
+ for (const owner of owners.get(target) ?? []) {
126
+ update(owner);
127
+ }
128
+ schedule();
129
+ },
130
+ intervalMs,
131
+ )
132
+ : () => {},
133
+ };
134
+ };
135
+ };
136
+ const readJobs = reader<DebugJob>(adapter.samplingMs, updateJob);
137
+ const readDevices = reader<DebugDevice>(hardwareMs, updateDevice);
138
+
139
+ /** Everything of a device whose page is shown, else its health while a list shows it. */
140
+ const shownDeviceReads = (device: DebugDevice) => {
141
+ if (shownDevices.has(device.id)) {
142
+ return deviceReads(device, manifest.io, paths.typeOf);
143
+ }
144
+ if (shownHealth.has(device.id)) {
145
+ return healthReads(device);
146
+ }
147
+ return [];
148
+ };
149
+
150
+ /** Reads `busy` of the shown jobs, and the details of the busy ones. */
151
+ const plan = () => {
152
+ const shown = manifest.jobs.filter((job) => shownJobs.has(job.id));
153
+ const busy = shown.filter((job) => busyOf(job, value, traced.get(job.id)));
154
+ unread = new Set(busy.slice(detailedJobs).map(({ id }) => id));
155
+ readJobs([
156
+ ...shown.map((job) => ({ owner: job, read: busyRead(job) })),
157
+ ...busy
158
+ .slice(0, detailedJobs)
159
+ .flatMap((job) =>
160
+ detailReads(job).map((read) => ({ owner: job, read })),
161
+ ),
162
+ ]);
163
+ readDevices(
164
+ manifest.devices.flatMap((device) =>
165
+ shownDeviceReads(device).map((read) => ({ owner: device, read })),
166
+ ),
167
+ );
168
+ };
169
+ let planned = false;
170
+ const schedule = () => {
171
+ if (planned) {
172
+ return;
173
+ }
174
+ planned = true;
175
+ queueMicrotask(() => {
176
+ planned = false;
177
+ plan();
178
+ });
179
+ };
180
+
181
+ return {
182
+ jobs: () => manifest.jobs.map(jobOf),
183
+ hardware: () => manifest.devices.map(deviceOf),
184
+ updateJob,
185
+ /** Reads what `interest` shows until the returned function is called. */
186
+ show: (interest: Pick<Interest, "jobs" | "health" | "devices">) => {
187
+ const stops = [
188
+ shownJobs.add(interest.jobs),
189
+ shownHealth.add(interest.health),
190
+ shownDevices.add(interest.devices),
191
+ ];
192
+ schedule();
193
+ return () => {
194
+ for (const stop of stops) {
195
+ stop();
196
+ }
197
+ schedule();
198
+ };
199
+ },
200
+ /** A trace record of `job` starting or finishing at `at`. */
201
+ traced: (job: DebugJob, started: boolean, at: string) => {
202
+ const startedAt = started ? at : traced.get(job.id)?.startedAt;
203
+ traced.set(job.id, { busy: started, ...(startedAt && { startedAt }) });
204
+ updateJob(job);
205
+ schedule();
206
+ },
207
+ /** A failure of `job` that nothing caught. */
208
+ failed: (job: DebugJob, failure: NonNullable<JobState["failure"]>) => {
209
+ failures.set(job.id, failure);
210
+ updateJob(job);
211
+ },
212
+ /** Nothing read is current while the controller isn't connected, for `status`. */
213
+ disconnected: (status: string) => {
214
+ for (const [target, sample] of latest) {
215
+ latest.set(target, { ...sample, quality: "unavailable", status });
216
+ }
217
+ for (const job of manifest.jobs) {
218
+ updateJob(job);
219
+ }
220
+ for (const device of manifest.devices) {
221
+ updateDevice(device);
222
+ }
223
+ },
224
+ close: () => {
225
+ readJobs([]);
226
+ readDevices([]);
227
+ },
228
+ };
229
+ };