@vehicle-sil/gui-client 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3681 @@
1
+ // ../client/src/values.ts
2
+ var rethrowLater = (error) => queueMicrotask(() => {
3
+ throw error;
4
+ });
5
+ function callEach(listeners, args, onError, stillCurrent = () => true) {
6
+ for (const listener of [...listeners]) {
7
+ if (!stillCurrent()) return;
8
+ try {
9
+ listener(...args);
10
+ } catch (error) {
11
+ try {
12
+ onError(error);
13
+ } catch (sinkError) {
14
+ rethrowLater(sinkError);
15
+ }
16
+ }
17
+ }
18
+ }
19
+ var Writable = class {
20
+ constructor(initial, equal = Object.is, onError = rethrowLater) {
21
+ this.equal = equal;
22
+ this.onError = onError;
23
+ this.value = initial;
24
+ }
25
+ equal;
26
+ onError;
27
+ value;
28
+ version = 0;
29
+ listeners = /* @__PURE__ */ new Set();
30
+ get() {
31
+ return this.value;
32
+ }
33
+ set(value) {
34
+ if (this.equal(this.value, value)) return;
35
+ this.value = value;
36
+ const version2 = ++this.version;
37
+ callEach(this.listeners, [value], this.onError, () => this.version === version2);
38
+ }
39
+ update(change) {
40
+ this.set(change(this.value));
41
+ }
42
+ subscribe(listener) {
43
+ this.listeners.add(listener);
44
+ return () => {
45
+ this.listeners.delete(listener);
46
+ };
47
+ }
48
+ /** Read-only view (get and subscribe only). */
49
+ readonly() {
50
+ return { get: () => this.get(), subscribe: (listener) => this.subscribe(listener) };
51
+ }
52
+ };
53
+ function derived(sources, compute, equal = Object.is, onError = rethrowLater) {
54
+ const value = new Writable(compute(), equal, onError);
55
+ for (const source of sources) source.subscribe(() => value.set(compute()));
56
+ return value.readonly();
57
+ }
58
+ function shallowEqual(a, b) {
59
+ if (Object.is(a, b)) return true;
60
+ const keys = Object.keys(a);
61
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.is(a[key], b[key]));
62
+ }
63
+
64
+ // ../client/src/connection.ts
65
+ var TRY_AGAIN_LATER = 1013;
66
+ var BATCH_MS = 100;
67
+ var STEADY_MS = 3e4;
68
+ var NOT_OPENED = 1006;
69
+ function webSocketFactory(options = {}) {
70
+ return (url, on) => {
71
+ const WebSocketClass = globalThis.WebSocket;
72
+ let socket;
73
+ try {
74
+ socket = options.origin ? new WebSocketClass(url, { headers: { Origin: options.origin } }) : new WebSocketClass(url);
75
+ } catch (error) {
76
+ const reason = `cannot open the WebSocket: ${error instanceof Error ? error.message : String(error)}`;
77
+ setTimeout(() => on.close(NOT_OPENED, reason), 0);
78
+ return { send: () => void 0, close: () => void 0 };
79
+ }
80
+ socket.onopen = () => on.open();
81
+ socket.onmessage = (event) => on.message(typeof event.data === "string" ? event.data : String(event.data));
82
+ socket.onclose = (event) => on.close(event.code ?? 0, event.reason ?? "");
83
+ return { send: (text2) => socket.send(text2), close: () => socket.close() };
84
+ };
85
+ }
86
+ function backoffMs(attempt, maxMs = 5e3) {
87
+ return Math.min(500 * 2 ** (attempt - 1), maxMs);
88
+ }
89
+ var Connection = class {
90
+ constructor(options) {
91
+ this.options = options;
92
+ this.onError = options.onError ?? rethrowLater;
93
+ this.stateValue = new Writable("closed", Object.is, this.onError);
94
+ this.failureCount = new Writable(0, Object.is, this.onError);
95
+ this.lastCloseValue = new Writable(null, Object.is, this.onError);
96
+ this.state = this.stateValue.readonly();
97
+ this.failures = this.failureCount.readonly();
98
+ this.lastClose = this.lastCloseValue.readonly();
99
+ this.tryAgainReason = derived(
100
+ [this.lastClose],
101
+ () => {
102
+ const close = this.lastClose.get();
103
+ return close?.code === TRY_AGAIN_LATER ? close.reason || "try-again-later" : null;
104
+ },
105
+ Object.is,
106
+ this.onError
107
+ );
108
+ }
109
+ options;
110
+ onError;
111
+ stateValue;
112
+ failureCount;
113
+ lastCloseValue;
114
+ batchListeners = /* @__PURE__ */ new Set();
115
+ unreadableListeners = /* @__PURE__ */ new Set();
116
+ socket = null;
117
+ wanted = false;
118
+ /** Consecutive drops without a readable notification. */
119
+ attempts = 0;
120
+ /** Consecutive restarts (restart). */
121
+ restarts = 0;
122
+ restartAsked = false;
123
+ /** Consecutive restarts caused by non-JSON notifications. Reset to 0 after staying connected for STEADY_MS. */
124
+ garbled = 0;
125
+ steadyTimer;
126
+ retryTimer;
127
+ batchTimer;
128
+ pending = [];
129
+ state;
130
+ failures;
131
+ lastClose;
132
+ tryAgainReason;
133
+ /** Connects (does nothing if connected or waiting to reconnect). */
134
+ connect() {
135
+ if (this.wanted) return;
136
+ this.wanted = true;
137
+ this.open();
138
+ }
139
+ /** Disconnects, without reconnecting. Drops notifications still being batched. */
140
+ close() {
141
+ this.wanted = false;
142
+ this.restarts = 0;
143
+ this.attempts = 0;
144
+ this.garbled = 0;
145
+ clearTimeout(this.retryTimer);
146
+ clearTimeout(this.steadyTimer);
147
+ this.dropPending();
148
+ const socket = this.socket;
149
+ this.socket = null;
150
+ socket?.close();
151
+ this.stateValue.set("closed");
152
+ }
153
+ /**
154
+ * Drops the current connection and reconnects after a delay (when a reader could not rebuild its state from the
155
+ * notifications). The delay grows with each consecutive restart.
156
+ */
157
+ restart() {
158
+ this.restartAfter(backoffMs(++this.restarts, this.options.maxBackoffMs));
159
+ }
160
+ restartAfter(delayMs) {
161
+ if (!this.wanted) return;
162
+ this.restartAsked = true;
163
+ this.dropPending();
164
+ clearTimeout(this.steadyTimer);
165
+ const socket = this.socket;
166
+ this.socket = null;
167
+ socket?.close();
168
+ this.stateValue.set("closed");
169
+ this.scheduleRetry(delayMs);
170
+ }
171
+ /**
172
+ * Sends a notification to the server (one that follows authentication, such as a variable subscription). Sends only
173
+ * while open and returns whether it sent. What could not be sent goes out with afterGreeting on the next open.
174
+ */
175
+ send(message) {
176
+ if (this.socket === null || this.stateValue.get() !== "open") return false;
177
+ try {
178
+ this.socket.send(JSON.stringify(message));
179
+ return true;
180
+ } catch (error) {
181
+ this.onError(error);
182
+ return false;
183
+ }
184
+ }
185
+ onBatch(listener) {
186
+ this.batchListeners.add(listener);
187
+ return () => {
188
+ this.batchListeners.delete(listener);
189
+ };
190
+ }
191
+ onUnreadable(listener) {
192
+ this.unreadableListeners.add(listener);
193
+ return () => {
194
+ this.unreadableListeners.delete(listener);
195
+ };
196
+ }
197
+ /** Passes on the batched notifications without waiting. */
198
+ flush() {
199
+ clearTimeout(this.batchTimer);
200
+ this.batchTimer = void 0;
201
+ const batch = this.pending;
202
+ this.pending = [];
203
+ if (batch.length === 0) return;
204
+ this.restartAsked = false;
205
+ callEach(this.batchListeners, [batch], this.onError);
206
+ if (!this.restartAsked) this.restarts = 0;
207
+ }
208
+ dropPending() {
209
+ clearTimeout(this.batchTimer);
210
+ this.batchTimer = void 0;
211
+ this.pending = [];
212
+ }
213
+ open() {
214
+ try {
215
+ this.openSocket();
216
+ } catch (error) {
217
+ this.onError(error);
218
+ this.socket = null;
219
+ this.lastCloseValue.set({
220
+ code: NOT_OPENED,
221
+ reason: `cannot open the WebSocket: ${error instanceof Error ? error.message : String(error)}`
222
+ });
223
+ this.stateValue.set("closed");
224
+ this.scheduleRetry(backoffMs(++this.attempts, this.options.maxBackoffMs));
225
+ }
226
+ }
227
+ openSocket() {
228
+ const greeting = this.options.greeting();
229
+ this.stateValue.set("connecting");
230
+ let opened = false;
231
+ let socket = null;
232
+ const current = () => socket !== null && this.socket === socket;
233
+ const handlers = {
234
+ open: () => {
235
+ if (!current()) return;
236
+ opened = true;
237
+ this.stateValue.set("open");
238
+ clearTimeout(this.steadyTimer);
239
+ this.steadyTimer = setTimeout(() => this.garbled = 0, STEADY_MS);
240
+ for (const message of greeting) socket?.send(JSON.stringify(message));
241
+ try {
242
+ for (const message of this.options.afterGreeting?.() ?? []) {
243
+ socket?.send(JSON.stringify(message));
244
+ }
245
+ } catch (error) {
246
+ this.onError(error);
247
+ }
248
+ },
249
+ message: (text2) => {
250
+ if (!current()) return;
251
+ let message;
252
+ try {
253
+ message = JSON.parse(text2);
254
+ } catch {
255
+ callEach(this.unreadableListeners, [text2], this.onError);
256
+ this.restartAfter(backoffMs(++this.garbled, this.options.maxBackoffMs));
257
+ return;
258
+ }
259
+ this.attempts = 0;
260
+ if (this.lastCloseValue.get() !== null) this.lastCloseValue.set(null);
261
+ this.pending.push(message);
262
+ this.batchTimer ??= setTimeout(() => this.flush(), this.options.batchMs ?? BATCH_MS);
263
+ },
264
+ close: (code, reason) => {
265
+ if (!current()) return;
266
+ this.socket = null;
267
+ clearTimeout(this.steadyTimer);
268
+ if (!opened) this.failureCount.update((n) => n + 1);
269
+ this.lastCloseValue.set({ code, reason });
270
+ this.stateValue.set("closed");
271
+ this.scheduleRetry(backoffMs(++this.attempts, this.options.maxBackoffMs));
272
+ }
273
+ };
274
+ socket = this.options.socket(this.options.url, handlers);
275
+ this.socket = socket;
276
+ }
277
+ scheduleRetry(delayMs) {
278
+ if (!this.wanted) return;
279
+ clearTimeout(this.retryTimer);
280
+ this.retryTimer = setTimeout(() => {
281
+ if (this.wanted && this.socket === null) this.open();
282
+ }, delayMs);
283
+ }
284
+ };
285
+
286
+ // ../client/src/protocol.ts
287
+ var ProtocolError = class extends Error {
288
+ constructor(path, expected) {
289
+ super(`${path}: expected ${expected}`);
290
+ this.path = path;
291
+ this.expected = expected;
292
+ this.name = "ProtocolError";
293
+ }
294
+ path;
295
+ expected;
296
+ };
297
+ var PROTOCOL_VERSION = 1;
298
+ function object(value, path) {
299
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
300
+ throw new ProtocolError(path, "an object");
301
+ }
302
+ return value;
303
+ }
304
+ var string = (value, path) => {
305
+ if (typeof value !== "string") throw new ProtocolError(path, "a string");
306
+ return value;
307
+ };
308
+ var number = (value, path) => {
309
+ if (typeof value !== "number" || !Number.isFinite(value)) {
310
+ throw new ProtocolError(path, "a number");
311
+ }
312
+ return value;
313
+ };
314
+ var integer = (value, path) => {
315
+ if (!Number.isInteger(value)) throw new ProtocolError(path, "an integer");
316
+ return value;
317
+ };
318
+ var boolean = (value, path) => {
319
+ if (typeof value !== "boolean") throw new ProtocolError(path, "true or false");
320
+ return value;
321
+ };
322
+ function nullable(read2) {
323
+ return (value, path) => value === null ? null : read2(value, path);
324
+ }
325
+ function optional(read2, fallback) {
326
+ return (value, path) => value === void 0 ? fallback : read2(value, path);
327
+ }
328
+ function array(read2) {
329
+ return (value, path) => {
330
+ if (!Array.isArray(value)) throw new ProtocolError(path, "an array");
331
+ return value.map((item, i) => read2(item, `${path}[${i}]`));
332
+ };
333
+ }
334
+ function field(fields, path, key, read2) {
335
+ return read2(fields[key], `${path}.${key}`);
336
+ }
337
+ var Unreadable = class {
338
+ constructor(root, prefix = "") {
339
+ this.root = root;
340
+ this.prefix = prefix;
341
+ }
342
+ root;
343
+ prefix;
344
+ names = /* @__PURE__ */ new Set();
345
+ add(path) {
346
+ const relative = path.startsWith(`${this.root}.`) ? path.slice(this.root.length + 1) : path;
347
+ this.names.add(this.prefix + relative.replace(/\[\d+\]/g, ""));
348
+ }
349
+ get parts() {
350
+ return [...this.names];
351
+ }
352
+ };
353
+ function lenient(read2, fallback, u) {
354
+ if (!u) return read2;
355
+ return (value, path) => {
356
+ try {
357
+ return read2(value, path);
358
+ } catch (error) {
359
+ if (!(error instanceof ProtocolError)) throw error;
360
+ u.add(error.path);
361
+ return fallback;
362
+ }
363
+ };
364
+ }
365
+ function soft(read2, fallback, u) {
366
+ return lenient(optional(read2, fallback), fallback, u);
367
+ }
368
+ function items(read2, u) {
369
+ if (!u) return array(read2);
370
+ return (value, path) => {
371
+ if (!Array.isArray(value)) {
372
+ u.add(path);
373
+ return [];
374
+ }
375
+ const out = [];
376
+ value.forEach((item, i) => {
377
+ try {
378
+ out.push(read2(item, `${path}[${i}]`));
379
+ } catch (error) {
380
+ if (!(error instanceof ProtocolError)) throw error;
381
+ u.add(error.path);
382
+ }
383
+ });
384
+ return out;
385
+ };
386
+ }
387
+ function version(fields, path, key, expected, u) {
388
+ if (fields[key] !== expected) {
389
+ const error = new ProtocolError(`${path}.${key}`, `format version ${expected}`);
390
+ if (!u) throw error;
391
+ u.add(error.path);
392
+ }
393
+ }
394
+ function severityRank(severity) {
395
+ return severity === "note" ? 2 : severity === "warning" ? 1 : 0;
396
+ }
397
+ var readFinding = (value, path, u) => {
398
+ const f = object(value, path);
399
+ return {
400
+ severity: field(f, path, "severity", string),
401
+ code: field(f, path, "code", lenient(string, "", u)),
402
+ file: field(f, path, "file", soft(nullable(string), null, u)),
403
+ line: field(f, path, "line", soft(nullable(integer), null, u)),
404
+ participant: field(f, path, "participant", soft(nullable(string), null, u)),
405
+ network: field(f, path, "network", soft(nullable(string), null, u)),
406
+ message: field(f, path, "message", string),
407
+ detail: field(f, path, "detail", soft(nullable(string), null, u))
408
+ };
409
+ };
410
+ var readVariable = (value, path) => {
411
+ const f = object(value, path);
412
+ return {
413
+ name: field(f, path, "name", string),
414
+ type: field(f, path, "type", string),
415
+ causality: field(f, path, "causality", string),
416
+ unit: field(f, path, "unit", optional(string, "")),
417
+ min: field(f, path, "min", optional(nullable(number), null)),
418
+ max: field(f, path, "max", optional(nullable(number), null)),
419
+ builtin: field(f, path, "builtin", optional(nullable(boolean), null))
420
+ };
421
+ };
422
+ var FEATURE_SCENARIO = "scenario";
423
+ var FEATURE_SCENARIO_CONTROL = "scenario-control";
424
+ var FEATURE_MANUAL = "manual-participants";
425
+ var readScenarioStepFields = (f, path, u) => ({
426
+ index: field(f, path, "index", integer),
427
+ line: field(f, path, "line", soft(nullable(integer), null, u)),
428
+ kind: field(f, path, "kind", lenient(string, "", u)),
429
+ text: field(f, path, "text", lenient(string, "", u)),
430
+ status: field(f, path, "status", string),
431
+ start_ms: field(f, path, "start_ms", soft(nullable(number), null, u)),
432
+ at_ms: field(f, path, "at_ms", soft(nullable(number), null, u)),
433
+ end_ms: field(f, path, "end_ms", soft(nullable(number), null, u)),
434
+ code: field(f, path, "code", soft(nullable(string), null, u)),
435
+ message: field(f, path, "message", soft(nullable(string), null, u))
436
+ });
437
+ var readScenarioStep = (value, path, u) => readScenarioStepFields(object(value, path), path, u);
438
+ var readCheckScenario = (value, path, u) => {
439
+ const f = object(value, path);
440
+ return {
441
+ file: field(f, path, "file", lenient(string, "", u)),
442
+ name: field(f, path, "name", soft(nullable(string), null, u)),
443
+ steps: field(f, path, "steps", lenient(integer, 0, u))
444
+ };
445
+ };
446
+ var readScenarioResult = (value, path, u) => {
447
+ const f = object(value, path);
448
+ return {
449
+ file: field(f, path, "file", lenient(string, "", u)),
450
+ name: field(f, path, "name", soft(nullable(string), null, u)),
451
+ status: field(f, path, "status", lenient(string, "", u)),
452
+ over_at_ms: field(f, path, "over_at_ms", soft(nullable(number), null, u)),
453
+ steps: field(
454
+ f,
455
+ path,
456
+ "steps",
457
+ items((v, p) => readScenarioStep(v, p, u), u)
458
+ )
459
+ };
460
+ };
461
+ var readCheckParticipant = (value, path, u) => {
462
+ const f = object(value, path);
463
+ return {
464
+ name: field(f, path, "name", nullable(string)),
465
+ line: field(f, path, "line", soft(nullable(integer), null, u)),
466
+ required: field(f, path, "required", lenient(nullable(boolean), null, u)),
467
+ enabled: field(f, path, "enabled", lenient(nullable(boolean), null, u)),
468
+ manual: field(f, path, "manual", soft(boolean, false, u)),
469
+ step_ms: field(f, path, "step_ms", lenient(nullable(number), null, u)),
470
+ status: field(f, path, "status", lenient(string, "", u)),
471
+ variables: field(
472
+ f,
473
+ path,
474
+ "variables",
475
+ soft(nullable(u ? items(readVariable, u) : array(readVariable)), null, u)
476
+ ),
477
+ control: field(
478
+ f,
479
+ path,
480
+ CONTROL_CHECK_KEY,
481
+ soft(
482
+ nullable((v, p) => readControlOffer(v, p, u)),
483
+ null,
484
+ u
485
+ )
486
+ )
487
+ };
488
+ };
489
+ var readCheckNetwork = (value, path, u) => {
490
+ const f = object(value, path);
491
+ return {
492
+ name: field(f, path, "name", lenient(nullable(string), null, u)),
493
+ kind: field(f, path, "kind", lenient(nullable(string), null, u)),
494
+ participants: field(f, path, "participants", items(string, u))
495
+ };
496
+ };
497
+ var readCheckResult = (value, path, u) => {
498
+ const f = object(value, path);
499
+ version(f, path, "vehicle_sil_check", 1, u);
500
+ return {
501
+ file: field(f, path, "file", soft(nullable(string), null, u)),
502
+ result: field(f, path, "result", lenient(string, "", u)),
503
+ errors: field(f, path, "errors", lenient(integer, 0, u)),
504
+ warnings: field(f, path, "warnings", lenient(integer, 0, u)),
505
+ notes: field(f, path, "notes", lenient(integer, 0, u)),
506
+ stop_at_ms: field(f, path, "stop_at_ms", soft(nullable(number), null, u)),
507
+ participants: field(
508
+ f,
509
+ path,
510
+ "participants",
511
+ items((v, p) => readCheckParticipant(v, p, u), u)
512
+ ),
513
+ networks: field(
514
+ f,
515
+ path,
516
+ "networks",
517
+ items((v, p) => readCheckNetwork(v, p, u), u)
518
+ ),
519
+ findings: field(
520
+ f,
521
+ path,
522
+ "findings",
523
+ items((v, p) => readFinding(v, p, u), u)
524
+ ),
525
+ scenario: field(
526
+ f,
527
+ path,
528
+ "scenario",
529
+ soft(
530
+ nullable((v, p) => readCheckScenario(v, p, u)),
531
+ null,
532
+ u
533
+ )
534
+ )
535
+ };
536
+ };
537
+ var CONTROL_EVENT = "control_link";
538
+ var CONTROL_RESULT_KEY = "control_link";
539
+ var CONTROL_SUMMARY_KEY = "control_link";
540
+ var CONTROL_CHECK_KEY = "control";
541
+ var readControlOffer = (value, path, u) => {
542
+ const f = object(value, path);
543
+ return {
544
+ transport: field(f, path, "transport", lenient(string, "", u)),
545
+ wire_version: field(f, path, "wire_version", soft(nullable(integer), null, u))
546
+ };
547
+ };
548
+ var readControlLink = (value, path, u) => {
549
+ const f = object(value, path);
550
+ return {
551
+ state: field(f, path, "state", string),
552
+ variables: field(f, path, "variables", soft(nullable(integer), null, u)),
553
+ version: field(f, path, "version", soft(nullable(integer), null, u)),
554
+ late_messages: field(f, path, "late_messages", soft(nullable(integer), null, u))
555
+ };
556
+ };
557
+ var readRunParticipant = (value, path, u) => {
558
+ const f = object(value, path);
559
+ return {
560
+ name: field(f, path, "name", string),
561
+ required: field(f, path, "required", lenient(boolean, true, u)),
562
+ enabled: field(f, path, "enabled", lenient(boolean, true, u)),
563
+ manual: field(f, path, "manual", soft(boolean, false, u)),
564
+ ended: field(f, path, "ended", lenient(string, "", u)),
565
+ exit_code: field(f, path, "exit_code", soft(nullable(integer), null, u)),
566
+ signal: field(f, path, "signal", soft(nullable(string), null, u)),
567
+ left_processes: field(f, path, "left_processes", soft(boolean, false, u)),
568
+ control_link: field(
569
+ f,
570
+ path,
571
+ CONTROL_RESULT_KEY,
572
+ soft(
573
+ nullable((v, p) => readControlLink(v, p, u)),
574
+ null,
575
+ u
576
+ )
577
+ )
578
+ };
579
+ };
580
+ var readRunTiming = (value, path, u) => {
581
+ const f = object(value, path);
582
+ const count2 = (key) => field(f, path, key, soft(nullable(number), null, u));
583
+ return {
584
+ speed: field(f, path, "speed", soft(readSpeed, null, u)),
585
+ time_step_ms: count2("time_step_ms"),
586
+ ecu_step_ms: count2("ecu_step_ms"),
587
+ step_delay_ms: count2("step_delay_ms"),
588
+ late_tolerance_ms: count2("late_tolerance_ms"),
589
+ sim_ms: count2("sim_ms"),
590
+ wall_ms: count2("wall_ms"),
591
+ actual_speed: count2("actual_speed"),
592
+ paced_steps: count2("paced_steps"),
593
+ late_steps: count2("late_steps"),
594
+ max_late_ms: count2("max_late_ms"),
595
+ slipped_ms: count2("slipped_ms"),
596
+ late_ms: count2("late_ms"),
597
+ paused_ms: count2("paused_ms")
598
+ };
599
+ };
600
+ var readRunResult = (value, path, u) => {
601
+ const f = object(value, path);
602
+ version(f, path, "vehicle_sil_run", 1, u);
603
+ return {
604
+ file: field(f, path, "file", soft(nullable(string), null, u)),
605
+ result: field(f, path, "result", lenient(string, "", u)),
606
+ errors: field(f, path, "errors", lenient(integer, 0, u)),
607
+ warnings: field(f, path, "warnings", lenient(integer, 0, u)),
608
+ notes: field(f, path, "notes", lenient(integer, 0, u)),
609
+ simulation: field(f, path, "simulation", soft(nullable(string), null, u)),
610
+ interrupted_by: field(f, path, "interrupted_by", soft(nullable(string), null, u)),
611
+ timing: field(
612
+ f,
613
+ path,
614
+ "timing",
615
+ soft(
616
+ nullable((v, p) => readRunTiming(v, p, u)),
617
+ null,
618
+ u
619
+ )
620
+ ),
621
+ participants: field(
622
+ f,
623
+ path,
624
+ "participants",
625
+ items((v, p) => readRunParticipant(v, p, u), u)
626
+ ),
627
+ findings: field(
628
+ f,
629
+ path,
630
+ "findings",
631
+ items((v, p) => readFinding(v, p, u), u)
632
+ ),
633
+ check: field(
634
+ f,
635
+ path,
636
+ "check",
637
+ soft(
638
+ nullable((v, p) => readCheckResult(v, p, u)),
639
+ null,
640
+ u
641
+ )
642
+ ),
643
+ scenario: field(
644
+ f,
645
+ path,
646
+ "scenario",
647
+ soft(
648
+ nullable((v, p) => readScenarioResult(v, p, u)),
649
+ null,
650
+ u
651
+ )
652
+ )
653
+ };
654
+ };
655
+ var PHASES = ["checking", "starting", "waiting", "running", "stopping", "ended"];
656
+ function readTimeFields(f, path, u) {
657
+ const count2 = (key) => field(f, path, key, soft(nullable(number), null, u));
658
+ return {
659
+ sim_ms: field(f, path, "sim_ms", number),
660
+ speed: field(f, path, "speed", soft(readSpeed, null, u)),
661
+ paused: field(f, path, "paused", soft(nullable(boolean), null, u)),
662
+ actual_speed: count2("actual_speed"),
663
+ late_steps: count2("late_steps"),
664
+ max_late_ms: count2("max_late_ms"),
665
+ slipped_ms: count2("slipped_ms"),
666
+ late_ms: count2("late_ms")
667
+ };
668
+ }
669
+ function readCommandFields(f, path, u) {
670
+ return {
671
+ command: field(f, path, "command", nullable(string)),
672
+ source: field(f, path, "source", soft(string, "stdin", u)),
673
+ accepted: field(f, path, "accepted", boolean),
674
+ message: field(f, path, "message", soft(nullable(string), null, u)),
675
+ ms: field(f, path, "ms", soft(nullable(integer), null, u))
676
+ };
677
+ }
678
+ var readLauncherEvent = (value, path, partly = false) => {
679
+ const f = object(value, path);
680
+ const kind = field(f, path, "event", string);
681
+ const u = partly ? new Unreadable(path, `${kind}.`) : void 0;
682
+ const event = readEventFields(
683
+ f,
684
+ path,
685
+ kind,
686
+ {
687
+ seq: field(f, path, "seq", integer),
688
+ t_ms: field(f, path, "t_ms", soft(nullable(number), null, u))
689
+ },
690
+ u
691
+ );
692
+ if (event && u && u.parts.length > 0) event.unreadable = u.parts;
693
+ return event;
694
+ };
695
+ function readEventFields(f, path, kind, base, u) {
696
+ switch (kind) {
697
+ case "hello":
698
+ return {
699
+ ...base,
700
+ event: kind,
701
+ vehicle_sil_events: field(f, path, "vehicle_sil_events", lenient(integer, 0, u)),
702
+ vehicle_sil: field(f, path, "vehicle_sil", lenient(string, "", u)),
703
+ pid: field(f, path, "pid", soft(nullable(integer), null, u)),
704
+ file: field(f, path, "file", soft(nullable(string), null, u)),
705
+ arguments: field(f, path, "arguments", soft(items(string, u), [], u))
706
+ };
707
+ case "phase":
708
+ return { ...base, event: kind, phase: field(f, path, "phase", string) };
709
+ case "check":
710
+ return {
711
+ ...base,
712
+ event: kind,
713
+ check: field(
714
+ f,
715
+ path,
716
+ "check",
717
+ lenient((v, p) => readCheckResult(v, p, u), null, u)
718
+ )
719
+ };
720
+ case "registry":
721
+ return { ...base, event: kind, uri: field(f, path, "uri", soft(nullable(string), null, u)) };
722
+ case "participant":
723
+ return {
724
+ ...base,
725
+ event: kind,
726
+ name: field(f, path, "name", string),
727
+ state: field(f, path, "state", string),
728
+ pid: field(f, path, "pid", soft(nullable(integer), null, u)),
729
+ exit_code: field(f, path, "exit_code", soft(nullable(integer), null, u)),
730
+ signal: field(f, path, "signal", soft(nullable(string), null, u)),
731
+ reason: field(f, path, "reason", soft(nullable(string), null, u)),
732
+ message: field(f, path, "message", soft(nullable(string), null, u)),
733
+ command_line: field(f, path, "command_line", soft(nullable(string), null, u)),
734
+ working_directory: field(f, path, "working_directory", soft(nullable(string), null, u)),
735
+ environment: field(f, path, "environment", soft(nullable(record(string)), null, u))
736
+ };
737
+ case "log_dropped":
738
+ return {
739
+ ...base,
740
+ event: kind,
741
+ count: field(f, path, "count", integer),
742
+ sources: field(f, path, "sources", record(integer))
743
+ };
744
+ case CONTROL_EVENT:
745
+ return {
746
+ ...base,
747
+ event: kind,
748
+ name: field(f, path, "name", string),
749
+ link: readControlLink(f, path, u)
750
+ };
751
+ case "log":
752
+ return {
753
+ ...base,
754
+ event: kind,
755
+ source: field(f, path, "source", string),
756
+ line: field(f, path, "line", string)
757
+ };
758
+ case "finding":
759
+ return { ...base, event: kind, finding: readFinding(f, path, u) };
760
+ case "time":
761
+ return { ...base, event: kind, ...readTimeFields(f, path, u) };
762
+ case "command":
763
+ return { ...base, event: kind, ...readCommandFields(f, path, u) };
764
+ case "scenario_step":
765
+ return { ...base, event: kind, step: readScenarioStepFields(f, path, u) };
766
+ case "result":
767
+ return {
768
+ ...base,
769
+ event: kind,
770
+ result: field(f, path, "result", (v, p) => readRunResult(v, p, u))
771
+ };
772
+ default:
773
+ return null;
774
+ }
775
+ }
776
+ var readServerProblem = (value, path) => {
777
+ const f = object(value, path);
778
+ const problem = {
779
+ code: field(f, path, "code", string),
780
+ message: field(f, path, "message", string)
781
+ };
782
+ const detail = f["detail"];
783
+ if (typeof detail === "object" && detail !== null && "skipped" in detail) {
784
+ const skipped = detail.skipped;
785
+ if (typeof skipped === "number" && Number.isSafeInteger(skipped) && skipped >= 0) {
786
+ problem.skipped = skipped;
787
+ }
788
+ }
789
+ return problem;
790
+ };
791
+ var readSpeed = (value, path) => value === null || value === "max" ? value : number(value, path);
792
+ var readAppInfo = (value) => {
793
+ const path = "app";
794
+ const f = object(value, path);
795
+ version(f, path, "vehicle_sil_gui", PROTOCOL_VERSION);
796
+ const lp = `${path}.launcher`;
797
+ const launcher = field(f, path, "launcher", object);
798
+ const launcherVersion = field(launcher, lp, "version", nullable(object));
799
+ const limits = field(f, path, "limits", object);
800
+ const lim = `${path}.limits`;
801
+ const variables = field(f, path, "variables", optional(object, null));
802
+ return {
803
+ version: field(f, path, "version", string),
804
+ instance: field(f, path, "instance", string),
805
+ root: field(f, path, "root", string),
806
+ initial_file: field(f, path, "initial_file", nullable(string)),
807
+ launcher: {
808
+ path: field(launcher, lp, "path", nullable(string)),
809
+ usable: field(launcher, lp, "usable", boolean),
810
+ problems: field(launcher, lp, "problems", array(readServerProblem)),
811
+ features: launcherVersion ? field(launcherVersion, `${lp}.version`, "features", optional(array(string), [])) : []
812
+ },
813
+ limits: {
814
+ speed_min: field(limits, `${path}.limits`, "speed_min", number),
815
+ speed_max: field(limits, `${path}.limits`, "speed_max", number),
816
+ step_ms_max: field(limits, `${path}.limits`, "step_ms_max", optional(number, 1e12)),
817
+ check_timeout_s: field(limits, `${path}.limits`, "check_timeout_s", optional(number, 120)),
818
+ watch_period_ms_min: field(limits, lim, "watch_period_ms_min", optional(number, 20)),
819
+ watch_period_ms_max: field(limits, lim, "watch_period_ms_max", optional(number, 6e4)),
820
+ write_at_ms_max: field(limits, lim, "write_at_ms_max", optional(number, 1e12)),
821
+ watches: field(limits, lim, "watches", optional(number, 16)),
822
+ watch_variables: field(limits, lim, "watch_variables", optional(number, 2e3)),
823
+ writes_per_request: field(limits, lim, "writes_per_request", optional(number, 256))
824
+ },
825
+ variables: variables ? {
826
+ available: field(variables, `${path}.variables`, "available", boolean),
827
+ reason: field(variables, `${path}.variables`, "reason", nullable(string))
828
+ } : { available: false, reason: null }
829
+ };
830
+ };
831
+ var readConfigList = (value) => {
832
+ const path = "configs";
833
+ const f = object(value, path);
834
+ return {
835
+ files: field(
836
+ f,
837
+ path,
838
+ "files",
839
+ array((item, p) => ({ path: field(object(item, p), p, "path", string) }))
840
+ ),
841
+ truncated: field(f, path, "truncated", boolean)
842
+ };
843
+ };
844
+ var readScenarioList = (value) => {
845
+ const path = "scenarios";
846
+ const f = object(value, path);
847
+ return {
848
+ file: field(f, path, "file", string),
849
+ directory: field(f, path, "directory", string),
850
+ found: field(f, path, "found", boolean),
851
+ scenarios: field(
852
+ f,
853
+ path,
854
+ "scenarios",
855
+ array((item, p) => {
856
+ const g = object(item, p);
857
+ return { path: field(g, p, "path", string), name: field(g, p, "name", string) };
858
+ })
859
+ ),
860
+ truncated: field(f, path, "truncated", boolean)
861
+ };
862
+ };
863
+ var readRecording = (value) => {
864
+ const r = field(object(value, "response"), "response", "recording", nullable(object));
865
+ if (r === null) return null;
866
+ const path = "response.recording";
867
+ return {
868
+ session_id: field(r, path, "session_id", integer),
869
+ file: field(r, path, "file", string),
870
+ state: field(r, path, "state", string),
871
+ available: field(r, path, "available", boolean),
872
+ reason: field(r, path, "reason", nullable(string)),
873
+ writes: field(r, path, "writes", integer),
874
+ omitted: field(r, path, "omitted", integer),
875
+ steps: field(r, path, "steps", integer),
876
+ yaml: field(r, path, "yaml", nullable(string))
877
+ };
878
+ };
879
+ var readCheckResponse = (value) => field(object(value, "response"), "response", "check", readCheckResult);
880
+ var readSummaryParticipant = (value, path, u) => {
881
+ const f = object(value, path);
882
+ return {
883
+ name: field(f, path, "name", string),
884
+ state: field(f, path, "state", soft(nullable(string), null, u)),
885
+ pid: field(f, path, "pid", soft(nullable(integer), null, u)),
886
+ exit_code: field(f, path, "exit_code", soft(nullable(integer), null, u)),
887
+ signal: field(f, path, "signal", soft(nullable(string), null, u)),
888
+ reason: field(f, path, "reason", soft(nullable(string), null, u)),
889
+ message: field(f, path, "message", soft(nullable(string), null, u)),
890
+ omitted_fields: field(f, path, "omitted_fields", soft(items(string, u), [], u)),
891
+ stop_requested: field(f, path, "stop_requested", soft(boolean, false, u)),
892
+ command_line: field(f, path, "command_line", soft(nullable(string), null, u)),
893
+ working_directory: field(f, path, "working_directory", soft(nullable(string), null, u)),
894
+ environment: field(f, path, "environment", soft(nullable(record(string)), null, u)),
895
+ control_link: field(
896
+ f,
897
+ path,
898
+ CONTROL_SUMMARY_KEY,
899
+ soft(
900
+ nullable((v, p) => readControlLink(v, p, u)),
901
+ null,
902
+ u
903
+ )
904
+ )
905
+ };
906
+ };
907
+ var readSummaryLauncher = (value, path) => {
908
+ const f = object(value, path);
909
+ return {
910
+ running: field(f, path, "running", boolean),
911
+ exit_code: field(f, path, "exit_code", nullable(integer)),
912
+ signal: field(f, path, "signal", nullable(integer)),
913
+ silent_s: field(f, path, "silent_s", optional(nullable(integer), null))
914
+ };
915
+ };
916
+ var readLogCounts = (value, path) => {
917
+ const f = object(value, path);
918
+ return { kept: field(f, path, "kept", integer), dropped: field(f, path, "dropped", integer) };
919
+ };
920
+ function record(read2) {
921
+ return (value, path) => Object.fromEntries(
922
+ Object.entries(object(value, path)).map(([key, item]) => [key, read2(item, `${path}.${key}`)])
923
+ );
924
+ }
925
+ var readSummaryScenario = (value, path, u) => {
926
+ const f = object(value, path);
927
+ return {
928
+ file: field(f, path, "file", string),
929
+ name: field(f, path, "name", soft(nullable(string), null, u)),
930
+ step_count: field(f, path, "step_count", soft(nullable(integer), null, u)),
931
+ steps: field(
932
+ f,
933
+ path,
934
+ "steps",
935
+ items((v, p) => readScenarioStep(v, p, u), u)
936
+ ),
937
+ steps_omitted: field(f, path, "steps_omitted", soft(integer, 0, u)),
938
+ status: field(f, path, "status", soft(nullable(string), null, u)),
939
+ over_at_ms: field(f, path, "over_at_ms", soft(nullable(number), null, u))
940
+ };
941
+ };
942
+ var readSessionSummary = (value, path) => {
943
+ const f = object(value, path);
944
+ const u = new Unreadable(path);
945
+ const time = field(f, path, "time", soft(nullable(object), null, u));
946
+ const timePath = `${path}.time`;
947
+ const summary = {
948
+ id: field(f, path, "id", integer),
949
+ state: field(f, path, "state", string),
950
+ launcher: field(f, path, "launcher", readSummaryLauncher),
951
+ stop: field(f, path, "stop", string),
952
+ file: field(f, path, "file", lenient(string, "", u)),
953
+ disable: field(f, path, "disable", items(string, u)),
954
+ manual: field(f, path, "manual", soft(items(string, u), [], u)),
955
+ speed: field(f, path, "speed", lenient(readSpeed, null, u)),
956
+ start_paused: field(f, path, "start_paused", soft(boolean, false, u)),
957
+ phase: field(f, path, "phase", soft(nullable(string), null, u)),
958
+ last_seq: field(f, path, "last_seq", soft(nullable(integer), null, u)),
959
+ last_t_ms: field(f, path, "last_t_ms", soft(nullable(number), null, u)),
960
+ sim_ms: time ? field(time, timePath, "sim_ms", lenient(number, null, u)) : null,
961
+ time_omitted_fields: time ? field(time, timePath, "omitted_fields", soft(items(string, u), [], u)) : [],
962
+ time: time ? lenient((v, p) => readTimeFields(object(v, p), p, u), null, u)(time, timePath) : null,
963
+ last_command: field(
964
+ f,
965
+ path,
966
+ "last_command",
967
+ soft(
968
+ nullable((v, p) => {
969
+ const c = object(v, p);
970
+ return {
971
+ ...readCommandFields(c, p, u),
972
+ seq: field(c, p, "seq", soft(nullable(integer), null, u))
973
+ };
974
+ }),
975
+ null,
976
+ u
977
+ )
978
+ ),
979
+ check: field(
980
+ f,
981
+ path,
982
+ "check",
983
+ soft(
984
+ nullable((v, p) => readCheckResult(v, p, u)),
985
+ null,
986
+ u
987
+ )
988
+ ),
989
+ participants: field(
990
+ f,
991
+ path,
992
+ "participants",
993
+ items((v, p) => readSummaryParticipant(v, p, u), u)
994
+ ),
995
+ findings: field(
996
+ f,
997
+ path,
998
+ "findings",
999
+ items((v, p) => readFinding(v, p, u), u)
1000
+ ),
1001
+ result: field(
1002
+ f,
1003
+ path,
1004
+ "result",
1005
+ soft(
1006
+ nullable((v, p) => readRunResult(v, p, u)),
1007
+ null,
1008
+ u
1009
+ )
1010
+ ),
1011
+ log: field(f, path, "log", soft(partlyRecord(readLogCounts, u), {}, u)),
1012
+ problems: field(f, path, "problems", items(readServerProblem, u)),
1013
+ problems_omitted: field(f, path, "problems_omitted", soft(integer, 0, u)),
1014
+ scenario: field(
1015
+ f,
1016
+ path,
1017
+ "scenario",
1018
+ soft(
1019
+ nullable((v, p) => readSummaryScenario(v, p, u)),
1020
+ null,
1021
+ u
1022
+ )
1023
+ )
1024
+ };
1025
+ return { ...summary, unreadable: u.parts };
1026
+ };
1027
+ function partlyRecord(read2, u) {
1028
+ return (value, path) => {
1029
+ const out = {};
1030
+ for (const [key, item] of Object.entries(object(value, path))) {
1031
+ const read1 = lenient(read2, void 0, u)(item, `${path}.${key}`);
1032
+ if (read1 !== void 0) out[key] = read1;
1033
+ }
1034
+ return out;
1035
+ };
1036
+ }
1037
+ var readSessionResponse = (value) => field(object(value, "response"), "response", "session", nullable(readSessionSummary));
1038
+ var readTimeResponse = (value) => {
1039
+ const path = "response";
1040
+ const f = object(value, path);
1041
+ const command = field(f, path, "command", object);
1042
+ return {
1043
+ session_id: field(f, path, "session_id", integer),
1044
+ command: field(command, `${path}.command`, "command", string)
1045
+ };
1046
+ };
1047
+ var readOperationReport = (value, path) => {
1048
+ const f = object(value, path);
1049
+ return {
1050
+ seq: field(f, path, "seq", integer),
1051
+ state: field(f, path, "state", string),
1052
+ done: field(f, path, "done", boolean),
1053
+ peers: field(
1054
+ f,
1055
+ path,
1056
+ "peers",
1057
+ record((v, p) => {
1058
+ const t = object(v, p);
1059
+ return {
1060
+ state: field(t, p, "state", string),
1061
+ applied_at_ms: field(t, p, "applied_at_ms", optional(nullable(number), null)),
1062
+ late: field(t, p, "late", optional(boolean, false)),
1063
+ reason: field(t, p, "reason", optional(nullable(string), null))
1064
+ };
1065
+ })
1066
+ )
1067
+ };
1068
+ };
1069
+ var readVariableSummary = (value, path) => {
1070
+ const f = object(value, path);
1071
+ return {
1072
+ name: field(f, path, "name", string),
1073
+ type: field(f, path, "type", string),
1074
+ role: field(f, path, "role", optional(string, "output")),
1075
+ writable: field(f, path, "writable", optional(boolean, false)),
1076
+ unit: field(f, path, "unit", optional(string, "")),
1077
+ min: field(f, path, "min", optional(nullable(number), null)),
1078
+ max: field(f, path, "max", optional(nullable(number), null)),
1079
+ step: field(f, path, "step", optional(nullable(number), null)),
1080
+ description: field(f, path, "description", optional(string, "")),
1081
+ enum: field(
1082
+ f,
1083
+ path,
1084
+ "enum",
1085
+ optional(
1086
+ nullable(
1087
+ array((v, p) => {
1088
+ const item = object(v, p);
1089
+ return { name: field(item, p, "name", string), value: field(item, p, "value", number) };
1090
+ })
1091
+ ),
1092
+ null
1093
+ )
1094
+ )
1095
+ };
1096
+ };
1097
+ var readVariablesSummary = (value) => readVariables(value, "variables");
1098
+ var readVariables = (value, path) => {
1099
+ const f = object(value, path);
1100
+ return {
1101
+ state: field(f, path, "state", string),
1102
+ reason: field(f, path, "reason", optional(nullable(string), null)),
1103
+ peers: field(
1104
+ f,
1105
+ path,
1106
+ "peers",
1107
+ optional(
1108
+ array((v, p) => {
1109
+ const peer = object(v, p);
1110
+ return {
1111
+ name: field(peer, p, "name", string),
1112
+ connected: field(peer, p, "connected", optional(boolean, false)),
1113
+ variables: field(peer, p, "variables", optional(array(readVariableSummary), []))
1114
+ };
1115
+ }),
1116
+ []
1117
+ )
1118
+ ),
1119
+ peers_omitted: field(f, path, "peers_omitted", optional(integer, 0)),
1120
+ variables_omitted: field(f, path, "variables_omitted", optional(integer, 0)),
1121
+ operations: field(f, path, "operations", optional(array(readOperationReport), [])),
1122
+ operations_from_seq: field(f, path, "operations_from_seq", optional(integer, null)),
1123
+ operations_open_omitted: field(f, path, "operations_open_omitted", optional(integer, 0))
1124
+ };
1125
+ };
1126
+ var readWriteResponse = (value) => {
1127
+ const f = object(value, "response");
1128
+ return {
1129
+ session_id: field(f, "response", "session_id", integer),
1130
+ operation: field(f, "response", "operation", integer)
1131
+ };
1132
+ };
1133
+ var readDashboardVariable = (value, path) => {
1134
+ const f = object(value, path);
1135
+ return { peer: field(f, path, "peer", string), name: field(f, path, "name", string) };
1136
+ };
1137
+ var readOptions = (value, path) => ({ ...object(value, path) });
1138
+ var readDashboardItem = (value, path) => {
1139
+ const f = object(value, path);
1140
+ const label = () => field(f, path, "label", nullable(string));
1141
+ if (f["variable"] !== void 0) {
1142
+ return {
1143
+ variable: field(f, path, "variable", readDashboardVariable),
1144
+ widget: field(f, path, "widget", nullable(string)),
1145
+ label: label(),
1146
+ options: field(f, path, "options", readOptions)
1147
+ };
1148
+ }
1149
+ if (f["panel"] !== void 0) {
1150
+ return {
1151
+ panel: field(f, path, "panel", string),
1152
+ label: label(),
1153
+ options: field(f, path, "options", readOptions),
1154
+ variables: field(f, path, "variables", array(readDashboardVariable))
1155
+ };
1156
+ }
1157
+ if (f["auto"] !== void 0) return { auto: field(f, path, "auto", string) };
1158
+ return null;
1159
+ };
1160
+ var readDashboardFile = (value, path) => {
1161
+ const f = object(value, path);
1162
+ return {
1163
+ title: field(f, path, "title", nullable(string)),
1164
+ panels: field(
1165
+ f,
1166
+ path,
1167
+ "panels",
1168
+ array((item, p) => {
1169
+ const m = object(item, p);
1170
+ return { module: field(m, p, "module", string), url: field(m, p, "url", string) };
1171
+ })
1172
+ ),
1173
+ sections: field(
1174
+ f,
1175
+ path,
1176
+ "sections",
1177
+ array((item, p) => {
1178
+ const s = object(item, p);
1179
+ return {
1180
+ title: field(s, p, "title", string),
1181
+ collapsed: field(s, p, "collapsed", boolean),
1182
+ items: field(s, p, "items", array(readDashboardItem)).filter(
1183
+ (entry) => entry !== null
1184
+ )
1185
+ };
1186
+ })
1187
+ )
1188
+ };
1189
+ };
1190
+ var readDashboardResponse = (value) => {
1191
+ const path = "response";
1192
+ const f = object(value, path);
1193
+ return {
1194
+ file: field(f, path, "file", string),
1195
+ path: field(f, path, "path", string),
1196
+ found: field(f, path, "found", boolean),
1197
+ errors: field(
1198
+ f,
1199
+ path,
1200
+ "errors",
1201
+ array((item, p) => {
1202
+ const e = object(item, p);
1203
+ return {
1204
+ line: field(e, p, "line", integer),
1205
+ column: field(e, p, "column", integer),
1206
+ at: field(e, p, "at", string),
1207
+ message: field(e, p, "message", string)
1208
+ };
1209
+ })
1210
+ ),
1211
+ dashboard: field(f, path, "dashboard", nullable(readDashboardFile))
1212
+ };
1213
+ };
1214
+ var readReplay = (value, path) => {
1215
+ const f = object(value, path);
1216
+ return { from_seq: field(f, path, "from_seq", nullable(integer)) };
1217
+ };
1218
+ var readServerMessage = (value) => {
1219
+ const path = "message";
1220
+ const f = object(value, path);
1221
+ const type = field(f, path, "type", string);
1222
+ switch (type) {
1223
+ case "hello":
1224
+ version(f, path, "vehicle_sil_gui", PROTOCOL_VERSION);
1225
+ return {
1226
+ type,
1227
+ instance: field(f, path, "instance", string),
1228
+ session: field(f, path, "session", nullable(readSessionSummary)),
1229
+ replay: field(f, path, "replay", nullable(readReplay))
1230
+ };
1231
+ case "event": {
1232
+ const event = field(f, path, "event", (v, p) => readLauncherEvent(v, p, true));
1233
+ return event && { type, session: field(f, path, "session", integer), event };
1234
+ }
1235
+ case "synced":
1236
+ return {
1237
+ type,
1238
+ session: field(f, path, "session", nullable(integer)),
1239
+ last_seq: field(f, path, "last_seq", nullable(integer))
1240
+ };
1241
+ case "session":
1242
+ return { type, session: field(f, path, "session", readSessionSummary) };
1243
+ case "error":
1244
+ return {
1245
+ type,
1246
+ session: field(f, path, "session", nullable(integer)),
1247
+ ...readServerProblem(value, path)
1248
+ };
1249
+ case "dropped":
1250
+ return {
1251
+ type,
1252
+ session: field(f, path, "session", nullable(integer)),
1253
+ reason: field(f, path, "reason", string),
1254
+ log: field(f, path, "log", record(integer)),
1255
+ at_least: field(f, path, "at_least", array(string)),
1256
+ events: field(f, path, "events", integer)
1257
+ };
1258
+ case "resync":
1259
+ return { type, message: field(f, path, "message", optional(string, "")) };
1260
+ case "variables":
1261
+ return {
1262
+ type,
1263
+ session: field(f, path, "session", integer),
1264
+ variables: field(f, path, "variables", readVariables)
1265
+ };
1266
+ case "values":
1267
+ return {
1268
+ type,
1269
+ id: field(f, path, "id", integer),
1270
+ session: field(f, path, "session", integer),
1271
+ sim_ms: field(f, path, "sim_ms", nullable(number)),
1272
+ paused: field(f, path, "paused", boolean),
1273
+ peers: field(
1274
+ f,
1275
+ path,
1276
+ "peers",
1277
+ record((v, p) => {
1278
+ const peer = object(v, p);
1279
+ return {
1280
+ sample_ms: field(peer, p, "sample_ms", number),
1281
+ values: field(
1282
+ peer,
1283
+ p,
1284
+ "values",
1285
+ record((x, xp) => {
1286
+ if (x !== null && typeof x !== "boolean") return number(x, xp);
1287
+ return x;
1288
+ })
1289
+ )
1290
+ };
1291
+ })
1292
+ )
1293
+ };
1294
+ case "operation":
1295
+ return {
1296
+ type,
1297
+ session: field(f, path, "session", integer),
1298
+ ...readOperationReport(value, path)
1299
+ };
1300
+ default:
1301
+ return null;
1302
+ }
1303
+ };
1304
+
1305
+ // ../client/src/http.ts
1306
+ var DEFAULT_TIMEOUT_MS = 3e4;
1307
+ var HttpError = class _HttpError extends Error {
1308
+ constructor(status, statusText, problem, timedOut = false) {
1309
+ super(
1310
+ problem ? problem.message : timedOut ? statusText : `HTTP ${status} ${statusText}`.trim()
1311
+ );
1312
+ this.status = status;
1313
+ this.statusText = statusText;
1314
+ this.problem = problem;
1315
+ this.timedOut = timedOut;
1316
+ this.name = "HttpError";
1317
+ }
1318
+ status;
1319
+ statusText;
1320
+ problem;
1321
+ timedOut;
1322
+ /** Error for a request given up after the timeout. */
1323
+ static noAnswer(method, path, timeoutMs) {
1324
+ return new _HttpError(
1325
+ 0,
1326
+ `no answer from ${method} ${path} within ${timeoutMs / 1e3} s`,
1327
+ null,
1328
+ true
1329
+ );
1330
+ }
1331
+ /**
1332
+ * Builds the error from the answer's body (parsed JSON). problem is null unless the body has the server's error
1333
+ * shape.
1334
+ */
1335
+ static from(status, statusText, body) {
1336
+ let problem = null;
1337
+ if (typeof body === "object" && body !== null && "error" in body) {
1338
+ try {
1339
+ problem = readServerProblem(body.error, "response.error");
1340
+ } catch {
1341
+ problem = null;
1342
+ }
1343
+ }
1344
+ return new _HttpError(status, statusText, problem);
1345
+ }
1346
+ };
1347
+ function errorMessage(error) {
1348
+ return error instanceof Error ? error.message : String(error);
1349
+ }
1350
+ function fetchTransport(options) {
1351
+ const send = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
1352
+ const token = typeof options.token === "function" ? options.token : () => options.token;
1353
+ return (request, done) => {
1354
+ const headers = {};
1355
+ const current = token();
1356
+ if (current) headers["Authorization"] = `Bearer ${current}`;
1357
+ if (request.method === "POST") {
1358
+ headers["Content-Type"] = "application/json";
1359
+ if (options.origin) headers["Origin"] = options.origin;
1360
+ }
1361
+ const url = new URL(request.path, options.baseUrl).href;
1362
+ const timeoutMs = request.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1363
+ const abort = new AbortController();
1364
+ let timedOut = false;
1365
+ const timer = setTimeout(() => {
1366
+ timedOut = true;
1367
+ abort.abort();
1368
+ }, timeoutMs);
1369
+ const init = {
1370
+ method: request.method,
1371
+ headers,
1372
+ redirect: "error",
1373
+ signal: abort.signal
1374
+ };
1375
+ if (request.method === "POST") init.body = JSON.stringify(request.body ?? {});
1376
+ const fail = (error) => done({
1377
+ ok: false,
1378
+ error: timedOut ? HttpError.noAnswer(request.method, request.path, timeoutMs) : new HttpError(0, errorMessage(error), null)
1379
+ });
1380
+ send(url, init).then(async (response) => {
1381
+ const body = await response.json().catch(() => null);
1382
+ clearTimeout(timer);
1383
+ if (timedOut) {
1384
+ fail(null);
1385
+ return;
1386
+ }
1387
+ done(
1388
+ response.ok ? { ok: true, body } : { ok: false, error: HttpError.from(response.status, response.statusText, body) }
1389
+ );
1390
+ }, fail).finally(() => clearTimeout(timer));
1391
+ };
1392
+ }
1393
+
1394
+ // ../client/src/run.ts
1395
+ function answerMissing(path, error) {
1396
+ if (!error.timedOut) return null;
1397
+ return path === "api/run" ? `${error.message}: the server may still start the run (it checks the file again when it has changed); whether it did shows in the session over the WebSocket` : `${error.message}: the server may have done it; the session over the WebSocket shows what happened`;
1398
+ }
1399
+ var RunControl = class {
1400
+ constructor(feed, transport, onError = rethrowLater, startTimeoutMs = () => 0) {
1401
+ this.feed = feed;
1402
+ this.transport = transport;
1403
+ this.startTimeoutMs = startTimeoutMs;
1404
+ this.startSending = new Writable(false, Object.is, onError);
1405
+ this.stopSending = new Writable(null, Object.is, onError);
1406
+ this.stopAskedWhileStarting = new Writable(false, Object.is, onError);
1407
+ this.failure = new Writable(null, Object.is, onError);
1408
+ this.starting = this.startSending.readonly();
1409
+ this.stopping = this.stopSending.readonly();
1410
+ this.stopWhileStarting = this.stopAskedWhileStarting.readonly();
1411
+ this.error = derived(
1412
+ [this.failure, feed.session],
1413
+ () => {
1414
+ const failure = this.failure.get();
1415
+ const session = feed.session.get();
1416
+ if (!failure) return null;
1417
+ const same = failure.session === (session?.id ?? null) && failure.running === (session?.launcher.running ?? false);
1418
+ return same ? failure.message : null;
1419
+ },
1420
+ Object.is,
1421
+ onError
1422
+ );
1423
+ }
1424
+ feed;
1425
+ transport;
1426
+ startTimeoutMs;
1427
+ startSending;
1428
+ stopSending;
1429
+ stopAskedWhileStarting;
1430
+ failure;
1431
+ starting;
1432
+ stopping;
1433
+ stopWhileStarting;
1434
+ error;
1435
+ /** Starts a run. */
1436
+ start(request) {
1437
+ this.startSending.set(true);
1438
+ this.stopAskedWhileStarting.set(false);
1439
+ return this.send("api/run", request, this.startTimeoutMs() || void 0, () => {
1440
+ this.startSending.set(false);
1441
+ const asked = this.stopAskedWhileStarting.get();
1442
+ this.stopAskedWhileStarting.set(false);
1443
+ const session = this.feed.session.get();
1444
+ if (asked && session?.launcher.running && session.stopRequests === 0) {
1445
+ this.stop().catch(() => void 0);
1446
+ }
1447
+ });
1448
+ }
1449
+ /** Stops in order (waits for the participants to end). Asking again never turns it into a stop without waiting. */
1450
+ stop() {
1451
+ if (this.startSending.get()) this.stopAskedWhileStarting.set(true);
1452
+ this.stopSending.set("stop");
1453
+ return this.send("api/stop", { force: false }, void 0, () => this.stopSending.set(null));
1454
+ }
1455
+ /** Stops without waiting (kills the participants). */
1456
+ forceStop() {
1457
+ this.stopSending.set("force");
1458
+ return this.send("api/stop", { force: true }, void 0, () => this.stopSending.set(null));
1459
+ }
1460
+ /**
1461
+ * Sends and applies the summary in the answer. done is called after the answer (failures too), before the Promise
1462
+ * settles.
1463
+ */
1464
+ send(path, body, timeoutMs, done) {
1465
+ this.failure.set(null);
1466
+ return new Promise((resolve, reject) => {
1467
+ this.transport({ method: "POST", path, body, timeoutMs }, (outcome) => {
1468
+ if (!outcome.ok) {
1469
+ const session = this.feed.session.get();
1470
+ this.failure.set({
1471
+ message: answerMissing(path, outcome.error) ?? errorMessage(outcome.error),
1472
+ session: session?.id ?? null,
1473
+ running: session?.launcher.running ?? false
1474
+ });
1475
+ done();
1476
+ reject(outcome.error);
1477
+ return;
1478
+ }
1479
+ let summary = null;
1480
+ try {
1481
+ summary = readSessionResponse(outcome.body);
1482
+ this.feed.adopt(summary);
1483
+ } catch (error) {
1484
+ this.feed.report(
1485
+ error instanceof ProtocolError ? `unreadable answer: ${error.message}` : String(error)
1486
+ );
1487
+ }
1488
+ done();
1489
+ resolve(summary);
1490
+ });
1491
+ });
1492
+ }
1493
+ };
1494
+
1495
+ // ../client/src/session-state.ts
1496
+ var MAX_LOG_LINES_PER_SOURCE = 2e3;
1497
+ var MAX_LOG_LINES = 2e4;
1498
+ var MAX_PROBLEMS = 200;
1499
+ var MAX_FINDINGS = 500;
1500
+ function timeView(time) {
1501
+ return {
1502
+ simMs: time.sim_ms,
1503
+ speed: time.speed,
1504
+ paused: time.paused,
1505
+ actualSpeed: time.actual_speed,
1506
+ lateSteps: time.late_steps,
1507
+ maxLateMs: time.max_late_ms,
1508
+ slippedMs: time.slipped_ms,
1509
+ lateMs: time.late_ms
1510
+ };
1511
+ }
1512
+ function commandView(command, seq) {
1513
+ return {
1514
+ name: command.command,
1515
+ accepted: command.accepted,
1516
+ message: command.message,
1517
+ ms: command.ms,
1518
+ seq
1519
+ };
1520
+ }
1521
+ function scenarioView(summary) {
1522
+ return {
1523
+ file: summary.file,
1524
+ name: summary.name,
1525
+ stepCount: summary.step_count,
1526
+ steps: summary.steps,
1527
+ stepsOmitted: summary.steps_omitted,
1528
+ status: summary.status,
1529
+ overAtMs: summary.over_at_ms
1530
+ };
1531
+ }
1532
+ function withStep(steps, step) {
1533
+ const i = steps.findIndex((s) => s.index >= step.index);
1534
+ if (i < 0) return [...steps, step];
1535
+ if (steps[i].index === step.index) return steps.map((s, j) => j === i ? step : s);
1536
+ return [...steps.slice(0, i), step, ...steps.slice(i)];
1537
+ }
1538
+ function runOutcome(session) {
1539
+ if (session.launcher.running) {
1540
+ if (session.result) return "finishing";
1541
+ if (session.stopRequests >= 2) return "forcing";
1542
+ return session.stopRequests >= 1 ? "stopping" : "running";
1543
+ }
1544
+ return session.result ? "ended" : "crashed";
1545
+ }
1546
+ function sessionFromSummary(summary) {
1547
+ const blank = {
1548
+ id: summary.id,
1549
+ lastSeq: -1,
1550
+ file: summary.file,
1551
+ disable: summary.disable,
1552
+ manual: summary.manual,
1553
+ speed: summary.speed,
1554
+ startPaused: summary.start_paused,
1555
+ phase: null,
1556
+ phaseRank: -1,
1557
+ check: null,
1558
+ participants: [],
1559
+ logs: [],
1560
+ logSources: {},
1561
+ findings: [],
1562
+ elapsedMs: 0,
1563
+ simMs: null,
1564
+ timeOmittedFields: [],
1565
+ time: null,
1566
+ stopRequests: 0,
1567
+ lastCommand: null,
1568
+ result: null,
1569
+ launcher: launcherOf(summary),
1570
+ problems: [],
1571
+ problemsOmitted: 0,
1572
+ unreadable: [],
1573
+ staleEvents: 0,
1574
+ droppedMarks: 0,
1575
+ scenario: null
1576
+ };
1577
+ return applySummary(blank, summary, true);
1578
+ }
1579
+ function addDropped(session, dropped) {
1580
+ const counts = Object.entries(dropped.log).filter(([, count2]) => count2 > 0);
1581
+ if (counts.length === 0) return session;
1582
+ const mark = session.droppedMarks + 1;
1583
+ const gaps = counts.map(([source, count2]) => ({
1584
+ seq: session.lastSeq + 0.5,
1585
+ key: `dropped ${mark} ${source}`,
1586
+ source,
1587
+ line: "",
1588
+ gap: { count: count2, atLeast: dropped.at_least.includes(source) }
1589
+ }));
1590
+ const next = { ...appendLogs(session, gaps), droppedMarks: mark };
1591
+ const sources = { ...next.logSources };
1592
+ for (const [source, count2] of counts) {
1593
+ sources[source] = { ...sources[source], dropped: sources[source].dropped + count2 };
1594
+ }
1595
+ return { ...next, logSources: sources };
1596
+ }
1597
+ var STOP_REQUESTS = { none: 0, requested: 1, forced: 2 };
1598
+ function stopRequestsOf(stop) {
1599
+ return STOP_REQUESTS[stop] ?? 1;
1600
+ }
1601
+ function launcherOf(summary) {
1602
+ return {
1603
+ running: summary.launcher.running,
1604
+ exitCode: summary.launcher.exit_code,
1605
+ signal: summary.launcher.signal,
1606
+ silentSeconds: summary.launcher.silent_s
1607
+ };
1608
+ }
1609
+ function applySummary(session, summary, force = false, controlOnly = false) {
1610
+ const newer = force || (summary.last_seq ?? -1) > session.lastSeq;
1611
+ const launcher = !force && !session.launcher.running && summary.launcher.running ? session.launcher : launcherOf(summary);
1612
+ const notLess = summary.problems.length + summary.problems_omitted >= session.problems.length + session.problemsOmitted;
1613
+ const next = {
1614
+ ...session,
1615
+ launcher,
1616
+ stopRequests: Math.max(session.stopRequests, stopRequestsOf(summary.stop)),
1617
+ logSources: withSources(session.logSources, Object.keys(summary.log)),
1618
+ ...force || notLess ? { problems: summary.problems, problemsOmitted: summary.problems_omitted } : {}
1619
+ };
1620
+ if (!newer || !force && controlOnly) {
1621
+ return next;
1622
+ }
1623
+ const phase = summary.phase ?? next.phase;
1624
+ const rank = phaseIndex(phase);
1625
+ const check = summary.check ?? next.check ?? summary.result?.check ?? null;
1626
+ const result = summary.result ?? next.result;
1627
+ const known = new Map(session.participants.map((p) => [p.name, p]));
1628
+ const participants = summary.participants.map((p) => ({
1629
+ name: p.name,
1630
+ state: p.state,
1631
+ required: null,
1632
+ pid: p.pid,
1633
+ exitCode: p.exit_code,
1634
+ signal: p.signal,
1635
+ failure: p.reason,
1636
+ message: p.message,
1637
+ // A stop the launcher asked for is kept even in summaries of later states (ended and so on)
1638
+ stopRequested: p.stop_requested || p.state === "stop_requested" || !!known.get(p.name)?.stopRequested,
1639
+ omittedFields: p.omitted_fields,
1640
+ controlLink: p.control_link ?? known.get(p.name)?.controlLink ?? null,
1641
+ manual: p.state === "manual" || p.command_line !== null || !!known.get(p.name)?.manual,
1642
+ commandLine: p.command_line,
1643
+ workingDirectory: p.working_directory,
1644
+ environment: p.environment ?? {}
1645
+ }));
1646
+ return {
1647
+ ...next,
1648
+ unreadable: force ? summary.unreadable : union(next.unreadable, summary.unreadable),
1649
+ phase,
1650
+ phaseRank: rank >= 0 ? rank : next.phaseRank,
1651
+ elapsedMs: Math.max(next.elapsedMs, summary.last_t_ms ?? 0),
1652
+ simMs: summary.sim_ms ?? next.simMs,
1653
+ timeOmittedFields: summary.sim_ms === null ? next.timeOmittedFields : summary.time_omitted_fields,
1654
+ time: summary.time ? timeView(summary.time) : next.time,
1655
+ lastCommand: summary.last_command ? commandView(summary.last_command, summary.last_command.seq ?? -1) : next.lastCommand,
1656
+ findings: summary.findings,
1657
+ result,
1658
+ check,
1659
+ scenario: summary.scenario ? scenarioView(summary.scenario) : next.scenario,
1660
+ // Whether a participant is required or left out is in the check result (as is the order, that of the configuration
1661
+ // file). If there is a result, how it ended (stopped or not) comes from the result too
1662
+ participants: withResult(check ? mergeCheck(participants, check) : participants, result)
1663
+ };
1664
+ }
1665
+ function union(a, b) {
1666
+ return b.every((name) => a.includes(name)) ? a : [.../* @__PURE__ */ new Set([...a, ...b])];
1667
+ }
1668
+ function withSources(sources, names) {
1669
+ const missing = names.filter((name) => !(name in sources));
1670
+ if (missing.length === 0) return sources;
1671
+ const next = { ...sources };
1672
+ for (const name of missing) next[name] = { lines: 0, dropped: 0 };
1673
+ return next;
1674
+ }
1675
+ function addProblem(session, problem) {
1676
+ if (session.problems.length >= MAX_PROBLEMS) {
1677
+ return { ...session, problemsOmitted: session.problemsOmitted + 1 };
1678
+ }
1679
+ return { ...session, problems: [...session.problems, problem] };
1680
+ }
1681
+ function phaseIndex(phase) {
1682
+ return phase === null ? -1 : PHASES.indexOf(phase);
1683
+ }
1684
+ function applyEvents(session, events, countStale = false) {
1685
+ let next = session;
1686
+ const logs = [];
1687
+ let stale = 0;
1688
+ for (const event of events) {
1689
+ if (event.seq > next.lastSeq) {
1690
+ next = applyOne(next, event, logs);
1691
+ if (event.unreadable)
1692
+ next = { ...next, unreadable: union(next.unreadable, event.unreadable) };
1693
+ } else {
1694
+ stale++;
1695
+ }
1696
+ }
1697
+ if (countStale && stale > 0) next = { ...next, staleEvents: next.staleEvents + stale };
1698
+ if (logs.length === 0) return next;
1699
+ next = appendLogs(next, logs);
1700
+ const gaps = logs.filter((line) => line.gap?.launcher);
1701
+ if (gaps.length === 0) return next;
1702
+ const sources = { ...next.logSources };
1703
+ for (const gap of gaps) {
1704
+ const counts = sources[gap.source] ?? { lines: 0, dropped: 0 };
1705
+ sources[gap.source] = { ...counts, dropped: counts.dropped + (gap.gap?.count ?? 0) };
1706
+ }
1707
+ return { ...next, logSources: sources };
1708
+ }
1709
+ function appendLogs(session, added) {
1710
+ const sources = {};
1711
+ for (const [source, counts] of Object.entries(session.logSources))
1712
+ sources[source] = { ...counts };
1713
+ for (const line of added) {
1714
+ const counts = sources[line.source] ??= { lines: 0, dropped: 0 };
1715
+ if (!line.gap) counts.lines++;
1716
+ }
1717
+ const drop = /* @__PURE__ */ new Map();
1718
+ const take = (source, count2) => {
1719
+ sources[source].lines -= count2;
1720
+ sources[source].dropped += count2;
1721
+ drop.set(source, (drop.get(source) ?? 0) + count2);
1722
+ };
1723
+ let total = 0;
1724
+ for (const [source, counts] of Object.entries(sources)) {
1725
+ if (counts.lines > MAX_LOG_LINES_PER_SOURCE)
1726
+ take(source, counts.lines - MAX_LOG_LINES_PER_SOURCE);
1727
+ total += counts.lines;
1728
+ }
1729
+ while (total > MAX_LOG_LINES) {
1730
+ const [largest, second] = Object.entries(sources).sort(([, a], [, b]) => b.lines - a.lines);
1731
+ const count2 = Math.max(
1732
+ 1,
1733
+ Math.min(total - MAX_LOG_LINES, largest[1].lines - (second?.[1].lines ?? 0))
1734
+ );
1735
+ take(largest[0], count2);
1736
+ total -= count2;
1737
+ }
1738
+ const all = [...session.logs, ...added];
1739
+ if (drop.size === 0) return { ...session, logs: all, logSources: sources };
1740
+ const kept = all.filter((line) => {
1741
+ const left = drop.get(line.source);
1742
+ if (left === void 0 || left === 0) return true;
1743
+ if (!line.gap) drop.set(line.source, left - 1);
1744
+ return false;
1745
+ });
1746
+ return { ...session, logs: kept, logSources: sources };
1747
+ }
1748
+ function applyOne(session, event, logs) {
1749
+ const next = {
1750
+ ...session,
1751
+ lastSeq: event.seq,
1752
+ elapsedMs: Math.max(session.elapsedMs, event.t_ms ?? 0)
1753
+ };
1754
+ switch (event.event) {
1755
+ case "phase": {
1756
+ const index = phaseIndex(event.phase);
1757
+ if (index < 0) return { ...next, phase: event.phase };
1758
+ return index >= next.phaseRank ? { ...next, phase: event.phase, phaseRank: index } : next;
1759
+ }
1760
+ case "check": {
1761
+ if (!event.check) return next;
1762
+ const found = event.check.scenario;
1763
+ return {
1764
+ ...next,
1765
+ check: event.check,
1766
+ participants: mergeCheck(next.participants, event.check),
1767
+ scenario: next.scenario && found ? { ...next.scenario, name: found.name, stepCount: found.steps } : next.scenario
1768
+ };
1769
+ }
1770
+ case "scenario_step":
1771
+ return next.scenario ? {
1772
+ ...next,
1773
+ scenario: { ...next.scenario, steps: withStep(next.scenario.steps, event.step) }
1774
+ } : next;
1775
+ case "participant":
1776
+ return { ...next, participants: updateParticipant(next.participants, event) };
1777
+ case CONTROL_EVENT: {
1778
+ const known = next.participants.find((p) => p.name === event.name);
1779
+ const updated = { ...known ?? blankParticipant(event.name), controlLink: event.link };
1780
+ return {
1781
+ ...next,
1782
+ participants: known ? next.participants.map((p) => p === known ? updated : p) : [...next.participants, updated]
1783
+ };
1784
+ }
1785
+ case "log":
1786
+ logs.push({ seq: event.seq, key: String(event.seq), source: event.source, line: event.line });
1787
+ return next;
1788
+ case "log_dropped":
1789
+ for (const [source, count2] of Object.entries(event.sources)) {
1790
+ if (count2 > 0) {
1791
+ logs.push({
1792
+ seq: event.seq,
1793
+ key: `${event.seq} ${source}`,
1794
+ source,
1795
+ line: "",
1796
+ gap: { count: count2, atLeast: false, launcher: true }
1797
+ });
1798
+ }
1799
+ }
1800
+ return next;
1801
+ case "finding":
1802
+ return next.findings.length >= MAX_FINDINGS ? next : { ...next, findings: [...next.findings, event.finding] };
1803
+ case "time":
1804
+ return { ...next, simMs: event.sim_ms, timeOmittedFields: [], time: timeView(event) };
1805
+ case "command":
1806
+ return { ...next, lastCommand: commandView(event, event.seq) };
1807
+ case "result":
1808
+ return {
1809
+ ...next,
1810
+ result: event.result,
1811
+ phase: "ended",
1812
+ phaseRank: phaseIndex("ended"),
1813
+ check: next.check ?? event.result.check,
1814
+ participants: mergeResult(next.participants, event.result),
1815
+ scenario: next.scenario && event.result.scenario ? {
1816
+ ...next.scenario,
1817
+ name: event.result.scenario.name,
1818
+ stepCount: next.scenario.stepCount ?? event.result.scenario.steps.length,
1819
+ steps: event.result.scenario.steps,
1820
+ status: event.result.scenario.status,
1821
+ overAtMs: event.result.scenario.over_at_ms
1822
+ } : next.scenario
1823
+ };
1824
+ default:
1825
+ return next;
1826
+ }
1827
+ }
1828
+ function mergeCheck(current, check) {
1829
+ const byName = new Map(current.map((p) => [p.name, p]));
1830
+ const ordered = [];
1831
+ for (const p of check.participants) {
1832
+ if (p.name === null) continue;
1833
+ const known = byName.get(p.name);
1834
+ byName.delete(p.name);
1835
+ ordered.push({
1836
+ ...known ?? blankParticipant(p.name),
1837
+ required: p.required,
1838
+ state: known?.state ?? (p.enabled === false ? "disabled" : null),
1839
+ manual: p.manual || !!known?.manual
1840
+ });
1841
+ }
1842
+ return [...ordered, ...byName.values()];
1843
+ }
1844
+ function updateParticipant(current, event) {
1845
+ const known = current.find((p) => p.name === event.name);
1846
+ const updated = {
1847
+ ...known ?? blankParticipant(event.name),
1848
+ state: event.state,
1849
+ // Events arrive whole (only the summary leaves fields out)
1850
+ omittedFields: []
1851
+ };
1852
+ if (event.pid !== null) updated.pid = event.pid;
1853
+ if (event.state === "failed") updated.failure = event.reason ?? "";
1854
+ if (event.state === "stop_requested") updated.stopRequested = true;
1855
+ if (event.message) updated.message = event.message;
1856
+ if (event.state === "manual") updated.manual = true;
1857
+ if (typeof event.command_line === "string") updated.commandLine = event.command_line;
1858
+ if (typeof event.working_directory === "string")
1859
+ updated.workingDirectory = event.working_directory;
1860
+ if (event.state === "manual") updated.environment = event.environment ?? {};
1861
+ if (event.state === "ended" || event.state === "killed") {
1862
+ updated.exitCode = event.exit_code;
1863
+ updated.signal = event.signal;
1864
+ }
1865
+ return known ? current.map((p) => p === known ? updated : p) : [...current, updated];
1866
+ }
1867
+ function withResult(participants, result) {
1868
+ return result ? mergeResult(participants, result) : participants;
1869
+ }
1870
+ function mergeResult(current, result) {
1871
+ const merged = [...current];
1872
+ for (const p of result.participants) {
1873
+ const i = merged.findIndex((known) => known.name === p.name);
1874
+ const base = i >= 0 ? merged[i] : blankParticipant(p.name);
1875
+ const state = !p.enabled ? "disabled" : p.ended === "killed" ? "killed" : p.ended === "not_started" ? base.state ?? "not_started" : "ended";
1876
+ const view = {
1877
+ ...base,
1878
+ required: p.required,
1879
+ state,
1880
+ exitCode: p.exit_code,
1881
+ signal: p.signal,
1882
+ stopRequested: base.stopRequested || p.ended === "stopped",
1883
+ // Keep what the events told about the connection (number of variables and so on); without it, only the result's
1884
+ // state. The result is newer (it has the count of messages that arrived late). What the result lacks comes from
1885
+ // the events
1886
+ controlLink: p.control_link ?? base.controlLink,
1887
+ manual: base.manual || p.manual
1888
+ };
1889
+ if (i >= 0) merged[i] = view;
1890
+ else merged.push(view);
1891
+ }
1892
+ return merged;
1893
+ }
1894
+ function blankParticipant(name) {
1895
+ return {
1896
+ name,
1897
+ state: null,
1898
+ required: null,
1899
+ pid: null,
1900
+ exitCode: null,
1901
+ signal: null,
1902
+ failure: null,
1903
+ message: null,
1904
+ stopRequested: false,
1905
+ omittedFields: [],
1906
+ controlLink: null,
1907
+ manual: false,
1908
+ commandLine: null,
1909
+ workingDirectory: null,
1910
+ environment: {}
1911
+ };
1912
+ }
1913
+
1914
+ // ../client/src/session.ts
1915
+ var MAX_NOTICES = 20;
1916
+ var STALE_EVENTS_NOTICE = "events came with a seq that is not after the last one, and were not shown (the launcher wrote them out of order, or the server sent them again)";
1917
+ var SessionFeed = class {
1918
+ constructor(connection, onError = rethrowLater) {
1919
+ this.connection = connection;
1920
+ this.onError = onError;
1921
+ this.current = new Writable(null, Object.is, onError);
1922
+ this.synced = new Writable(false, Object.is, onError);
1923
+ this.receivedAt = new Writable(0, Object.is, onError);
1924
+ this.noticeList = new Writable([], Object.is, onError);
1925
+ this.rejectedValue = new Writable(false, Object.is, onError);
1926
+ this.incompatibleValue = new Writable(null, Object.is, onError);
1927
+ this.session = this.current.readonly();
1928
+ this.lastEventAt = this.receivedAt.readonly();
1929
+ this.notices = this.noticeList.readonly();
1930
+ this.rejected = this.rejectedValue.readonly();
1931
+ this.incompatible = this.incompatibleValue.readonly();
1932
+ this.ready = derived(
1933
+ [connection.state, this.synced],
1934
+ () => connection.state.get() === "open" && this.synced.get(),
1935
+ Object.is,
1936
+ onError
1937
+ );
1938
+ connection.onBatch((batch) => this.receive(batch));
1939
+ connection.onUnreadable(
1940
+ (text2) => this.notify(`unreadable message: not JSON (connecting again): ${text2.slice(0, 80)}`)
1941
+ );
1942
+ }
1943
+ connection;
1944
+ onError;
1945
+ current;
1946
+ synced;
1947
+ receivedAt;
1948
+ noticeList;
1949
+ rejectedValue;
1950
+ incompatibleValue;
1951
+ messageListeners = /* @__PURE__ */ new Set();
1952
+ noticeId = 0;
1953
+ stoppedFlag = false;
1954
+ session;
1955
+ ready;
1956
+ lastEventAt;
1957
+ notices;
1958
+ rejected;
1959
+ incompatible;
1960
+ /** Refused, or the versions differ: never connect again (set before the readable values and before disconnecting). */
1961
+ get stopped() {
1962
+ return this.stoppedFlag;
1963
+ }
1964
+ /**
1965
+ * Fields to add to the authentication message: where in the session it holds the server should resend from. Called
1966
+ * on every connect (after the call, the copy is not in sync until hello and the resent events have arrived). Used
1967
+ * only inside the library.
1968
+ */
1969
+ resumeFields() {
1970
+ this.synced.set(false);
1971
+ const session = this.current.get();
1972
+ return session ? { session: session.id, from_seq: session.lastSeq + 1 } : {};
1973
+ }
1974
+ onMessages(listener) {
1975
+ this.messageListeners.add(listener);
1976
+ return () => {
1977
+ this.messageListeners.delete(listener);
1978
+ };
1979
+ }
1980
+ /**
1981
+ * Applies the summary in an HTTP answer without waiting for the notification (the answers to start, stop and
1982
+ * fetchSession(); used inside the library). While the WebSocket is connected, takes only the launcher and the stop
1983
+ * request for the same run (the rest arrives in notifications). A summary of an earlier run never brings back an old
1984
+ * run over a new one.
1985
+ */
1986
+ adopt(summary) {
1987
+ if (!summary) return;
1988
+ const session = this.current.get();
1989
+ if (session && summary.id < session.id) return;
1990
+ const live = this.connection.state.get() === "open";
1991
+ this.current.set(
1992
+ session?.id === summary.id ? applySummary(session, summary, false, live) : sessionFromSummary(summary)
1993
+ );
1994
+ }
1995
+ report(message, count2 = 1) {
1996
+ this.notify(message, count2);
1997
+ }
1998
+ dismissNotice(id) {
1999
+ this.noticeList.update((list) => list.filter((notice) => notice.id !== id));
2000
+ }
2001
+ /** Reads and applies a batch from the connection. */
2002
+ receive(raw) {
2003
+ const batch = [];
2004
+ let stop = null;
2005
+ let incompatible = null;
2006
+ for (const value of raw) {
2007
+ let message;
2008
+ try {
2009
+ message = readServerMessage(value);
2010
+ } catch (error) {
2011
+ this.notify(
2012
+ error instanceof ProtocolError ? `unreadable message: ${error.message}` : String(error)
2013
+ );
2014
+ const type = value?.type;
2015
+ if (type === "hello" && error instanceof ProtocolError && error.path === "message.vehicle_sil_gui") {
2016
+ const version2 = JSON.stringify(value.vehicle_sil_gui);
2017
+ incompatible = `the server speaks version ${version2} of the GUI protocol (vehicle_sil_gui) and this client reads version ${PROTOCOL_VERSION}: use a client made for the server's version`;
2018
+ stop = "incompatible";
2019
+ break;
2020
+ }
2021
+ if (type === "hello" || type === "session") {
2022
+ stop = "lost";
2023
+ break;
2024
+ }
2025
+ continue;
2026
+ }
2027
+ if (message === null) continue;
2028
+ batch.push(message);
2029
+ if (message.type === "error" && message.code === "unauthorized") {
2030
+ stop = "unauthorized";
2031
+ break;
2032
+ }
2033
+ }
2034
+ if (stop === "unauthorized" || stop === "incompatible") {
2035
+ this.stoppedFlag = true;
2036
+ this.connection.close();
2037
+ }
2038
+ if (stop === "lost") this.connection.restart();
2039
+ this.apply(batch);
2040
+ if (stop === "lost" || stop === "incompatible") this.synced.set(false);
2041
+ if (stop === "unauthorized") this.rejectedValue.set(true);
2042
+ if (incompatible !== null) this.incompatibleValue.set(incompatible);
2043
+ }
2044
+ apply(batch) {
2045
+ if (batch.length === 0) return;
2046
+ const before = this.current.get();
2047
+ let session = before;
2048
+ let events = [];
2049
+ let applied = false;
2050
+ let synced = this.synced.get();
2051
+ let replaying = !synced;
2052
+ const flush = () => {
2053
+ if (session && events.length > 0) {
2054
+ session = applyEvents(session, events, !replaying);
2055
+ applied = true;
2056
+ }
2057
+ events = [];
2058
+ };
2059
+ for (const message of batch) {
2060
+ if (message.type !== "event") flush();
2061
+ switch (message.type) {
2062
+ case "hello": {
2063
+ synced = false;
2064
+ replaying = true;
2065
+ const { session: summary, replay } = message;
2066
+ const resumed = summary && session?.id === summary.id && replay?.from_seq != null;
2067
+ session = !summary ? null : resumed && session ? applySummary(session, summary, true) : sessionFromSummary(summary);
2068
+ break;
2069
+ }
2070
+ case "dropped": {
2071
+ if (session && message.session === session.id) session = addDropped(session, message);
2072
+ break;
2073
+ }
2074
+ case "synced":
2075
+ synced = true;
2076
+ replaying = false;
2077
+ break;
2078
+ case "session":
2079
+ session = session?.id === message.session.id ? applySummary(session, message.session, true) : sessionFromSummary(message.session);
2080
+ break;
2081
+ case "event":
2082
+ if (session?.id === message.session) events.push(message.event);
2083
+ break;
2084
+ case "error":
2085
+ if (message.code === "unauthorized") {
2086
+ } else if (session && message.session === session.id) {
2087
+ const { code, message: text2, skipped } = message;
2088
+ session = addProblem(
2089
+ session,
2090
+ skipped === void 0 ? { code, message: text2 } : { code, message: text2, skipped }
2091
+ );
2092
+ } else {
2093
+ this.notify(message.message);
2094
+ }
2095
+ break;
2096
+ case "resync":
2097
+ synced = false;
2098
+ replaying = true;
2099
+ break;
2100
+ }
2101
+ }
2102
+ flush();
2103
+ const stale = (session?.staleEvents ?? 0) - (before?.id === session?.id ? before?.staleEvents ?? 0 : 0);
2104
+ this.current.set(session);
2105
+ this.synced.set(synced);
2106
+ if (applied) this.receivedAt.set(Date.now());
2107
+ if (stale > 0) this.notify(STALE_EVENTS_NOTICE, stale);
2108
+ callEach(this.messageListeners, [batch], this.onError);
2109
+ }
2110
+ notify(message, count2 = 1) {
2111
+ this.noticeList.update((list) => {
2112
+ const same = list.find((notice) => notice.message === message);
2113
+ if (same) {
2114
+ return [...list.filter((n) => n !== same), { ...same, count: same.count + count2 }];
2115
+ }
2116
+ return [...list, { id: ++this.noticeId, message, count: count2 }].slice(-MAX_NOTICES);
2117
+ });
2118
+ }
2119
+ };
2120
+
2121
+ // ../client/src/time.ts
2122
+ var FEATURE_SPEED = "speed";
2123
+ var FEATURE_START_PAUSED = "start-paused";
2124
+ var FEATURE_TIME_COMMANDS = "time-commands";
2125
+ var ANSWER_TIMEOUT_MS = 5e3;
2126
+ var TimeControl = class {
2127
+ constructor(session, ready, app, transport, answerTimeoutMs = ANSWER_TIMEOUT_MS, onError = rethrowLater, variables = null) {
2128
+ this.session = session;
2129
+ this.transport = transport;
2130
+ this.answerTimeoutMs = answerTimeoutMs;
2131
+ this.variables = variables;
2132
+ this.inFlight = new Writable(0, Object.is, onError);
2133
+ this.pending = new Writable(null, Object.is, onError);
2134
+ this.failureValue = new Writable(null, Object.is, onError);
2135
+ this.state = derived(
2136
+ [
2137
+ session,
2138
+ ready,
2139
+ app,
2140
+ this.inFlight,
2141
+ this.pending,
2142
+ this.failureValue,
2143
+ ...variables ? [variables] : []
2144
+ ],
2145
+ () => this.compute(session.get(), ready.get(), app.get()),
2146
+ shallowEqual,
2147
+ onError
2148
+ );
2149
+ }
2150
+ session;
2151
+ transport;
2152
+ answerTimeoutMs;
2153
+ variables;
2154
+ inFlight;
2155
+ pending;
2156
+ failureValue;
2157
+ answerTimer;
2158
+ lastLateness = null;
2159
+ /** Time state and the commands that may be used now. */
2160
+ state;
2161
+ pause() {
2162
+ return this.send({ command: "pause" });
2163
+ }
2164
+ resume() {
2165
+ return this.send({ command: "resume" });
2166
+ }
2167
+ /**
2168
+ * While paused, advances virtual time by ms and pauses again (the launcher rounds up to a multiple of the time step).
2169
+ */
2170
+ step(ms) {
2171
+ return this.send({ command: "step", ms });
2172
+ }
2173
+ /** Changes the speed (a pause stays in effect). */
2174
+ setSpeed(value) {
2175
+ return this.send({ command: "speed", value });
2176
+ }
2177
+ /**
2178
+ * Sends a command. The result arrives as the launcher's command and time events (the content of the HTTP answer is
2179
+ * not used). With no run, or while waiting for the answer to the previous command (sending), nothing is sent and
2180
+ * `{sent: false, reason}` is returned. If no answer comes within answerTimeoutMs, stops waiting and reports it in
2181
+ * failure. Check whether a command can be used (canPause and so on) before sending.
2182
+ */
2183
+ send(command) {
2184
+ const session = this.session.get();
2185
+ if (!session) return { sent: false, reason: "no-session" };
2186
+ if (this.state.get().sending !== null) return { sent: false, reason: "waiting" };
2187
+ this.failureValue.set(null);
2188
+ const pending = {
2189
+ command: command.command,
2190
+ session: session.id,
2191
+ afterSeq: session.lastCommand?.seq ?? -1
2192
+ };
2193
+ this.pending.set(pending);
2194
+ this.inFlight.update((n) => n + 1);
2195
+ clearTimeout(this.answerTimer);
2196
+ this.answerTimer = setTimeout(() => this.giveUp(pending), this.answerTimeoutMs);
2197
+ this.transport({ method: "POST", path: "api/time", body: command }, (outcome) => {
2198
+ this.inFlight.update((n) => n - 1);
2199
+ if (outcome.ok || this.pending.get() !== pending) return;
2200
+ clearTimeout(this.answerTimer);
2201
+ this.pending.set(null);
2202
+ this.failureValue.set({
2203
+ kind: "server",
2204
+ message: errorMessage(outcome.error),
2205
+ command: pending.command,
2206
+ session: this.session.get()?.id ?? null
2207
+ });
2208
+ });
2209
+ return { sent: true };
2210
+ }
2211
+ /** Stops the wait timer and stops waiting for the answer (when the client closes). */
2212
+ dispose() {
2213
+ clearTimeout(this.answerTimer);
2214
+ this.pending.set(null);
2215
+ }
2216
+ /** The answer timed out: if no answer has come yet, stop waiting and say so. */
2217
+ giveUp(pending) {
2218
+ if (this.pending.get() !== pending || this.state.get().sending === null) return;
2219
+ this.pending.set(null);
2220
+ this.failureValue.set({
2221
+ kind: "no-answer",
2222
+ message: `the launcher did not answer the command (${pending.command}) within ${this.answerTimeoutMs / 1e3} s; it may not read its input. You can send it again.`,
2223
+ command: pending.command,
2224
+ session: pending.session
2225
+ });
2226
+ }
2227
+ compute(session, ready, app) {
2228
+ const supported = app?.launcher.features.includes(FEATURE_TIME_COMMANDS) ?? false;
2229
+ const time = session?.time ?? null;
2230
+ let lateness = !time || time.lateSteps === null || time.maxLateMs === null ? null : {
2231
+ lateSteps: time.lateSteps,
2232
+ maxLateMs: time.maxLateMs,
2233
+ slippedMs: time.slippedMs ?? 0,
2234
+ lateMs: time.lateMs ?? 0
2235
+ };
2236
+ if (lateness && this.lastLateness && shallowEqual(lateness, this.lastLateness)) {
2237
+ lateness = this.lastLateness;
2238
+ }
2239
+ this.lastLateness = lateness;
2240
+ const lastCommand = session?.lastCommand ?? null;
2241
+ const variables = this.variables?.get();
2242
+ const beforeStart = !!session && session.startPaused && session.phase === "waiting" && session.time === null && session.launcher.running && session.result === null && variables?.session === session.id && variables.status !== "off" && variables.status !== "unknown";
2243
+ const controllable = supported && ready && !!session && (session.phase === "running" && session.time !== null || beforeStart) && session.launcher.running && session.result === null && session.stopRequests === 0;
2244
+ const pending = this.pending.get();
2245
+ let sending = null;
2246
+ if (pending) {
2247
+ const answered = !session || session.id !== pending.session || !session.launcher.running || (session.lastCommand?.seq ?? -1) > pending.afterSeq;
2248
+ sending = this.inFlight.get() > 0 || !answered ? pending.command : null;
2249
+ }
2250
+ const paused = time?.paused ?? (beforeStart ? true : null);
2251
+ const stepping = lastCommand?.name === "step" && lastCommand.accepted && paused === false;
2252
+ const free = controllable && sending === null;
2253
+ const canResume = free && (paused === true || stepping);
2254
+ const failure = this.failureValue.get();
2255
+ return {
2256
+ supported,
2257
+ time,
2258
+ paced: typeof time?.speed === "number",
2259
+ lateness,
2260
+ behind: (lateness?.lateSteps ?? 0) > 0,
2261
+ lastCommand,
2262
+ controllable,
2263
+ beforeStart,
2264
+ sending,
2265
+ stepping,
2266
+ canPause: free && paused === false,
2267
+ canResume,
2268
+ canStep: canResume,
2269
+ failure: failure && failure.session === (session?.id ?? null) ? failure : null
2270
+ };
2271
+ }
2272
+ };
2273
+
2274
+ // ../client/src/urls.ts
2275
+ function webSocketUrl(baseUri, path) {
2276
+ const url = new URL(path, baseUri);
2277
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
2278
+ return url.href;
2279
+ }
2280
+
2281
+ // ../client/src/variable-state.ts
2282
+ function valueCondition(input) {
2283
+ const { status, known, reading } = input;
2284
+ if (!known) {
2285
+ return status === "ready" || status === "ended" ? { kind: "missing" } : { kind: "unavailable", status };
2286
+ }
2287
+ if (reading === void 0) {
2288
+ return status === "ready" || status === "ended" ? { kind: "waiting" } : { kind: "unavailable", status };
2289
+ }
2290
+ if (!input.connected) return { kind: "stale", reading, why: "connection" };
2291
+ if (status === "ended") return { kind: "ended", reading };
2292
+ if (status !== "ready") return { kind: "stale", reading, why: "reconnecting" };
2293
+ if (!input.peerConnected) return { kind: "stale", reading, why: "peer" };
2294
+ if (input.readFailing) return { kind: "stale", reading, why: "reading" };
2295
+ return reading.paused ? { kind: "paused", reading } : { kind: "live", reading };
2296
+ }
2297
+ function sameCondition(a, b) {
2298
+ if (a.kind !== b.kind) return false;
2299
+ const reading = (c) => "reading" in c ? c.reading : void 0;
2300
+ const status = (c) => c.kind === "unavailable" ? c.status : void 0;
2301
+ const why = (c) => c.kind === "stale" ? c.why : void 0;
2302
+ return reading(a) === reading(b) && status(a) === status(b) && why(a) === why(b);
2303
+ }
2304
+ function writeBlock(input) {
2305
+ const { info, status } = input;
2306
+ if (info !== void 0 && !info.writable) return "read-only";
2307
+ if (!input.connected) return "disconnected";
2308
+ if (status === "ended") return "ended";
2309
+ if (status !== "ready") return "not-ready";
2310
+ if (info === void 0) return "missing";
2311
+ if (!input.peerConnected) return "peer-disconnected";
2312
+ if (info.role === "parameter" && !input.beforeStart) return "parameter";
2313
+ return null;
2314
+ }
2315
+ function isWriteError(status) {
2316
+ return "message" in status;
2317
+ }
2318
+ function hasRange(info) {
2319
+ return info.min !== null && info.max !== null && Number.isFinite(info.min) && Number.isFinite(info.max) && info.min < info.max;
2320
+ }
2321
+
2322
+ // ../client/src/variables.ts
2323
+ var WriteError = class extends Error {
2324
+ constructor(kind, message, code = null, operation = null) {
2325
+ super(message);
2326
+ this.kind = kind;
2327
+ this.code = code;
2328
+ this.operation = operation;
2329
+ this.name = "WriteError";
2330
+ }
2331
+ kind;
2332
+ code;
2333
+ operation;
2334
+ };
2335
+ var WRITE_TIMEOUT_MS = 1e4;
2336
+ var HISTORY_MAX = 1e5;
2337
+ var HISTORY_TOTAL_MAX = 2e6;
2338
+ var HISTORY_FIRST = 16;
2339
+ var WATCH_MESSAGE_BYTES = 200 * 1024;
2340
+ var TIMER_MAX_MS = 2 ** 31 - 1;
2341
+ var OPERATIONS_KEPT = 64;
2342
+ var WATCH_PERIOD_MS = 100;
2343
+ var WATCH_PERIODS_MS = [20, 50, 100, 200, 500, 1e3, 2e3, 5e3, 1e4, 6e4];
2344
+ var WATCH_VARIABLES = 2e3;
2345
+ var NO_VARIABLES = {
2346
+ session: null,
2347
+ status: "unknown",
2348
+ reason: null,
2349
+ peers: [],
2350
+ peersOmitted: 0,
2351
+ variablesOmitted: 0
2352
+ };
2353
+ function utf8Length(textValue) {
2354
+ let bytes = 0;
2355
+ for (let i = 0; i < textValue.length; i++) {
2356
+ const code = textValue.charCodeAt(i);
2357
+ bytes += code < 128 ? 1 : code < 2048 ? 2 : 3;
2358
+ }
2359
+ return bytes;
2360
+ }
2361
+ var keyOf = (peer, name) => `${peer}\0${name}`;
2362
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2363
+ var text = (value, fallback = "") => typeof value === "string" ? value : fallback;
2364
+ var numberOrNull = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
2365
+ var count = (value) => typeof value === "number" && value >= 0 ? value : 0;
2366
+ function readVariables2(value, session) {
2367
+ if (!isObject(value)) return { ...NO_VARIABLES, session };
2368
+ const peers = [];
2369
+ for (const p of Array.isArray(value["peers"]) ? value["peers"] : []) {
2370
+ if (!isObject(p) || typeof p["name"] !== "string") continue;
2371
+ const variables = [];
2372
+ for (const v of Array.isArray(p["variables"]) ? p["variables"] : []) {
2373
+ if (!isObject(v) || typeof v["name"] !== "string") continue;
2374
+ const items2 = Array.isArray(v["enum"]) ? v["enum"].flatMap(
2375
+ (i) => isObject(i) && typeof i["name"] === "string" && typeof i["value"] === "number" ? [{ name: i["name"], value: i["value"] }] : []
2376
+ ) : null;
2377
+ variables.push({
2378
+ name: v["name"],
2379
+ type: text(v["type"]),
2380
+ role: text(v["role"], "output"),
2381
+ writable: v["writable"] === true,
2382
+ unit: text(v["unit"]),
2383
+ min: numberOrNull(v["min"]),
2384
+ max: numberOrNull(v["max"]),
2385
+ step: numberOrNull(v["step"]),
2386
+ description: text(v["description"]),
2387
+ enum: items2
2388
+ });
2389
+ }
2390
+ peers.push({ name: p["name"], connected: p["connected"] === true, variables });
2391
+ }
2392
+ return {
2393
+ session,
2394
+ status: text(value["state"], "unknown"),
2395
+ reason: typeof value["reason"] === "string" ? value["reason"] : null,
2396
+ peers,
2397
+ peersOmitted: count(value["peers_omitted"]),
2398
+ variablesOmitted: count(value["variables_omitted"])
2399
+ };
2400
+ }
2401
+ function readOperation(value, session) {
2402
+ if (!isObject(value) || !Number.isSafeInteger(value["seq"]) || typeof value["state"] !== "string") {
2403
+ return null;
2404
+ }
2405
+ const peers = {};
2406
+ for (const [name, p] of Object.entries(isObject(value["peers"]) ? value["peers"] : {})) {
2407
+ if (!isObject(p)) continue;
2408
+ peers[name] = {
2409
+ state: text(p["state"], "unknown"),
2410
+ appliedAtMs: numberOrNull(p["applied_at_ms"]),
2411
+ late: p["late"] === true,
2412
+ reason: typeof p["reason"] === "string" ? p["reason"] : null
2413
+ };
2414
+ }
2415
+ return {
2416
+ session,
2417
+ seq: value["seq"],
2418
+ state: value["state"],
2419
+ done: value["done"] === true,
2420
+ peers
2421
+ };
2422
+ }
2423
+ var History = class {
2424
+ /** limit: the most points to keep. Memory doubles as points arrive (it is not all taken up front). */
2425
+ constructor(max) {
2426
+ this.max = max;
2427
+ this.capacity = Math.min(max, HISTORY_FIRST);
2428
+ this.times = new Float64Array(this.capacity);
2429
+ this.values = new Float64Array(this.capacity);
2430
+ this.kinds = new Uint8Array(this.capacity);
2431
+ }
2432
+ max;
2433
+ times;
2434
+ values;
2435
+ /** Kind of value: 0 number, 1 bool, 2 null. */
2436
+ kinds;
2437
+ capacity;
2438
+ start = 0;
2439
+ length = 0;
2440
+ get size() {
2441
+ return this.length;
2442
+ }
2443
+ /** Memory taken (in points). */
2444
+ get reserved() {
2445
+ return this.capacity;
2446
+ }
2447
+ get limit() {
2448
+ return this.max;
2449
+ }
2450
+ get lastTime() {
2451
+ return this.length === 0 ? null : this.times[(this.start + this.length - 1) % this.capacity] ?? null;
2452
+ }
2453
+ /**
2454
+ * Adds a point. If the buffer is full and below the limit, doubles it as far as mayGrow(number of points to add)
2455
+ * allows. If that is not allowed, keeps the current size and drops the oldest point.
2456
+ */
2457
+ push(sampleMs, value, mayGrow) {
2458
+ if (this.max === 0) return;
2459
+ if (this.length === this.capacity && this.capacity < this.max) {
2460
+ const next = Math.min(this.max, this.capacity * 2);
2461
+ if (mayGrow(next - this.capacity)) this.resize(next);
2462
+ }
2463
+ const at = (this.start + this.length) % this.capacity;
2464
+ this.set(at, sampleMs, value);
2465
+ if (this.length < this.capacity) this.length += 1;
2466
+ else this.start = (this.start + 1) % this.capacity;
2467
+ }
2468
+ /** Replaces the value of the last point (when a value of the same step arrives again with a different value). */
2469
+ replaceLast(value) {
2470
+ if (this.length === 0) return;
2471
+ const at = (this.start + this.length - 1) % this.capacity;
2472
+ this.set(at, this.times[at] ?? 0, value);
2473
+ }
2474
+ set(at, sampleMs, value) {
2475
+ this.times[at] = sampleMs;
2476
+ this.values[at] = value === null ? 0 : Number(value);
2477
+ this.kinds[at] = value === null ? 2 : typeof value === "boolean" ? 1 : 0;
2478
+ }
2479
+ /** Up to n of the newest points, oldest first. */
2480
+ last(n) {
2481
+ const take = Math.min(n, this.length);
2482
+ const out = [];
2483
+ for (let i = this.length - take; i < this.length; i++) {
2484
+ const at = (this.start + i) % this.capacity;
2485
+ const kind = this.kinds[at];
2486
+ const value = this.values[at] ?? 0;
2487
+ out.push({
2488
+ sampleMs: this.times[at] ?? 0,
2489
+ value: kind === 2 ? null : kind === 1 ? value !== 0 : value
2490
+ });
2491
+ }
2492
+ return out;
2493
+ }
2494
+ /** Raises the limit (memory is taken as points arrive). */
2495
+ raise(max) {
2496
+ if (max > this.max) this.max = max;
2497
+ }
2498
+ resize(capacity) {
2499
+ const kept = this.last(this.length);
2500
+ this.capacity = capacity;
2501
+ this.times = new Float64Array(capacity);
2502
+ this.values = new Float64Array(capacity);
2503
+ this.kinds = new Uint8Array(capacity);
2504
+ this.start = 0;
2505
+ this.length = kept.length;
2506
+ kept.forEach((point, at) => this.set(at, point.sampleMs, point.value));
2507
+ }
2508
+ };
2509
+ function lost(seq, summary) {
2510
+ if (summary.fromSeq === null || seq >= summary.fromSeq) return null;
2511
+ if (summary.operations.some((o) => o.seq === seq)) return null;
2512
+ return new WriteError(
2513
+ "no-answer",
2514
+ summary.openOmitted ? `the server does not keep track of the write (operation ${seq}) any more (it holds too many open operations): its result may not come; look at the values before writing again` : `the result of the write (operation ${seq}) was lost while the connection was down (it was settled meanwhile, and the server does not list it any more): look at the values before writing again`
2515
+ );
2516
+ }
2517
+ var VariablesFeed = class {
2518
+ constructor(link, http, onError = rethrowLater, limits = () => ({})) {
2519
+ this.link = link;
2520
+ this.http = http;
2521
+ this.onError = onError;
2522
+ this.limits = limits;
2523
+ this.stateValue = new Writable(NO_VARIABLES, Object.is, onError);
2524
+ this.operationsValue = new Writable([], Object.is, onError);
2525
+ this.problemValue = new Writable(null, Object.is, onError);
2526
+ this.state = this.stateValue.readonly();
2527
+ this.operations = this.operationsValue.readonly();
2528
+ this.watchProblem = this.problemValue.readonly();
2529
+ link.onBatch((batch) => this.receive(batch));
2530
+ }
2531
+ link;
2532
+ http;
2533
+ onError;
2534
+ limits;
2535
+ stateValue;
2536
+ operationsValue;
2537
+ handles = /* @__PURE__ */ new Set();
2538
+ buckets = /* @__PURE__ */ new Map();
2539
+ readings = /* @__PURE__ */ new Map();
2540
+ histories = /* @__PURE__ */ new Map();
2541
+ pending = /* @__PURE__ */ new Set();
2542
+ /** Variables someone watches (null: a watch observes all). */
2543
+ watched = /* @__PURE__ */ new Set();
2544
+ /** History points requested by watches of all variables (the largest request). */
2545
+ allHistory = 0;
2546
+ /** History points requested by name (per variable, the largest among the watches that asked). */
2547
+ namedHistory = /* @__PURE__ */ new Map();
2548
+ /** Total memory taken for histories (in points). */
2549
+ historyReserved = 0;
2550
+ problemValue;
2551
+ nextId = 1;
2552
+ syncQueued = false;
2553
+ state;
2554
+ operations;
2555
+ watchProblem;
2556
+ // --- Connection -----------------------------------------------------------------------------
2557
+ /** Messages sent right after connecting (after authentication): all current subscriptions. */
2558
+ resume() {
2559
+ this.syncQueued = false;
2560
+ const messages = [];
2561
+ for (const [periodMs, wanted] of this.wanted()) {
2562
+ const bucket = this.bucket(periodMs);
2563
+ const message = this.watchMessage(bucket, wanted);
2564
+ bucket.asked = JSON.stringify(message);
2565
+ messages.push(message);
2566
+ }
2567
+ for (const [periodMs, bucket] of this.buckets) {
2568
+ if (!messages.some((m) => m.id === bucket.id))
2569
+ this.buckets.delete(periodMs);
2570
+ }
2571
+ return messages;
2572
+ }
2573
+ /** The client was closed: fail the pending writes (including those waiting for the HTTP answer). Watches stay. */
2574
+ dispose() {
2575
+ for (const pending of [...this.pending]) {
2576
+ this.settle(
2577
+ pending,
2578
+ new WriteError("closed", "the client was closed before the result came")
2579
+ );
2580
+ }
2581
+ }
2582
+ // --- Notifications --------------------------------------------------------------------------
2583
+ receive(batch) {
2584
+ const touched = /* @__PURE__ */ new Set();
2585
+ let touchedAll = false;
2586
+ let operations = null;
2587
+ let fresh = [];
2588
+ const flush = () => {
2589
+ if (operations) this.setOperations(operations, fresh);
2590
+ operations = null;
2591
+ fresh = [];
2592
+ };
2593
+ for (const message of batch) {
2594
+ if (!isObject(message)) continue;
2595
+ switch (message["type"]) {
2596
+ case "hello": {
2597
+ flush();
2598
+ const summary = message["session"];
2599
+ if (isObject(summary) && Number.isSafeInteger(summary["id"])) {
2600
+ this.adoptSummary(summary);
2601
+ } else {
2602
+ this.enter(null);
2603
+ this.stateValue.set({ ...NO_VARIABLES, status: "off" });
2604
+ }
2605
+ touchedAll = true;
2606
+ break;
2607
+ }
2608
+ case "session": {
2609
+ const summary = message["session"];
2610
+ const id = isObject(summary) ? summary["id"] : null;
2611
+ if (Number.isSafeInteger(id) && id !== this.stateValue.get().session) {
2612
+ flush();
2613
+ this.enter(id);
2614
+ this.stateValue.set({ ...NO_VARIABLES, session: id });
2615
+ touchedAll = true;
2616
+ }
2617
+ break;
2618
+ }
2619
+ case "variables": {
2620
+ const id = message["session"];
2621
+ if (!Number.isSafeInteger(id)) break;
2622
+ if (id !== this.stateValue.get().session) {
2623
+ flush();
2624
+ this.enter(id);
2625
+ touchedAll = true;
2626
+ }
2627
+ this.stateValue.set(readVariables2(message["variables"], id));
2628
+ break;
2629
+ }
2630
+ case "values": {
2631
+ if (message["session"] !== this.stateValue.get().session) break;
2632
+ this.takeValues(message, touched);
2633
+ break;
2634
+ }
2635
+ case "operation": {
2636
+ const id = message["session"];
2637
+ if (id !== this.stateValue.get().session) break;
2638
+ const operation = readOperation(message, id);
2639
+ if (operation) {
2640
+ operations = this.withOperation(operations ?? this.operationsValue.get(), operation);
2641
+ fresh.push(operation);
2642
+ }
2643
+ break;
2644
+ }
2645
+ case "error": {
2646
+ const code = message["code"];
2647
+ if (code === "invalid-watch" || code === "too-many-watches") {
2648
+ this.problemValue.set({ code, message: text(message["message"]) });
2649
+ }
2650
+ break;
2651
+ }
2652
+ }
2653
+ }
2654
+ flush();
2655
+ if (touchedAll || touched.size > 0) this.publish(touchedAll ? null : touched);
2656
+ }
2657
+ /** Applies the variables part of hello and of an HTTP summary (`session`). */
2658
+ adoptSummary(summary) {
2659
+ if (!isObject(summary) || !Number.isSafeInteger(summary["id"])) return;
2660
+ const id = summary["id"];
2661
+ const variables = summary["variables"];
2662
+ if (id !== this.stateValue.get().session) {
2663
+ this.enter(id);
2664
+ this.publish(null);
2665
+ } else if (variables === void 0) {
2666
+ return;
2667
+ }
2668
+ this.stateValue.set(readVariables2(variables, id));
2669
+ if (isObject(variables) && Array.isArray(variables["operations"])) {
2670
+ let operations = this.operationsValue.get();
2671
+ const listed = [];
2672
+ for (const entry of variables["operations"]) {
2673
+ const operation = readOperation(entry, id);
2674
+ if (operation) {
2675
+ listed.push(operation);
2676
+ operations = this.withOperation(operations, operation);
2677
+ }
2678
+ }
2679
+ this.setOperations(operations, listed);
2680
+ const fromSeq = variables["operations_from_seq"];
2681
+ const openOmitted = variables["operations_open_omitted"];
2682
+ this.forgetLost(id, {
2683
+ operations: listed,
2684
+ fromSeq: Number.isSafeInteger(fromSeq) ? fromSeq : null,
2685
+ openOmitted: typeof openOmitted === "number" && openOmitted > 0
2686
+ });
2687
+ }
2688
+ }
2689
+ /**
2690
+ * With the summary after a reconnect (or from api/session), settles as "no answer came" (lost) the writes waiting for
2691
+ * a result that will no longer arrive. For writes whose number is not known yet (before the HTTP answer), the summary
2692
+ * is kept and checked the same way once the number is known.
2693
+ */
2694
+ forgetLost(session, summary) {
2695
+ for (const pending of [...this.pending]) {
2696
+ if (pending.session !== session) continue;
2697
+ if (pending.seq === null) {
2698
+ pending.summary = summary;
2699
+ continue;
2700
+ }
2701
+ const error = lost(pending.seq, summary);
2702
+ if (error) this.settle(pending, error);
2703
+ }
2704
+ }
2705
+ /**
2706
+ * Switched to another run: drop the previous run's values, histories and operations (histories not requested by name
2707
+ * are dropped with their memory, so they do not keep growing as the variables change from run to run). Writes
2708
+ * waiting for the previous run's result are failed, since the result will not come.
2709
+ */
2710
+ enter(session) {
2711
+ if (session === this.stateValue.get().session) return;
2712
+ this.readings.clear();
2713
+ this.histories.clear();
2714
+ this.historyReserved = 0;
2715
+ this.operationsValue.set([]);
2716
+ for (const pending of [...this.pending]) {
2717
+ if (pending.session !== session) {
2718
+ this.settle(
2719
+ pending,
2720
+ new WriteError(
2721
+ "no-answer",
2722
+ `the run ${pending.session} is over (another one has started): the result of the write ` + (pending.seq === null ? "" : `(operation ${pending.seq}) `) + "did not come"
2723
+ )
2724
+ );
2725
+ }
2726
+ }
2727
+ }
2728
+ takeValues(message, touched) {
2729
+ const peers = message["peers"];
2730
+ if (!isObject(peers)) return;
2731
+ const simMs = numberOrNull(message["sim_ms"]);
2732
+ const paused = message["paused"] === true;
2733
+ const mayGrow = (more) => {
2734
+ if (this.historyReserved + more > HISTORY_TOTAL_MAX) return false;
2735
+ this.historyReserved += more;
2736
+ return true;
2737
+ };
2738
+ for (const [peer, entry] of Object.entries(peers)) {
2739
+ if (!isObject(entry) || !isObject(entry["values"])) continue;
2740
+ const sampleMs = numberOrNull(entry["sample_ms"]) ?? 0;
2741
+ for (const [name, raw] of Object.entries(entry["values"])) {
2742
+ const value = typeof raw === "boolean" || typeof raw === "number" && Number.isFinite(raw) ? raw : null;
2743
+ const key = keyOf(peer, name);
2744
+ if (this.watched !== null && !this.watched.has(key)) continue;
2745
+ const before = this.readings.get(key);
2746
+ if (before && before.sampleMs === sampleMs && before.simMs === simMs && before.paused === paused && Object.is(before.value, value)) {
2747
+ continue;
2748
+ }
2749
+ this.readings.set(key, { value, sampleMs, simMs, paused });
2750
+ touched.add(key);
2751
+ const wanted = Math.max(this.namedHistory.get(key) ?? 0, this.allHistory);
2752
+ if (wanted === 0) continue;
2753
+ let history = this.histories.get(key);
2754
+ if (!history) {
2755
+ if (!mayGrow(Math.min(wanted, HISTORY_FIRST))) continue;
2756
+ history = new History(wanted);
2757
+ this.histories.set(key, history);
2758
+ } else {
2759
+ history.raise(wanted);
2760
+ }
2761
+ const last = history.lastTime;
2762
+ if (last === null || sampleMs > last) history.push(sampleMs, value, mayGrow);
2763
+ else if (sampleMs === last) history.replaceLast(value);
2764
+ }
2765
+ }
2766
+ }
2767
+ /** Rebuilds values of the watches that observe the changed variables (all watches if touched is null). */
2768
+ publish(touched) {
2769
+ for (const handle of this.handles) {
2770
+ if (touched !== null && handle.keys !== null) {
2771
+ let hit = false;
2772
+ for (const key of handle.keys) {
2773
+ if (touched.has(key)) {
2774
+ hit = true;
2775
+ break;
2776
+ }
2777
+ }
2778
+ if (!hit) continue;
2779
+ }
2780
+ handle.values.set(this.valuesOf(handle));
2781
+ }
2782
+ }
2783
+ valuesOf(handle) {
2784
+ const out = {};
2785
+ const add = (key, reading) => {
2786
+ const cut = key.indexOf("\0");
2787
+ (out[key.slice(0, cut)] ??= {})[key.slice(cut + 1)] = reading;
2788
+ };
2789
+ if (handle.keys === null) {
2790
+ for (const [key, reading] of this.readings) add(key, reading);
2791
+ } else {
2792
+ for (const key of handle.keys) {
2793
+ const reading = this.readings.get(key);
2794
+ if (reading) add(key, reading);
2795
+ }
2796
+ }
2797
+ return out;
2798
+ }
2799
+ // --- Operations -----------------------------------------------------------------------------
2800
+ withOperation(operations, operation) {
2801
+ const at = operations.findIndex((o) => o.seq === operation.seq);
2802
+ if (at >= 0 && operations[at]?.done && !operation.done) return [...operations];
2803
+ const next = at >= 0 ? operations.map((o, i) => i === at ? operation : o) : [...operations, operation];
2804
+ return next.length > OPERATIONS_KEPT ? next.slice(next.length - OPERATIONS_KEPT) : next;
2805
+ }
2806
+ /**
2807
+ * Replaces the list of operations and clears the writes whose result has settled. `fresh` holds the operations that
2808
+ * just arrived (a batch of notifications, the list in a summary): the list is cut to OPERATIONS_KEPT entries, so
2809
+ * settled operations cut from the list are picked up from here.
2810
+ */
2811
+ setOperations(operations, fresh = []) {
2812
+ this.operationsValue.set(operations);
2813
+ for (const pending of [...this.pending]) {
2814
+ if (pending.seq === null) continue;
2815
+ const mine = (o) => o.done && o.seq === pending.seq && o.session === pending.session;
2816
+ const operation = fresh.find(mine) ?? operations.find(mine);
2817
+ if (operation) this.settle(pending, operation);
2818
+ }
2819
+ }
2820
+ settle(pending, outcome) {
2821
+ if (!this.pending.delete(pending)) return;
2822
+ clearTimeout(pending.timer);
2823
+ if (outcome instanceof WriteError) {
2824
+ pending.reject(outcome);
2825
+ } else if (outcome.state === "applied") {
2826
+ pending.resolve(outcome);
2827
+ } else {
2828
+ const reasons = Object.entries(outcome.peers).filter(([, p]) => p.state !== "applied").map(([name, p]) => `${name}: ${p.state}${p.reason ? ` (${p.reason})` : ""}`);
2829
+ pending.reject(
2830
+ new WriteError(
2831
+ "failed",
2832
+ `the write (operation ${outcome.seq}) was not applied: ${reasons.join("; ") || outcome.state}`,
2833
+ null,
2834
+ outcome
2835
+ )
2836
+ );
2837
+ }
2838
+ }
2839
+ write(writes, options = {}) {
2840
+ const asked = options.timeoutMs;
2841
+ const timeoutMs = asked === Infinity ? Infinity : typeof asked === "number" && asked > 0 ? Math.min(asked, TIMER_MAX_MS) : WRITE_TIMEOUT_MS;
2842
+ const session = this.stateValue.get().session;
2843
+ if (session === null) {
2844
+ return Promise.reject(
2845
+ new WriteError(
2846
+ "refused",
2847
+ "there is no run to write to (wait for the variables of a run: client.variables.state)",
2848
+ "not-running"
2849
+ )
2850
+ );
2851
+ }
2852
+ const body = { session, writes };
2853
+ if (options.atMs !== void 0) body["at_ms"] = options.atMs;
2854
+ if (options.late !== void 0) body["late"] = options.late;
2855
+ return new Promise((resolve, reject) => {
2856
+ const pending = { session, seq: null, resolve, reject, timer: void 0 };
2857
+ this.pending.add(pending);
2858
+ const known = () => this.operationsValue.get().find((o) => o.seq === pending.seq && o.session === pending.session);
2859
+ this.http({ method: "POST", path: "api/write", body }, (outcome) => {
2860
+ if (!this.pending.has(pending)) return;
2861
+ if (!outcome.ok) {
2862
+ const error = outcome.error;
2863
+ const code = error instanceof HttpError ? error.problem?.code ?? null : null;
2864
+ const unsure = error instanceof HttpError && [0, 500, 502, 504].includes(error.status);
2865
+ this.settle(
2866
+ pending,
2867
+ new WriteError(
2868
+ unsure ? "no-answer" : "refused",
2869
+ unsure ? `${errorMessage(error)} (the write may have been taken: look at the operations and the values before writing again)` : errorMessage(error),
2870
+ code
2871
+ )
2872
+ );
2873
+ return;
2874
+ }
2875
+ const answer = outcome.body;
2876
+ const seq = isObject(answer) ? answer["operation"] : null;
2877
+ const answered = isObject(answer) ? answer["session_id"] : null;
2878
+ if (!Number.isSafeInteger(seq) || !Number.isSafeInteger(answered)) {
2879
+ this.settle(
2880
+ pending,
2881
+ new WriteError(
2882
+ "no-answer",
2883
+ "the server answered the write without an operation number"
2884
+ )
2885
+ );
2886
+ return;
2887
+ }
2888
+ if (answered !== pending.session || this.stateValue.get().session !== pending.session) {
2889
+ this.settle(
2890
+ pending,
2891
+ new WriteError(
2892
+ "no-answer",
2893
+ `the run ${pending.session} ended before the answer to the write came (operation ${String(seq)}): its result will not come; look at the values before writing again`
2894
+ )
2895
+ );
2896
+ return;
2897
+ }
2898
+ pending.seq = seq;
2899
+ if (options.onAccepted) {
2900
+ try {
2901
+ options.onAccepted({ session: pending.session, seq: pending.seq });
2902
+ } catch (error) {
2903
+ this.onError(error);
2904
+ }
2905
+ if (!this.pending.has(pending)) return;
2906
+ }
2907
+ if (timeoutMs !== Infinity) {
2908
+ pending.timer = setTimeout(() => {
2909
+ const last = known();
2910
+ this.settle(
2911
+ pending,
2912
+ new WriteError(
2913
+ "no-answer",
2914
+ `no result of the write (operation ${pending.seq}) came in ${timeoutMs / 1e3} s` + (last ? `: it is ${last.state} (it is applied when the simulation reaches its step)` : ""),
2915
+ null,
2916
+ last ?? null
2917
+ )
2918
+ );
2919
+ }, timeoutMs);
2920
+ pending.timer.unref?.();
2921
+ }
2922
+ const summary = pending.summary;
2923
+ const already = known() ?? summary?.operations.find((o) => o.seq === seq && o.session === pending.session);
2924
+ if (already?.done) this.settle(pending, already);
2925
+ else if (summary) {
2926
+ const error = lost(pending.seq, summary);
2927
+ if (error) this.settle(pending, error);
2928
+ }
2929
+ });
2930
+ });
2931
+ }
2932
+ // --- watch ----------------------------------------------------------------------------------
2933
+ watch(variables, options = {}) {
2934
+ const history = options.history ?? 0;
2935
+ const handle = {
2936
+ keys: variables === "all" ? null : new Set(variables.map((v) => keyOf(v.peer, v.name))),
2937
+ periodMs: this.period(options.periodMs ?? WATCH_PERIOD_MS),
2938
+ // A non-number or a negative value means 0 (keep none)
2939
+ history: Number.isFinite(history) ? Math.max(0, Math.min(Math.floor(history), HISTORY_MAX)) : 0,
2940
+ values: new Writable({}, Object.is, this.onError)
2941
+ };
2942
+ this.handles.add(handle);
2943
+ this.forget();
2944
+ handle.values.set(this.valuesOf(handle));
2945
+ this.queueSync();
2946
+ let open = true;
2947
+ const mine = (ref) => {
2948
+ const key = keyOf(ref.peer, ref.name);
2949
+ return open && (handle.keys === null || handle.keys.has(key)) ? key : null;
2950
+ };
2951
+ return {
2952
+ values: handle.values.readonly(),
2953
+ value: (ref) => {
2954
+ const key = mine(ref);
2955
+ return key === null ? void 0 : this.readings.get(key);
2956
+ },
2957
+ history: (ref) => {
2958
+ const key = mine(ref);
2959
+ return key === null ? [] : this.histories.get(key)?.last(handle.history) ?? [];
2960
+ },
2961
+ close: () => {
2962
+ if (!open) return;
2963
+ open = false;
2964
+ this.handles.delete(handle);
2965
+ this.forget();
2966
+ this.queueSync();
2967
+ }
2968
+ };
2969
+ }
2970
+ /**
2971
+ * Turns a requested interval into the longest of WATCH_PERIODS_MS that is not longer, kept within the server's range
2972
+ * (lower and upper limit).
2973
+ */
2974
+ period(wanted) {
2975
+ const limits = this.limits();
2976
+ const min = limits.watch_period_ms_min ?? WATCH_PERIODS_MS[0];
2977
+ const max = limits.watch_period_ms_max ?? WATCH_PERIODS_MS[WATCH_PERIODS_MS.length - 1] ?? min;
2978
+ let chosen = WATCH_PERIODS_MS[0];
2979
+ for (const period of WATCH_PERIODS_MS) if (period <= wanted) chosen = period;
2980
+ return Math.min(Math.max(chosen, min), Math.max(max, min));
2981
+ }
2982
+ /** Recounts who watches what, and drops the values of variables nobody watches and histories nobody requests. */
2983
+ forget() {
2984
+ let all = false;
2985
+ let allHistory = 0;
2986
+ const seen = /* @__PURE__ */ new Set();
2987
+ const named = /* @__PURE__ */ new Map();
2988
+ for (const handle of this.handles) {
2989
+ if (handle.keys === null) {
2990
+ all = true;
2991
+ allHistory = Math.max(allHistory, handle.history);
2992
+ continue;
2993
+ }
2994
+ for (const key of handle.keys) {
2995
+ seen.add(key);
2996
+ if (handle.history > 0) named.set(key, Math.max(named.get(key) ?? 0, handle.history));
2997
+ }
2998
+ }
2999
+ this.watched = all ? null : seen;
3000
+ this.allHistory = allHistory;
3001
+ this.namedHistory = named;
3002
+ for (const [key, history] of this.histories) {
3003
+ if (allHistory === 0 && !named.has(key)) {
3004
+ this.historyReserved -= history.reserved;
3005
+ this.histories.delete(key);
3006
+ }
3007
+ }
3008
+ if (all) return;
3009
+ for (const key of this.readings.keys()) if (!seen.has(key)) this.readings.delete(key);
3010
+ }
3011
+ /**
3012
+ * Per interval, the variables to request (null: all). A variable goes to the shortest interval among the watches that
3013
+ * observe it.
3014
+ */
3015
+ wanted() {
3016
+ const fastest = /* @__PURE__ */ new Map();
3017
+ let allPeriod = null;
3018
+ for (const handle of this.handles) {
3019
+ if (handle.keys === null) {
3020
+ allPeriod = Math.min(allPeriod ?? Infinity, handle.periodMs);
3021
+ continue;
3022
+ }
3023
+ for (const key of handle.keys) {
3024
+ fastest.set(key, Math.min(fastest.get(key) ?? Infinity, handle.periodMs));
3025
+ }
3026
+ }
3027
+ const out = /* @__PURE__ */ new Map();
3028
+ if (allPeriod !== null) out.set(allPeriod, null);
3029
+ const limit = this.limits().watch_variables ?? WATCH_VARIABLES;
3030
+ for (const [key, periodMs] of fastest) {
3031
+ if (allPeriod !== null && allPeriod <= periodMs) continue;
3032
+ const keys = out.get(periodMs);
3033
+ if (keys === void 0) out.set(periodMs, /* @__PURE__ */ new Set([key]));
3034
+ else keys?.add(key);
3035
+ }
3036
+ for (const [periodMs, keys] of out) if (keys && keys.size > limit) out.set(periodMs, null);
3037
+ return out;
3038
+ }
3039
+ bucket(periodMs) {
3040
+ let bucket = this.buckets.get(periodMs);
3041
+ if (!bucket) {
3042
+ bucket = { id: this.nextId++, periodMs, asked: null };
3043
+ this.buckets.set(periodMs, bucket);
3044
+ }
3045
+ return bucket;
3046
+ }
3047
+ watchMessage(bucket, wanted) {
3048
+ const message = (variables) => ({
3049
+ type: "watch",
3050
+ id: bucket.id,
3051
+ variables,
3052
+ period_ms: bucket.periodMs
3053
+ });
3054
+ if (wanted === null) return message("all");
3055
+ const named = message(
3056
+ [...wanted].sort().map((key) => {
3057
+ const cut = key.indexOf("\0");
3058
+ return { peer: key.slice(0, cut), name: key.slice(cut + 1) };
3059
+ })
3060
+ );
3061
+ return utf8Length(JSON.stringify(named)) > WATCH_MESSAGE_BYTES ? message("all") : named;
3062
+ }
3063
+ /** After watches were added or removed, brings the server subscriptions in line, once for all changes. */
3064
+ queueSync() {
3065
+ if (this.syncQueued) return;
3066
+ this.syncQueued = true;
3067
+ queueMicrotask(() => {
3068
+ if (!this.syncQueued) return;
3069
+ this.syncQueued = false;
3070
+ this.sync();
3071
+ });
3072
+ }
3073
+ sync() {
3074
+ const wanted = this.wanted();
3075
+ for (const [periodMs, bucket] of [...this.buckets]) {
3076
+ if (wanted.has(periodMs)) continue;
3077
+ this.buckets.delete(periodMs);
3078
+ if (bucket.asked !== null) this.link.send({ type: "unwatch", id: bucket.id });
3079
+ }
3080
+ for (const [periodMs, keys] of wanted) {
3081
+ const bucket = this.bucket(periodMs);
3082
+ const message = this.watchMessage(bucket, keys);
3083
+ const asked = JSON.stringify(message);
3084
+ if (asked === bucket.asked) continue;
3085
+ bucket.asked = asked;
3086
+ this.problemValue.set(null);
3087
+ this.link.send(message);
3088
+ }
3089
+ }
3090
+ };
3091
+
3092
+ // ../client/src/variable-binding.ts
3093
+ var DROPPED_MESSAGE = "the value kept back was not sent: the variable cannot be written any more (the run ended or another one started, or the ECU is not connected). Check the value and write it again";
3094
+ var keyOf2 = (ref) => `${ref.peer}\0${ref.name}`;
3095
+ var IDLE = { kind: "idle" };
3096
+ var VariableBinder = class {
3097
+ constructor(sources) {
3098
+ this.sources = sources;
3099
+ }
3100
+ sources;
3101
+ entries = /* @__PURE__ */ new Map();
3102
+ entriesSession = null;
3103
+ /** Per variable, the functions to call when the write status changes (the binds listen). */
3104
+ listeners = /* @__PURE__ */ new Map();
3105
+ /** Lookup table of the list (rebuilt when peers change). */
3106
+ tableOf = null;
3107
+ table = /* @__PURE__ */ new Map();
3108
+ connectedPeers = /* @__PURE__ */ new Set();
3109
+ /** Binds to a variable (ClientVariables.bind). */
3110
+ bind(ref, options = {}) {
3111
+ return new Binding(this, { peer: ref.peer, name: ref.name }, options);
3112
+ }
3113
+ lookUp() {
3114
+ const peers = this.sources.variables.state.get().peers;
3115
+ if (peers === this.tableOf) return;
3116
+ this.tableOf = peers;
3117
+ this.table = /* @__PURE__ */ new Map();
3118
+ this.connectedPeers = /* @__PURE__ */ new Set();
3119
+ for (const peer of peers) {
3120
+ this.table.set(peer.name, new Map(peer.variables.map((v) => [v.name, v])));
3121
+ if (peer.connected) this.connectedPeers.add(peer.name);
3122
+ }
3123
+ }
3124
+ /** Definition of the variable (undefined if it is not in the current run). */
3125
+ find(ref) {
3126
+ this.lookUp();
3127
+ return this.table.get(ref.peer)?.get(ref.name);
3128
+ }
3129
+ /** Whether that participant is connected to the Control Server now. */
3130
+ peerConnected(peer) {
3131
+ this.lookUp();
3132
+ return this.connectedPeers.has(peer);
3133
+ }
3134
+ /** Whether the connection between the client and the GUI server is open. */
3135
+ connected() {
3136
+ return this.sources.connection.get() === "open";
3137
+ }
3138
+ /**
3139
+ * Why the variable cannot be written now (null if it can). Only the widget-independent reasons (Binding adds
3140
+ * scenario, range and value).
3141
+ */
3142
+ block(ref) {
3143
+ return writeBlock({
3144
+ info: this.find(ref),
3145
+ status: this.sources.variables.state.get().status,
3146
+ connected: this.connected(),
3147
+ beforeStart: this.sources.time.get().beforeStart,
3148
+ peerConnected: this.peerConnected(ref.peer)
3149
+ });
3150
+ }
3151
+ /** Status of the last write to that variable in the current run. */
3152
+ status(ref) {
3153
+ return this.entry(ref)?.status ?? IDLE;
3154
+ }
3155
+ /** The value sent whose result has not arrived yet (null if none). */
3156
+ pending(ref) {
3157
+ return this.entry(ref)?.pending ?? null;
3158
+ }
3159
+ /** Called when the write status of that variable changes. Call the returned function to stop. */
3160
+ onChange(ref, listener) {
3161
+ const key = keyOf2(ref);
3162
+ const set = this.listeners.get(key) ?? /* @__PURE__ */ new Set();
3163
+ this.listeners.set(key, set);
3164
+ set.add(listener);
3165
+ return () => {
3166
+ set.delete(listener);
3167
+ if (set.size === 0 && this.listeners.get(key) === set) this.listeners.delete(key);
3168
+ };
3169
+ }
3170
+ changed(entry) {
3171
+ const set = this.listeners.get(entry.key);
3172
+ if (set) callEach(set, [], this.sources.onError);
3173
+ }
3174
+ /**
3175
+ * Writes. Does nothing when the variable cannot be written. If the server has not received the previous write yet,
3176
+ * the value is held instead of sent, and once the server receives it only the last value is sent (at that point it
3177
+ * checks again that the run is the same and the variable can still be written). A write whose result never came is
3178
+ * not resent.
3179
+ */
3180
+ write(ref, value) {
3181
+ if (this.block(ref) !== null) return;
3182
+ const entry = this.entry(ref);
3183
+ if (!entry) return;
3184
+ if (entry.sending) {
3185
+ entry.queued = { value };
3186
+ entry.shown = entry.sending;
3187
+ entry.status = { kind: "sending" };
3188
+ entry.pending = value;
3189
+ this.changed(entry);
3190
+ return;
3191
+ }
3192
+ this.send(entry, value);
3193
+ }
3194
+ /**
3195
+ * Shows an error the widget found before sending (not a number, out of range and so on) as the write status. Leaves
3196
+ * alone the write being sent, the write waiting for its result and the next value held (the result of a write
3197
+ * already sent no longer appears in the status field, but the value-sent display is cleared when it settles; if the
3198
+ * held value is sent later, the status field follows that write).
3199
+ */
3200
+ reject(ref, message) {
3201
+ const entry = this.entry(ref);
3202
+ if (!entry) return;
3203
+ entry.shown = null;
3204
+ entry.status = { kind: "invalid", message };
3205
+ this.changed(entry);
3206
+ }
3207
+ /**
3208
+ * Status of that variable in the current run (undefined without a run). When the run changes, the previous run's
3209
+ * statuses are dropped.
3210
+ */
3211
+ entry(ref) {
3212
+ const session = this.sources.variables.state.get().session;
3213
+ if (session !== this.entriesSession) {
3214
+ this.entries = /* @__PURE__ */ new Map();
3215
+ this.entriesSession = session;
3216
+ }
3217
+ if (session === null) return void 0;
3218
+ const key = keyOf2(ref);
3219
+ let entry = this.entries.get(key);
3220
+ if (!entry) {
3221
+ entry = {
3222
+ session,
3223
+ key,
3224
+ ref: { peer: ref.peer, name: ref.name },
3225
+ status: IDLE,
3226
+ pending: null,
3227
+ sending: null,
3228
+ queued: null,
3229
+ last: null,
3230
+ shown: null
3231
+ };
3232
+ this.entries.set(key, entry);
3233
+ }
3234
+ return entry;
3235
+ }
3236
+ send(entry, value) {
3237
+ const mine = { value };
3238
+ const { peer, name } = entry.ref;
3239
+ entry.sending = mine;
3240
+ entry.last = mine;
3241
+ entry.shown = mine;
3242
+ entry.status = { kind: "sending" };
3243
+ entry.pending = value;
3244
+ this.changed(entry);
3245
+ const accepted = (seq) => {
3246
+ if (entry.sending !== mine) return;
3247
+ entry.sending = null;
3248
+ const next = entry.queued;
3249
+ entry.queued = null;
3250
+ if (!next) {
3251
+ if (entry.shown === mine && seq !== null) {
3252
+ entry.status = { kind: "queued", seq };
3253
+ this.changed(entry);
3254
+ }
3255
+ return;
3256
+ }
3257
+ const same = this.sources.variables.state.get().session === entry.session;
3258
+ if (same && this.block(entry.ref) === null) {
3259
+ this.send(entry, next.value);
3260
+ return;
3261
+ }
3262
+ entry.pending = null;
3263
+ entry.shown = null;
3264
+ entry.status = { kind: "dropped", message: DROPPED_MESSAGE };
3265
+ this.changed(entry);
3266
+ };
3267
+ const settled = (status) => {
3268
+ if (entry.sending === mine) {
3269
+ entry.sending = null;
3270
+ entry.queued = null;
3271
+ }
3272
+ if (entry.last === mine) {
3273
+ entry.last = null;
3274
+ entry.pending = null;
3275
+ }
3276
+ if (entry.shown === mine) entry.status = status;
3277
+ this.changed(entry);
3278
+ };
3279
+ this.sources.variables.write(
3280
+ { [peer]: { [name]: value } },
3281
+ {
3282
+ // While paused, the result does not come until time advances. Do not time out; wait for the result of the
3283
+ // operation (if the result is lost because the run ends, the run changes or the connection is re-established,
3284
+ // write settles it as "no answer came")
3285
+ timeoutMs: Infinity,
3286
+ onAccepted: ({ seq }) => accepted(seq)
3287
+ }
3288
+ ).then(
3289
+ (operation) => {
3290
+ accepted(null);
3291
+ settled({ kind: "applied", atMs: operation.peers[peer]?.appliedAtMs ?? null });
3292
+ },
3293
+ (error) => settled(
3294
+ error instanceof WriteError ? { kind: error.kind, message: error.message, code: error.code } : { kind: "no-answer", message: String(error), code: null }
3295
+ )
3296
+ );
3297
+ }
3298
+ };
3299
+ function sameBound(a, b) {
3300
+ return a.info === b.info && a.reading === b.reading && a.block === b.block && a.writeStatus === b.writeStatus && a.pending === b.pending && sameCondition(a.condition, b.condition);
3301
+ }
3302
+ var Binding = class {
3303
+ constructor(binder, ref, options) {
3304
+ this.binder = binder;
3305
+ this.ref = ref;
3306
+ this.options = options;
3307
+ const { sources } = binder;
3308
+ if (options.visible ?? true) this.openWatch();
3309
+ this.value = new Writable(this.compute(), sameBound, sources.onError);
3310
+ const refresh = () => this.refresh();
3311
+ this.stops.push(
3312
+ sources.variables.state.subscribe(refresh),
3313
+ sources.connection.subscribe(refresh),
3314
+ sources.time.subscribe(refresh),
3315
+ sources.session.subscribe(refresh),
3316
+ binder.onChange(ref, refresh)
3317
+ );
3318
+ this.state = {
3319
+ // Built from the current state on every read (never returns a stale status, even if another subscriber was called
3320
+ // first)
3321
+ get: () => {
3322
+ this.refresh();
3323
+ return this.value.get();
3324
+ },
3325
+ subscribe: (listener) => this.value.subscribe(listener)
3326
+ };
3327
+ }
3328
+ binder;
3329
+ ref;
3330
+ options;
3331
+ state;
3332
+ value;
3333
+ stops = [];
3334
+ watch = null;
3335
+ stopWatch = null;
3336
+ open = true;
3337
+ refresh() {
3338
+ if (this.open) this.value.set(this.compute());
3339
+ }
3340
+ compute() {
3341
+ const { binder, ref } = this;
3342
+ const { sources } = binder;
3343
+ const variables = sources.variables.state.get();
3344
+ const info = binder.find(ref);
3345
+ const reading = this.watch?.value(ref);
3346
+ const condition = valueCondition({
3347
+ status: variables.status,
3348
+ known: info !== void 0,
3349
+ reading,
3350
+ connected: binder.connected(),
3351
+ peerConnected: binder.peerConnected(ref.peer),
3352
+ // A reason while still ready means reading values keeps failing (the value is the last one read)
3353
+ readFailing: variables.status === "ready" && variables.reason !== null
3354
+ });
3355
+ const pending = binder.pending(ref);
3356
+ return {
3357
+ ref,
3358
+ info,
3359
+ reading,
3360
+ condition,
3361
+ block: this.blockOf(info, reading, pending),
3362
+ writeStatus: binder.status(ref),
3363
+ pending
3364
+ };
3365
+ }
3366
+ blockOf(info, reading, pending) {
3367
+ const base = this.binder.block(this.ref);
3368
+ if (base !== null) return base;
3369
+ const session = this.binder.sources.session.get();
3370
+ if (session?.scenario && session.launcher.running) return "scenario";
3371
+ if (this.options.needsRange && info && !hasRange(info)) return "no-range";
3372
+ if (this.options.needsValue && reading === void 0 && pending === null) return "no-value";
3373
+ return null;
3374
+ }
3375
+ openWatch() {
3376
+ const { periodMs, history } = this.options;
3377
+ const watch = this.binder.sources.variables.watch([this.ref], { periodMs, history });
3378
+ this.watch = watch;
3379
+ this.stopWatch = watch.values.subscribe(() => this.refresh());
3380
+ }
3381
+ closeWatch() {
3382
+ this.stopWatch?.();
3383
+ this.stopWatch = null;
3384
+ this.watch?.close();
3385
+ this.watch = null;
3386
+ }
3387
+ history() {
3388
+ return this.options.history && this.watch ? this.watch.history(this.ref) : [];
3389
+ }
3390
+ write(value) {
3391
+ if (!this.open) return;
3392
+ if (this.compute().block !== null) return;
3393
+ this.binder.write(this.ref, value);
3394
+ }
3395
+ reject(message) {
3396
+ if (this.open) this.binder.reject(this.ref, message);
3397
+ }
3398
+ setVisible(visible) {
3399
+ if (!this.open || visible === (this.watch !== null)) return;
3400
+ if (visible) this.openWatch();
3401
+ else this.closeWatch();
3402
+ this.refresh();
3403
+ }
3404
+ close() {
3405
+ if (!this.open) return;
3406
+ this.open = false;
3407
+ for (const stop of this.stops) stop();
3408
+ this.closeWatch();
3409
+ }
3410
+ };
3411
+
3412
+ // ../client/src/client.ts
3413
+ var DEFAULT_LIMITS = {
3414
+ speed_min: 1e-6,
3415
+ speed_max: 1e6,
3416
+ step_ms_max: 1e12,
3417
+ check_timeout_s: 120,
3418
+ watch_period_ms_min: 20,
3419
+ watch_period_ms_max: 6e4,
3420
+ watches: 16,
3421
+ watch_variables: 2e3,
3422
+ writes_per_request: 256,
3423
+ write_at_ms_max: 1e12
3424
+ };
3425
+ var reportToConsole = (error) => console.error("vehicle-sil gui-client: a subscriber threw (the client goes on):", error);
3426
+ function longRequestMs(limits) {
3427
+ return 2 * limits.check_timeout_s * 1e3 + DEFAULT_TIMEOUT_MS;
3428
+ }
3429
+ function isNode(runtime = globalThis) {
3430
+ const process = runtime.process;
3431
+ return typeof process?.versions?.node === "string";
3432
+ }
3433
+ function defaultOrigin(baseUrl, runtime = globalThis) {
3434
+ return isNode(runtime) ? new URL(baseUrl).origin : void 0;
3435
+ }
3436
+ function createClient(options) {
3437
+ const token = typeof options.token === "function" ? options.token : () => options.token;
3438
+ const onError = options.onError ?? reportToConsole;
3439
+ const origin = options.origin ?? defaultOrigin(options.baseUrl);
3440
+ const http = options.http ?? fetchTransport({ baseUrl: options.baseUrl, token, origin });
3441
+ const app = new Writable(null, Object.is, onError);
3442
+ const limits = new Writable(DEFAULT_LIMITS, Object.is, onError);
3443
+ app.subscribe((info) => limits.set(info?.limits ?? DEFAULT_LIMITS));
3444
+ let feed = null;
3445
+ let variablesFeed = null;
3446
+ const connection = new Connection({
3447
+ url: webSocketUrl(options.baseUrl, "ws"),
3448
+ socket: options.socket ?? webSocketFactory({ origin }),
3449
+ greeting: () => [
3450
+ {
3451
+ type: "auth",
3452
+ token: token() ?? "",
3453
+ ...feed?.resumeFields(),
3454
+ session_without_check: true
3455
+ }
3456
+ ],
3457
+ afterGreeting: () => variablesFeed?.resume() ?? [],
3458
+ onError
3459
+ });
3460
+ feed = new SessionFeed(connection, onError);
3461
+ const session = feed;
3462
+ variablesFeed = new VariablesFeed(connection, http, onError, () => limits.get());
3463
+ const variables = variablesFeed;
3464
+ const run = new RunControl(session, http, onError, () => longRequestMs(limits.get()));
3465
+ const time = new TimeControl(
3466
+ session.session,
3467
+ session.ready,
3468
+ app.readonly(),
3469
+ http,
3470
+ options.answerTimeoutMs ?? ANSWER_TIMEOUT_MS,
3471
+ onError,
3472
+ variables.state
3473
+ );
3474
+ const binder = new VariableBinder({
3475
+ variables,
3476
+ connection: connection.state,
3477
+ time: time.state,
3478
+ session: session.session,
3479
+ onError
3480
+ });
3481
+ const call = (req, read2, after) => new Promise(
3482
+ (resolve, reject) => http(req, (outcome) => {
3483
+ if (!outcome.ok) {
3484
+ reject(outcome.error);
3485
+ return;
3486
+ }
3487
+ try {
3488
+ const value = read2(outcome.body);
3489
+ after?.(value);
3490
+ resolve(value);
3491
+ } catch (error) {
3492
+ reject(error);
3493
+ }
3494
+ })
3495
+ );
3496
+ return {
3497
+ connection: {
3498
+ state: connection.state,
3499
+ failures: connection.failures,
3500
+ lastClose: connection.lastClose,
3501
+ tryAgainReason: connection.tryAgainReason,
3502
+ onBatch: (listener) => connection.onBatch(listener),
3503
+ onUnreadable: (listener) => connection.onUnreadable(listener)
3504
+ },
3505
+ session: {
3506
+ session: session.session,
3507
+ ready: session.ready,
3508
+ lastEventAt: session.lastEventAt,
3509
+ notices: session.notices,
3510
+ rejected: session.rejected,
3511
+ incompatible: session.incompatible,
3512
+ onMessages: (listener) => session.onMessages(listener),
3513
+ report: (message, count2) => session.report(message, count2),
3514
+ dismissNotice: (id) => session.dismissNotice(id)
3515
+ },
3516
+ run: {
3517
+ starting: run.starting,
3518
+ stopping: run.stopping,
3519
+ stopWhileStarting: run.stopWhileStarting,
3520
+ error: run.error,
3521
+ start: (request) => run.start(request),
3522
+ stop: () => run.stop(),
3523
+ forceStop: () => run.forceStop()
3524
+ },
3525
+ time: {
3526
+ state: time.state,
3527
+ answerTimeoutMs: time.answerTimeoutMs,
3528
+ pause: () => time.pause(),
3529
+ resume: () => time.resume(),
3530
+ step: (ms) => time.step(ms),
3531
+ setSpeed: (value) => time.setSpeed(value),
3532
+ send: (command) => time.send(command)
3533
+ },
3534
+ variables: {
3535
+ state: variables.state,
3536
+ operations: variables.operations,
3537
+ watchProblem: variables.watchProblem,
3538
+ watch: (wanted, watchOptions) => variables.watch(wanted, watchOptions),
3539
+ write: (writes, writeOptions) => variables.write(writes, writeOptions),
3540
+ bind: (ref, bindOptions) => binder.bind(ref, bindOptions)
3541
+ },
3542
+ app: app.readonly(),
3543
+ limits: limits.readonly(),
3544
+ connect: () => {
3545
+ if (token() && !session.stopped) connection.connect();
3546
+ },
3547
+ close: () => {
3548
+ connection.close();
3549
+ time.dispose();
3550
+ variables.dispose();
3551
+ },
3552
+ loadApp: () => call({ method: "GET", path: "api/app" }, readAppInfo, (info) => app.set(info)),
3553
+ configs: () => call({ method: "GET", path: "api/configs" }, readConfigList),
3554
+ dashboard: (file) => call(
3555
+ { method: "GET", path: `api/dashboard?file=${encodeURIComponent(file)}` },
3556
+ readDashboardResponse
3557
+ ),
3558
+ scenarios: (file) => call(
3559
+ { method: "GET", path: `api/scenarios?file=${encodeURIComponent(file)}` },
3560
+ readScenarioList
3561
+ ),
3562
+ recording: () => call({ method: "GET", path: "api/recording" }, readRecording),
3563
+ check: (body) => call(
3564
+ {
3565
+ method: "POST",
3566
+ path: "api/check",
3567
+ body,
3568
+ timeoutMs: longRequestMs(limits.get())
3569
+ },
3570
+ readCheckResponse
3571
+ ),
3572
+ fetchSession: () => new Promise(
3573
+ (resolve, reject) => http({ method: "GET", path: "api/session" }, (outcome) => {
3574
+ if (!outcome.ok) {
3575
+ reject(outcome.error);
3576
+ return;
3577
+ }
3578
+ try {
3579
+ const summary = readSessionResponse(outcome.body);
3580
+ session.adopt(summary);
3581
+ variables.adoptSummary(outcome.body?.session);
3582
+ resolve(summary);
3583
+ } catch (error) {
3584
+ reject(error);
3585
+ }
3586
+ })
3587
+ )
3588
+ };
3589
+ }
3590
+
3591
+ // ../client/src/token.ts
3592
+ var TOKEN_STORAGE_KEY = "vehicle-sil-gui-token";
3593
+ function takeToken(place) {
3594
+ const storage = storageOf(place);
3595
+ const match = /(?:^#|&)token=([^&]*)/.exec(place.location.hash);
3596
+ if (!match) {
3597
+ return read(storage);
3598
+ }
3599
+ place.history.replaceState(
3600
+ place.history.state,
3601
+ "",
3602
+ place.location.pathname + place.location.search
3603
+ );
3604
+ let token;
3605
+ try {
3606
+ token = decodeURIComponent(match[1]) || null;
3607
+ } catch {
3608
+ token = null;
3609
+ }
3610
+ if (token === null) {
3611
+ return read(storage);
3612
+ }
3613
+ try {
3614
+ storage?.setItem(TOKEN_STORAGE_KEY, token);
3615
+ } catch {
3616
+ }
3617
+ return token;
3618
+ }
3619
+ function storageOf(place) {
3620
+ try {
3621
+ return place.sessionStorage ?? null;
3622
+ } catch {
3623
+ return null;
3624
+ }
3625
+ }
3626
+ function read(storage) {
3627
+ try {
3628
+ return storage?.getItem(TOKEN_STORAGE_KEY) ?? null;
3629
+ } catch {
3630
+ return null;
3631
+ }
3632
+ }
3633
+ export {
3634
+ ANSWER_TIMEOUT_MS,
3635
+ BATCH_MS,
3636
+ DEFAULT_LIMITS,
3637
+ DEFAULT_TIMEOUT_MS,
3638
+ DROPPED_MESSAGE,
3639
+ FEATURE_MANUAL,
3640
+ FEATURE_SCENARIO,
3641
+ FEATURE_SCENARIO_CONTROL,
3642
+ FEATURE_SPEED,
3643
+ FEATURE_START_PAUSED,
3644
+ FEATURE_TIME_COMMANDS,
3645
+ HISTORY_MAX,
3646
+ HISTORY_TOTAL_MAX,
3647
+ HttpError,
3648
+ OPERATIONS_KEPT,
3649
+ PHASES,
3650
+ PROTOCOL_VERSION,
3651
+ ProtocolError,
3652
+ TOKEN_STORAGE_KEY,
3653
+ TRY_AGAIN_LATER,
3654
+ WATCH_PERIODS_MS,
3655
+ WATCH_PERIOD_MS,
3656
+ WRITE_TIMEOUT_MS,
3657
+ WriteError,
3658
+ createClient,
3659
+ errorMessage,
3660
+ fetchTransport,
3661
+ hasRange,
3662
+ isWriteError,
3663
+ phaseIndex,
3664
+ readAppInfo,
3665
+ readCheckResponse,
3666
+ readConfigList,
3667
+ readDashboardResponse,
3668
+ readRecording,
3669
+ readScenarioList,
3670
+ readServerMessage,
3671
+ readSessionResponse,
3672
+ readTimeResponse,
3673
+ readVariablesSummary,
3674
+ readWriteResponse,
3675
+ runOutcome,
3676
+ severityRank,
3677
+ takeToken,
3678
+ valueCondition,
3679
+ webSocketFactory,
3680
+ writeBlock
3681
+ };