@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
@@ -0,0 +1,295 @@
1
+ import type { Quality } from "@tsplc/opcua/contract";
2
+ import {
3
+ type DeviceState,
4
+ decodeStreamEvent,
5
+ type Interest,
6
+ interestQuery,
7
+ type JobState,
8
+ type Sample,
9
+ type Session,
10
+ type StreamEvent,
11
+ type StreamEvents,
12
+ type TimelineEntry,
13
+ type WatchGroups,
14
+ } from "../api";
15
+ import { errorMessage } from "../errors";
16
+ import type { DebugEventSite, DebugManifest } from "../manifest";
17
+ import { apiUrl, getJson, putJson } from "./client";
18
+ import { type ValueState, valueState } from "./format";
19
+ import { createPages, type Page } from "./pages";
20
+ import { createRecentWindow } from "./recent-window";
21
+ import { ManifestTree } from "./tree";
22
+
23
+ export type Topic =
24
+ | "session"
25
+ | "samples"
26
+ | "jobs"
27
+ | "devices"
28
+ | "timeline"
29
+ | "watch"
30
+ | "stream"
31
+ | "error"
32
+ | "clock";
33
+
34
+ /** The browser's EventSource state, apart from the controller connection the host reports. */
35
+ type StreamState = "connecting" | "open" | "reconnecting";
36
+
37
+ interface LiveSample {
38
+ sample: Sample | undefined;
39
+ state: ValueState;
40
+ }
41
+
42
+ const TIMELINE_LIMIT = 5000;
43
+ /** Timeline entries arrive in bursts, and a page lists many of them. */
44
+ const TIMELINE_RENDER_MS = 300;
45
+ const REOPEN_DEBOUNCE_MS = 250;
46
+ /** The browser retries a dropped stream on its own, but not one the host refused. */
47
+ const REFUSED_RETRY_MS = 3000;
48
+
49
+ const streamedEvents = [
50
+ "session",
51
+ "sample",
52
+ "job",
53
+ "device",
54
+ "timeline",
55
+ ] satisfies (keyof StreamEvents)[];
56
+
57
+ /**
58
+ * Everything the UI shows, kept current from one EventSource. Changes are batched per animation frame
59
+ * and handed to the listener by topic.
60
+ */
61
+ export class Store {
62
+ readonly tree: ManifestTree;
63
+ /** The manifest's trace sites by id. */
64
+ readonly eventSites: ReadonlyMap<number, DebugEventSite>;
65
+ stream: StreamState = "connecting";
66
+ error: string | undefined;
67
+ samples = new Map<string, Sample>();
68
+ jobs = new Map<number, JobState>();
69
+ devices = new Map<string, DeviceState>();
70
+ watch: WatchGroups = { groups: {} };
71
+
72
+ private readonly recent = createRecentWindow(TIMELINE_LIMIT);
73
+ /** Browser clock minus host clock, from the fastest sample delivery seen. */
74
+ private hostSkewMs = Infinity;
75
+ private source: EventSource | undefined;
76
+ private showing: string | undefined;
77
+ /** The interest the open stream carries; nothing once the host refused it. */
78
+ private streaming: string | undefined;
79
+ private params: Record<string, string> = {};
80
+ private reopenTimer: ReturnType<typeof setTimeout> | undefined;
81
+ private timelineTimer: ReturnType<typeof setTimeout> | undefined;
82
+ private pending = new Set<Topic>();
83
+ private readonly pages = createPages({
84
+ show: (interest) => this.show(interest),
85
+ reportError: (error) => this.reportError(error),
86
+ });
87
+ private listener: (topics: Set<Topic>) => void = () => {};
88
+
89
+ constructor(
90
+ readonly manifest: DebugManifest,
91
+ public session: Session,
92
+ ) {
93
+ this.tree = new ManifestTree(manifest);
94
+ this.eventSites = new Map(manifest.events.map((site) => [site.id, site]));
95
+ setInterval(() => this.notify("clock"), 1000);
96
+ }
97
+
98
+ /** Oldest first, by `at`. */
99
+ get timeline() {
100
+ return this.recent.entries;
101
+ }
102
+
103
+ listen(listener: (topics: Set<Topic>) => void) {
104
+ this.listener = listener;
105
+ }
106
+
107
+ notify(topic: Topic) {
108
+ if (this.pending.size === 0) {
109
+ requestAnimationFrame(() => this.flush());
110
+ }
111
+ this.pending.add(topic);
112
+ }
113
+
114
+ private flush() {
115
+ const topics = this.pending;
116
+ this.pending = new Set();
117
+ this.listener(topics);
118
+ }
119
+
120
+ reportError(error: unknown) {
121
+ this.error = errorMessage(error);
122
+ this.notify("error");
123
+ }
124
+
125
+ clearError() {
126
+ this.error = undefined;
127
+ this.notify("error");
128
+ }
129
+
130
+ /** Host time now, so ages of host timestamps do not depend on the browser's clock. */
131
+ hostNow() {
132
+ return (
133
+ Date.now() - (Number.isFinite(this.hostSkewMs) ? this.hostSkewMs : 0)
134
+ );
135
+ }
136
+
137
+ ageOf(iso: string) {
138
+ return Math.max(0, this.hostNow() - Date.parse(iso));
139
+ }
140
+
141
+ get connected() {
142
+ return (
143
+ this.stream === "open" && this.session.connection.state === "connected"
144
+ );
145
+ }
146
+
147
+ live(path: string): LiveSample {
148
+ const sample = this.samples.get(path);
149
+ if (!sample) {
150
+ return { sample, state: "unavailable" };
151
+ }
152
+ const ageMs = this.ageOf(sample.receivedAt);
153
+ const state = valueState(sample.quality, ageMs, this.reading);
154
+ return { sample, state };
155
+ }
156
+
157
+ /** The state of a value read with no time of its own, so only the connection makes it stale. */
158
+ untimedState(quality: Quality): ValueState {
159
+ return valueState(quality, 0, this.reading);
160
+ }
161
+
162
+ private get reading() {
163
+ return {
164
+ connected: this.connected,
165
+ intervalMs: this.session.reading.intervalMs,
166
+ };
167
+ }
168
+
169
+ openPage(): Page {
170
+ return this.pages.open();
171
+ }
172
+
173
+ /** Reopens the stream once the interest settles on one the open stream does not carry. */
174
+ private show(interest: Partial<Interest>) {
175
+ const params = interestQuery(interest);
176
+ const showing = JSON.stringify(Object.entries(params).sort());
177
+ if (showing === this.showing) {
178
+ return;
179
+ }
180
+ this.showing = showing;
181
+ this.params = params;
182
+ clearTimeout(this.reopenTimer);
183
+ this.reopenTimer = setTimeout(
184
+ () => {
185
+ if (this.showing !== this.streaming) {
186
+ this.open();
187
+ }
188
+ },
189
+ this.source ? REOPEN_DEBOUNCE_MS : 0,
190
+ );
191
+ }
192
+
193
+ private open() {
194
+ this.source?.close();
195
+ const source = new EventSource(apiUrl("stream", this.params));
196
+ this.source = source;
197
+ this.streaming = this.showing;
198
+ source.onopen = () => {
199
+ this.stream = "open";
200
+ this.notify("stream");
201
+ void this.resync();
202
+ };
203
+ source.onerror = () => {
204
+ this.stream = "reconnecting";
205
+ this.notify("stream");
206
+ if (source.readyState === EventSource.CLOSED && this.source === source) {
207
+ this.streaming = undefined;
208
+ this.reopenTimer = setTimeout(() => this.open(), REFUSED_RETRY_MS);
209
+ }
210
+ };
211
+ for (const name of streamedEvents) {
212
+ source.addEventListener(name, (event) => {
213
+ try {
214
+ const decoded = decodeStreamEvent(name, event.data);
215
+ if (decoded) {
216
+ this.receive(decoded);
217
+ }
218
+ } catch (error) {
219
+ this.reportError(error);
220
+ }
221
+ });
222
+ }
223
+ }
224
+
225
+ private receive(event: StreamEvent) {
226
+ switch (event.name) {
227
+ case "session":
228
+ this.session = event.data;
229
+ this.notify("session");
230
+ break;
231
+ case "sample":
232
+ this.hostSkewMs = Math.min(
233
+ this.hostSkewMs,
234
+ Date.now() - Date.parse(event.data.receivedAt),
235
+ );
236
+ this.samples.set(event.data.path, event.data);
237
+ this.notify("samples");
238
+ break;
239
+ case "job":
240
+ this.jobs.set(event.data.id, event.data);
241
+ this.notify("jobs");
242
+ break;
243
+ case "device":
244
+ this.devices.set(event.data.id, event.data);
245
+ this.notify("devices");
246
+ break;
247
+ case "timeline":
248
+ this.addTimeline([event.data]);
249
+ break;
250
+ }
251
+ }
252
+
253
+ /** Catch up on what the stream does not replay: every (re)open may follow a gap. */
254
+ private async resync() {
255
+ try {
256
+ const after = this.recent.resumeAfter();
257
+ const [session, jobs, devices, timeline, watch] = await Promise.all([
258
+ getJson("session"),
259
+ getJson("jobs"),
260
+ getJson("hardware"),
261
+ getJson("timeline", after === undefined ? {} : { after }),
262
+ getJson("watch"),
263
+ ]);
264
+ this.session = session;
265
+ this.jobs = new Map(jobs.map((job) => [job.id, job]));
266
+ this.devices = new Map(devices.map((device) => [device.id, device]));
267
+ this.watch = watch;
268
+ this.addTimeline(timeline);
269
+ for (const topic of ["session", "jobs", "devices", "watch"] as const) {
270
+ this.notify(topic);
271
+ }
272
+ } catch (error) {
273
+ this.reportError(error);
274
+ }
275
+ }
276
+
277
+ private addTimeline(entries: readonly TimelineEntry[]) {
278
+ this.recent.add(entries);
279
+ if (this.timelineTimer === undefined) {
280
+ this.timelineTimer = setTimeout(() => {
281
+ this.timelineTimer = undefined;
282
+ this.notify("timeline");
283
+ }, TIMELINE_RENDER_MS);
284
+ }
285
+ }
286
+
287
+ async saveWatch(groups: Record<string, string[]>) {
288
+ try {
289
+ this.watch = await putJson("watch", { groups });
290
+ this.notify("watch");
291
+ } catch (error) {
292
+ this.reportError(error);
293
+ }
294
+ }
295
+ }
@@ -0,0 +1,11 @@
1
+ /** `load`, run once and its result kept; a failed load is forgotten, so the next call tries again. */
2
+ export const cacheSuccess = <T>(load: () => Promise<T>) => {
3
+ let loaded: Promise<T> | undefined;
4
+ return () => {
5
+ loaded ??= load().catch((error: unknown) => {
6
+ loaded = undefined;
7
+ throw error;
8
+ });
9
+ return loaded;
10
+ };
11
+ };
package/src/ui/tree.ts ADDED
@@ -0,0 +1,162 @@
1
+ import { joinPath } from "@tsplc/opcua/contract";
2
+ import type { DebugConstant, DebugManifest, SourceRange } from "../manifest";
3
+ import {
4
+ createPaths,
5
+ type Paths,
6
+ pathSegments,
7
+ type ResolvedPath,
8
+ typeOf,
9
+ } from "../paths";
10
+
11
+ /** One row of the instance tree: a root, a record field, an array element or a folded constant. */
12
+ export interface TreeNode {
13
+ path: string;
14
+ /** The last segment: a field name, `[3]`, or the whole path for a top-level node. */
15
+ name: string;
16
+ type: string;
17
+ declaration?: SourceRange;
18
+ /** Whether the target adapter can read it at runtime. */
19
+ readable: boolean;
20
+ generated: boolean;
21
+ constant?: DebugConstant;
22
+ }
23
+
24
+ export interface TreeRow {
25
+ node: TreeNode;
26
+ depth: number;
27
+ }
28
+
29
+ export const parentPath = (path: string) =>
30
+ pathSegments(path).slice(0, -1).reduce(joinPath, "");
31
+
32
+ /** Every proper prefix of `path` at a `.` or `[` boundary, shortest first. */
33
+ export const ancestorPaths = (path: string) =>
34
+ pathSegments(path)
35
+ .slice(0, -1)
36
+ .map((_, index, segments) =>
37
+ segments.slice(0, index + 1).reduce(joinPath, ""),
38
+ );
39
+
40
+ /** The manifest's instances as a lazily expanded tree, addressed by TypeScript path. */
41
+ export class ManifestTree {
42
+ readonly paths: Paths;
43
+ readonly top: TreeNode[];
44
+ private readonly children = new Map<string, TreeNode[]>();
45
+
46
+ constructor(readonly manifest: DebugManifest) {
47
+ this.paths = createPaths(manifest);
48
+ const orphans = manifest.constants.filter(
49
+ (constant) => !this.resolve(parentPath(constant.path)),
50
+ );
51
+ this.top = [...manifest.roots, ...orphans].flatMap(
52
+ ({ path }) => this.resolve(path) ?? [],
53
+ );
54
+ }
55
+
56
+ expandable(node: TreeNode) {
57
+ if (node.constant) {
58
+ return false;
59
+ }
60
+ const kind = typeOf(this.manifest, node.type).kind;
61
+ return kind === "record" || kind === "array";
62
+ }
63
+
64
+ /** A record's fields or an array's elements, then the constants folded below it. */
65
+ childrenOf(node: TreeNode): TreeNode[] {
66
+ const cached = this.children.get(node.path);
67
+ if (cached) {
68
+ return cached;
69
+ }
70
+ const children = this.paths
71
+ .children(node.path)
72
+ .flatMap((child) =>
73
+ child.kind === "group" ? [] : [this.node(child, node)],
74
+ );
75
+ this.children.set(node.path, children);
76
+ return children;
77
+ }
78
+
79
+ /** The rows shown for an expansion state, depth first. */
80
+ rows(
81
+ expanded: ReadonlySet<string>,
82
+ { showGenerated }: { showGenerated: boolean },
83
+ ): TreeRow[] {
84
+ const rows: TreeRow[] = [];
85
+ const visit = (nodes: TreeNode[], depth: number) => {
86
+ for (const node of nodes) {
87
+ if (node.generated && !showGenerated) {
88
+ continue;
89
+ }
90
+ rows.push({ node, depth });
91
+ if (expanded.has(node.path) && this.expandable(node)) {
92
+ visit(this.childrenOf(node), depth + 1);
93
+ }
94
+ }
95
+ };
96
+ visit(this.top, 0);
97
+ return rows;
98
+ }
99
+
100
+ /** Nodes whose path contains `query` (case-insensitive), in tree order, at most `limit`. */
101
+ search(
102
+ query: string,
103
+ { showGenerated, limit }: { showGenerated: boolean; limit: number },
104
+ ) {
105
+ const needle = query.toLowerCase();
106
+ const found: TreeNode[] = [];
107
+ let total = 0;
108
+ const visit = (nodes: TreeNode[]) => {
109
+ for (const node of nodes) {
110
+ if (node.generated && !showGenerated) {
111
+ continue;
112
+ }
113
+ if (node.path.toLowerCase().includes(needle)) {
114
+ total += 1;
115
+ if (total <= limit) {
116
+ found.push(node);
117
+ }
118
+ }
119
+ if (this.expandable(node)) {
120
+ visit(this.childrenOf(node));
121
+ }
122
+ }
123
+ };
124
+ visit(this.top);
125
+ return { nodes: found, total };
126
+ }
127
+
128
+ resolve(path: string): TreeNode | undefined {
129
+ const resolved = this.paths.resolve(path);
130
+ return resolved && this.node(resolved, this.resolve(parentPath(path)));
131
+ }
132
+
133
+ /**
134
+ * A resolved path as a row below `parent`: fields and elements of a compiler-made node are
135
+ * compiler-made too.
136
+ */
137
+ private node(resolved: ResolvedPath, parent: TreeNode | undefined): TreeNode {
138
+ const name = parent
139
+ ? resolved.path.slice(parent.path.length).replace(/^\./, "")
140
+ : resolved.path;
141
+ if (resolved.kind === "constant") {
142
+ const { path, type, value, declaration } = resolved;
143
+ return {
144
+ path,
145
+ name,
146
+ type,
147
+ declaration,
148
+ readable: false,
149
+ generated: false,
150
+ constant: { path, type, value, declaration },
151
+ };
152
+ }
153
+ return {
154
+ path: resolved.path,
155
+ name,
156
+ type: resolved.type,
157
+ declaration: resolved.declaration,
158
+ readable: resolved.readable,
159
+ generated: parent?.generated === true || resolved.generated === true,
160
+ };
161
+ }
162
+ }