@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,165 @@
1
+ import {
2
+ elementaryType,
3
+ isIntegerValued,
4
+ millisecondsPerDay,
5
+ nanosecondsPerMillisecond,
6
+ secondsPerDay,
7
+ stringType,
8
+ } from "@tsplc/iec";
9
+ import {
10
+ integerLiteral,
11
+ temporalPrefixes,
12
+ unescapeString,
13
+ } from "@tsplc/iec/st";
14
+ import { encodeConstant } from "./constant";
15
+ import type { DebugType } from "./manifest";
16
+
17
+ /** CODESYS's `TRUE`/`FALSE`, and the digits a BOOL may also read as. */
18
+ const booleans: Record<string, boolean> = {
19
+ TRUE: true,
20
+ FALSE: false,
21
+ "1": true,
22
+ "0": false,
23
+ };
24
+
25
+ const millisecondsPerSecond = Number(millisecondsPerDay / secondsPerDay);
26
+
27
+ const timeUnits: Record<string, number> = {
28
+ d: Number(millisecondsPerDay),
29
+ h: 3600 * millisecondsPerSecond,
30
+ m: 60 * millisecondsPerSecond,
31
+ s: millisecondsPerSecond,
32
+ ms: 1,
33
+ us: 0.001,
34
+ ns: 1 / Number(nanosecondsPerMillisecond),
35
+ };
36
+
37
+ const durationPrefixes = [...temporalPrefixes]
38
+ .flatMap(([prefix, type]) => (type.family === "duration" ? [prefix] : []))
39
+ .join("|");
40
+ const durationLiteral = new RegExp(`^(?:${durationPrefixes})#(-?)(.+)$`, "i");
41
+
42
+ /** A typed literal's type, as in `INT#5`, but not a duration's own prefix. */
43
+ const typePrefix = new RegExp(
44
+ `^(?!(?:${durationPrefixes})#)[a-z_]+#(?=.)`,
45
+ "i",
46
+ );
47
+
48
+ const withoutTypePrefix = (text: string) => text.replace(typePrefix, "");
49
+
50
+ /** An integer literal, as the debugger decodes integers. */
51
+ const integer = (text: string) => {
52
+ const value = integerLiteral(text);
53
+ return value === undefined
54
+ ? undefined
55
+ : encodeConstant({ kind: "integer", value });
56
+ };
57
+
58
+ const real = (text: string) => {
59
+ const number = Number(text);
60
+ return text !== "" && !Number.isNaN(number) ? number : undefined;
61
+ };
62
+
63
+ /** `T#1h2m3s4ms`, `TIME#-1.5s`, `LTIME#5us`, in milliseconds. */
64
+ const duration = (text: string) => {
65
+ const [, sign, body] = durationLiteral.exec(text) ?? [];
66
+ if (body === undefined) {
67
+ return undefined;
68
+ }
69
+ const units = body.replaceAll("_", "");
70
+ const parts = [...units.matchAll(/(\d+(?:\.\d+)?)(ms|us|ns|d|h|m|s)/gi)];
71
+ if (parts.map(([part]) => part).join("") !== units) {
72
+ return undefined;
73
+ }
74
+ const ms = parts.reduce<number | undefined>((total, [, amount, unit]) => {
75
+ const factor =
76
+ unit === undefined ? undefined : timeUnits[unit.toLowerCase()];
77
+ return total === undefined || factor === undefined
78
+ ? undefined
79
+ : total + Number(amount) * factor;
80
+ }, 0);
81
+ return ms !== undefined && sign ? -ms : ms;
82
+ };
83
+
84
+ /** `'it$'s'` or `"wide"`, with IEC's `$` escapes. */
85
+ const quoted = (text: string, wide: boolean) => {
86
+ const [, , body] = /^(['"])(.*)\1$/s.exec(text) ?? [];
87
+ return body === undefined ? undefined : unescapeString(body, { wide });
88
+ };
89
+
90
+ /** A member's number, or the name the login gave when the manifest doesn't list it. */
91
+ const enumValue = (
92
+ type: Extract<DebugType, { kind: "enum" }>,
93
+ text: string,
94
+ ) => {
95
+ const number = integer(text);
96
+ if (typeof number === "number") {
97
+ return number;
98
+ }
99
+ // `E_Bin.Present`, `Present`, or a member the manifest lacks with its number: `Missing (7)`.
100
+ const [, name, value] =
101
+ /^(?:\w+\.)*(\w+)(?:\s*\((-?\d+)\))?$/.exec(text) ?? [];
102
+ if (name === undefined) {
103
+ return undefined;
104
+ }
105
+ return type.members[name] ?? (value === undefined ? name : Number(value));
106
+ };
107
+
108
+ /** Only raw assembly bytes are read whole; their elements are scalars named by IEC type. */
109
+ const arrayValue = (
110
+ type: Extract<DebugType, { kind: "array" }>,
111
+ text: string,
112
+ ) => {
113
+ const items = text.replace(/^\[/, "").replace(/\]$/, "").trim();
114
+ if (!items) {
115
+ return [];
116
+ }
117
+ const values = items
118
+ .split(/\s*,\s*/)
119
+ .map((item) => scalarValue(type.element, item));
120
+ return values.length === type.length &&
121
+ values.every((value) => value !== undefined)
122
+ ? values
123
+ : undefined;
124
+ };
125
+
126
+ const scalarValue = (iec: string, text: string): unknown => {
127
+ const untyped = withoutTypePrefix(text);
128
+ const name = iec.toUpperCase();
129
+ const type = elementaryType(name);
130
+ if (isIntegerValued(type)) {
131
+ return integer(untyped);
132
+ }
133
+ switch (type?.family) {
134
+ case "bool":
135
+ return booleans[untyped.toUpperCase()];
136
+ case "real":
137
+ return real(untyped);
138
+ case "duration":
139
+ return duration(text);
140
+ case "string":
141
+ return quoted(text, name === "WSTRING") ?? text;
142
+ }
143
+ const sized = stringType(name);
144
+ return sized ? (quoted(text, sized.wide) ?? text) : text;
145
+ };
146
+
147
+ /**
148
+ * A value as `read_value` returns it, in the form the debugger decodes: BOOL as a boolean,
149
+ * numbers and TIME (in ms) as numbers, enums as their member's number (or its name when the
150
+ * manifest doesn't list it), STRING unquoted, and arrays read whole as arrays. Undefined when the
151
+ * text doesn't fit the type.
152
+ */
153
+ export const parseLoginValue = (type: DebugType, text: string): unknown => {
154
+ const trimmed = text.trim();
155
+ switch (type.kind) {
156
+ case "enum":
157
+ return enumValue(type, withoutTypePrefix(trimmed));
158
+ case "array":
159
+ return arrayValue(type, withoutTypePrefix(trimmed));
160
+ case "record":
161
+ return undefined;
162
+ case "scalar":
163
+ return scalarValue(type.iec, trimmed);
164
+ }
165
+ };
package/src/login.ts ADDED
@@ -0,0 +1,315 @@
1
+ import { sleep } from "@tsplc/opcua";
2
+ import type {
3
+ Connection,
4
+ TargetAdapter,
5
+ TargetRead,
6
+ TargetSample,
7
+ } from "./adapter";
8
+ import type { DebuggerOptions } from "./debugger";
9
+ import { errorMessage } from "./errors";
10
+ import { parseLoginValue } from "./login-value";
11
+ import type { DebugManifest, DebugType } from "./manifest";
12
+
13
+ /** Why the login can't read now; `state` is what the debugger shows meanwhile. */
14
+ export class LoginUnavailable extends Error {
15
+ constructor(
16
+ message: string,
17
+ options?: ErrorOptions & { state?: "connecting" | "unavailable" },
18
+ ) {
19
+ super(message, options);
20
+ this.state = options?.state ?? "unavailable";
21
+ }
22
+
23
+ readonly state: "connecting" | "unavailable";
24
+ }
25
+
26
+ export const noLogin =
27
+ "Live values need an engineering login: run `tsplc login`.";
28
+
29
+ /** How long to wait between attempts while there is no login to read through. */
30
+ const retryMs = 5000;
31
+ /** A read still unanswered after this many sampling intervals means the login stopped answering. */
32
+ const stalledIntervals = 3;
33
+ /** Timers fire a little early or late; a subscription due within this part of an interval is read now. */
34
+ const dueTolerance = 0.5;
35
+
36
+ /** The login's text for each expression it returned, and the call that returned it. */
37
+ type Texts = Record<string, { text: string; read: number }>;
38
+
39
+ const typeName = (type: DebugType) =>
40
+ type.kind === "scalar" ? type.iec : type.kind;
41
+
42
+ /**
43
+ * Reads through an engineering login that answers `read(expressions)` with CODESYS's own text
44
+ * for each value: no publication is needed, and nothing is subscribed. Watched targets are polled
45
+ * every `samplingMs`, one command per poll, and a poll that overruns delays the next by as long.
46
+ *
47
+ * A read fails as a whole when one expression can't be read, so a failing read is retried with
48
+ * `probe` alone: if that fails too the login is lost; otherwise the read is split until the
49
+ * expressions that fail are found, and those are reported bad until the next login.
50
+ */
51
+ export const createLoginAdapter = (options: {
52
+ read: (expressions: string[]) => Promise<Record<string, string>>;
53
+ /** A target that always reads, such as the build id. */
54
+ probe: string;
55
+ endpoint: string;
56
+ samplingMs?: number;
57
+ }): TargetAdapter => {
58
+ const samplingMs = options.samplingMs ?? 1000;
59
+ let connection: Connection = {
60
+ state: "connecting",
61
+ since: new Date().toISOString(),
62
+ };
63
+ const connectionListeners = new Set<(connection: Connection) => void>();
64
+ const subscriptions = new Set<{
65
+ targets: readonly TargetRead[];
66
+ listener: (target: string, sample: TargetSample) => void;
67
+ intervalMs: number;
68
+ due: number;
69
+ }>();
70
+ /** Expressions the controller refused, with its reason, until the login is lost. */
71
+ const rejected = new Map<string, string>();
72
+ const controller = new AbortController();
73
+
74
+ const setConnection = (state: Connection["state"], error?: string) => {
75
+ if (controller.signal.aborted) {
76
+ return;
77
+ }
78
+ if (connection.state === state && connection.error === error) {
79
+ return;
80
+ }
81
+ if (state !== "connected") {
82
+ rejected.clear();
83
+ }
84
+ connection = {
85
+ state,
86
+ since: new Date().toISOString(),
87
+ ...(error && { error }),
88
+ };
89
+ for (const listener of connectionListeners) {
90
+ listener(connection);
91
+ }
92
+ };
93
+
94
+ /** Each `read_values` call's own sequence, so a read split into several calls is never taken as one. */
95
+ let reads = 0;
96
+ const readCall = async (expressions: string[]): Promise<Texts> => {
97
+ const texts = await options.read(expressions);
98
+ reads += 1;
99
+ const read = reads;
100
+ return Object.fromEntries(
101
+ Object.entries(texts).map(([target, text]) => [target, { text, read }]),
102
+ );
103
+ };
104
+
105
+ const split = async (expressions: string[]): Promise<Texts> => {
106
+ try {
107
+ return await readCall(expressions);
108
+ } catch (error) {
109
+ if (error instanceof LoginUnavailable) {
110
+ throw error;
111
+ }
112
+ const [only, ...others] = expressions;
113
+ if (only !== undefined && !others.length) {
114
+ rejected.set(only, errorMessage(error));
115
+ return {};
116
+ }
117
+ const half = Math.ceil(expressions.length / 2);
118
+ return {
119
+ ...(await split(expressions.slice(0, half))),
120
+ ...(await split(expressions.slice(half))),
121
+ };
122
+ }
123
+ };
124
+
125
+ const readText = async (expressions: string[]): Promise<Texts> => {
126
+ try {
127
+ return await readCall(expressions);
128
+ } catch (error) {
129
+ if (error instanceof LoginUnavailable) {
130
+ throw error;
131
+ }
132
+ // One expression the controller can't read fails the whole read; a lost login fails the probe too.
133
+ await options.read([options.probe]);
134
+ return split(expressions);
135
+ }
136
+ };
137
+
138
+ /** The login's text for each expression, or why it can't read; keeps `connection` current. */
139
+ const readTexts = async (
140
+ expressions: string[],
141
+ ): Promise<{ texts: Texts } | { error: string }> => {
142
+ const overdue = setTimeout(
143
+ () => setConnection("lost", "The engineering login stopped answering"),
144
+ stalledIntervals * samplingMs,
145
+ );
146
+ try {
147
+ const texts = expressions.length ? await readText(expressions) : {};
148
+ setConnection("connected");
149
+ return { texts };
150
+ } catch (error) {
151
+ setConnection(
152
+ error instanceof LoginUnavailable ? error.state : "lost",
153
+ errorMessage(error),
154
+ );
155
+ return { error: errorMessage(error) };
156
+ } finally {
157
+ clearTimeout(overdue);
158
+ }
159
+ };
160
+
161
+ /** A target's value from the login's text, or bad with the reason it has none. */
162
+ const parsedSample = (
163
+ { target, type }: TargetRead,
164
+ returned: Texts[string] | undefined,
165
+ receivedAt: string,
166
+ ): TargetSample => {
167
+ const text = returned?.text;
168
+ const value = text === undefined ? undefined : parseLoginValue(type, text);
169
+ if (value !== undefined && returned) {
170
+ return {
171
+ value,
172
+ quality: "good",
173
+ status: "Good",
174
+ receivedAt,
175
+ read: returned.read,
176
+ };
177
+ }
178
+ const reason =
179
+ text === undefined
180
+ ? "Not returned by the login"
181
+ : `Not a ${typeName(type)}`;
182
+ return {
183
+ value: text ?? null,
184
+ quality: "bad",
185
+ status: rejected.get(target) ?? reason,
186
+ receivedAt,
187
+ };
188
+ };
189
+
190
+ /** Never fails: while the login can't read, every target is unavailable. */
191
+ const read = async (targets: readonly TargetRead[]) => {
192
+ const unique = [
193
+ ...new Map(targets.map((target) => [target.target, target])).values(),
194
+ ];
195
+ const result = await readTexts(
196
+ unique
197
+ .map(({ target }) => target)
198
+ .filter((target) => !rejected.has(target)),
199
+ );
200
+ const receivedAt = new Date().toISOString();
201
+ if ("error" in result) {
202
+ return new Map<string, TargetSample>(
203
+ unique.map(({ target }) => [
204
+ target,
205
+ {
206
+ value: null,
207
+ quality: "unavailable",
208
+ status: result.error,
209
+ receivedAt,
210
+ },
211
+ ]),
212
+ );
213
+ }
214
+ return new Map(
215
+ unique.map((read) => [
216
+ read.target,
217
+ parsedSample(read, result.texts[read.target], receivedAt),
218
+ ]),
219
+ );
220
+ };
221
+
222
+ /** Until the next poll: the rest of the interval, as long again after an overrun, longer without a login. */
223
+ const pauseAfter = (tookMs: number) => {
224
+ if (connection.state !== "connected" && connection.state !== "connecting") {
225
+ return retryMs;
226
+ }
227
+ return tookMs > samplingMs ? tookMs : samplingMs - tookMs;
228
+ };
229
+
230
+ const poll = async () => {
231
+ while (!controller.signal.aborted) {
232
+ const started = Date.now();
233
+ const due = [...subscriptions].filter(
234
+ ({ due }) => due <= started + samplingMs * dueTolerance,
235
+ );
236
+ if (due.length) {
237
+ for (const subscription of due) {
238
+ subscription.due = started + subscription.intervalMs;
239
+ }
240
+ // Closing the debugger must not wait for an engineering worker that stopped answering.
241
+ const stopped = Promise.withResolvers<void>();
242
+ const stop = () => stopped.resolve();
243
+ controller.signal.addEventListener("abort", stop, { once: true });
244
+ const samples = await Promise.race([
245
+ read(due.flatMap(({ targets }) => targets)),
246
+ stopped.promise,
247
+ ]).finally(() => controller.signal.removeEventListener("abort", stop));
248
+ if (!samples || controller.signal.aborted) {
249
+ break;
250
+ }
251
+ for (const subscription of due) {
252
+ if (subscriptions.has(subscription)) {
253
+ for (const { target } of subscription.targets) {
254
+ const sample = samples.get(target);
255
+ if (sample) {
256
+ subscription.listener(target, sample);
257
+ }
258
+ }
259
+ }
260
+ }
261
+ }
262
+ await sleep(pauseAfter(Date.now() - started), controller.signal);
263
+ }
264
+ };
265
+ const running = poll();
266
+
267
+ return {
268
+ method: "engineering login",
269
+ endpoint: options.endpoint,
270
+ samplingMs,
271
+ connection: () => connection,
272
+ onConnection: (listener) => {
273
+ connectionListeners.add(listener);
274
+ return () => connectionListeners.delete(listener);
275
+ },
276
+ read,
277
+ subscribe: (targets, listener, intervalMs = samplingMs) => {
278
+ const subscription = { targets, listener, intervalMs, due: 0 };
279
+ subscriptions.add(subscription);
280
+ return () => subscriptions.delete(subscription);
281
+ },
282
+ close: async () => {
283
+ controller.abort();
284
+ subscriptions.clear();
285
+ connectionListeners.clear();
286
+ await running;
287
+ },
288
+ };
289
+ };
290
+
291
+ /**
292
+ * The controller of a debugger that reads through an engineering login: a login adapter that
293
+ * probes the manifest's build id, and the forced expressions the login reports.
294
+ */
295
+ export const loginReader = (
296
+ manifest: DebugManifest,
297
+ login: {
298
+ read: (expressions: string[]) => Promise<Record<string, string>>;
299
+ /** The login's state, with the expressions the controller forces, or why it can't report them. */
300
+ status: () => Promise<
301
+ { forced: readonly string[] } | { error: string } | null
302
+ >;
303
+ endpoint: string;
304
+ },
305
+ ): Pick<DebuggerOptions, "adapter" | "forced"> => ({
306
+ adapter: createLoginAdapter({
307
+ read: login.read,
308
+ probe: manifest.build.target,
309
+ endpoint: login.endpoint,
310
+ }),
311
+ forced: async () => {
312
+ const status = await login.status();
313
+ return status && "forced" in status ? status.forced : null;
314
+ },
315
+ });