signalk-multihelm 0.3.0 → 0.5.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/plugin/index.js CHANGED
@@ -1,125 +1,17 @@
1
+ import fs from "node:fs";
1
2
  import os from "node:os";
2
- import { Type } from "typebox";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
3
5
  import makeMdns from "multicast-dns";
4
- import { isDeepStrictEqual } from "node:util";
5
- import fs from "node:fs";
6
6
  import http from "node:http";
7
7
  import https from "node:https";
8
8
  import { pipeline } from "node:stream/promises";
9
+ import { Type } from "typebox";
10
+ import { isDeepStrictEqual } from "node:util";
9
11
  import crypto from "node:crypto";
10
- import path from "node:path";
11
12
  import { Value } from "typebox/value";
12
13
  // src/api.ts
13
14
  var PROPERTY_NAME = "multihelm";
14
- // src/discovery.ts
15
- /**
16
- * Finds the other Signal K servers on the network, to offer them for pairing.
17
- *
18
- * Every Signal K server announces its REST API as `_signalk-http._tcp` (or
19
- * `_signalk-https._tcp`) over mDNS. The server's own discovery turns these
20
- * into data-connection suggestions only, so Multihelm asks for them itself
21
- * while it runs. Found servers are only shown; the user pairs with one.
22
- */
23
- var SERVICES = ["_signalk-http._tcp.local", "_signalk-https._tcp.local"];
24
- var QUERY_INTERVAL_MS = 3e4;
25
- /** A server not heard of for this long is dropped from the list. */
26
- var FORGET_AFTER_MS = 18e4;
27
- function txtRecord(answer) {
28
- const result = {};
29
- const data = Array.isArray(answer.data) ? answer.data : [answer.data];
30
- for (const entry of data) {
31
- const text = typeof entry === "string" ? entry : Buffer.from(entry).toString("utf-8");
32
- const eq = text.indexOf("=");
33
- if (eq > 0) result[text.slice(0, eq)] = text.slice(eq + 1);
34
- }
35
- return result;
36
- }
37
- function ownAddresses() {
38
- const result = /* @__PURE__ */ new Set();
39
- for (const list of Object.values(os.networkInterfaces())) for (const info of list ?? []) result.add(info.address);
40
- return result;
41
- }
42
- var ServerDiscovery = class {
43
- ownPort;
44
- mdns = null;
45
- timer = null;
46
- instances = /* @__PURE__ */ new Map();
47
- addresses = /* @__PURE__ */ new Map();
48
- found = /* @__PURE__ */ new Map();
49
- constructor(ownPort) {
50
- this.ownPort = ownPort;
51
- }
52
- start() {
53
- if (this.mdns) return;
54
- try {
55
- this.mdns = makeMdns();
56
- } catch {
57
- this.mdns = null;
58
- return;
59
- }
60
- this.mdns.on("response", (response) => {
61
- this.takeRecords([...response.answers, ...response.additionals]);
62
- });
63
- this.mdns.on("error", () => {});
64
- const query = () => {
65
- this.mdns?.query(SERVICES.map((name) => ({
66
- name,
67
- type: "PTR"
68
- })));
69
- };
70
- query();
71
- this.timer = setInterval(query, QUERY_INTERVAL_MS);
72
- }
73
- stop() {
74
- if (this.timer) {
75
- clearInterval(this.timer);
76
- this.timer = null;
77
- }
78
- this.mdns?.destroy();
79
- this.mdns = null;
80
- }
81
- list() {
82
- const now = Date.now();
83
- for (const [key, server] of this.found) if (now - server.lastSeen > FORGET_AFTER_MS) this.found.delete(key);
84
- return [...this.found.values()].sort((a, b) => a.name.localeCompare(b.name));
85
- }
86
- /** Fold in the records of one mDNS response. */
87
- takeRecords(records) {
88
- for (const record of records) if (record.type === "PTR" && SERVICES.includes(record.name)) {
89
- const instance = record.data;
90
- if (!this.instances.has(instance)) this.instances.set(instance, {
91
- service: record.name,
92
- txt: {}
93
- });
94
- }
95
- for (const record of records) if (record.type === "SRV") {
96
- const instance = this.instances.get(record.name);
97
- if (instance) {
98
- const srv = record.data;
99
- instance.target = srv.target;
100
- instance.port = srv.port;
101
- }
102
- } else if (record.type === "TXT") {
103
- const instance = this.instances.get(record.name);
104
- if (instance) instance.txt = txtRecord(record);
105
- } else if (record.type === "A") this.addresses.set(record.name, record.data);
106
- const own = ownAddresses();
107
- for (const [instance, info] of this.instances) {
108
- if (!info.target || info.port === void 0) continue;
109
- const address = this.addresses.get(info.target);
110
- if (!address) continue;
111
- if (own.has(address) && info.port === this.ownPort()) continue;
112
- const url = `${info.service.startsWith("_signalk-https") ? "https" : "http"}://${address}:${String(info.port)}`;
113
- const server = {
114
- name: instance.replace(`.${info.service}`, ""),
115
- url,
116
- lastSeen: Date.now()
117
- };
118
- if (info.txt.vname) server.vessel = info.txt.vname;
119
- this.found.set(url, server);
120
- }
121
- }
122
- };
123
15
  // src/peer-client.ts
124
16
  /**
125
17
  * HTTP client for a Multihelm peer: its routes, and the Signal K
@@ -131,6 +23,19 @@ var ServerDiscovery = class {
131
23
  */
132
24
  var ROUTE_PREFIX = "/plugins/signalk-multihelm";
133
25
  var REQUEST_TIMEOUT_MS$1 = 3e4;
26
+ function helloQuery(from) {
27
+ if (!from) return "";
28
+ const query = new URLSearchParams({
29
+ from: from.serverId,
30
+ name: from.name
31
+ });
32
+ if (from.signalk) query.set("signalk", from.signalk);
33
+ if (from.multihelm) query.set("multihelm", from.multihelm);
34
+ return `?${query.toString()}`;
35
+ }
36
+ function optionalText(value) {
37
+ return typeof value === "string" && value !== "" ? value : void 0;
38
+ }
134
39
  var PeerHttpError = class extends Error {
135
40
  status;
136
41
  constructor(status, message) {
@@ -189,16 +94,23 @@ function normalizePeerUrl(input) {
189
94
  if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password) return null;
190
95
  return `${url.protocol}//${url.host}`;
191
96
  }
192
- async function fetchHello(base, token) {
193
- const body = await getJson(`${base}${ROUTE_PREFIX}/hello`, token);
97
+ async function fetchHello(base, token, from) {
98
+ const body = await getJson(`${base}${ROUTE_PREFIX}/hello${helloQuery(from)}`, token);
194
99
  if (typeof body.serverId !== "string" || typeof body.protocol !== "number") throw new Error(`${base} did not answer as a Multihelm peer`);
195
- return {
100
+ const hello = {
196
101
  serverId: body.serverId,
197
102
  name: typeof body.name === "string" ? body.name : base,
198
103
  protocol: body.protocol,
199
104
  datasets: Array.isArray(body.datasets) ? body.datasets.filter((d) => typeof d === "string") : [],
200
105
  master: body.master === true
201
106
  };
107
+ const signalk = optionalText(body.signalk);
108
+ const multihelm = optionalText(body.multihelm);
109
+ return {
110
+ ...hello,
111
+ ...signalk ? { signalk } : {},
112
+ ...multihelm ? { multihelm } : {}
113
+ };
202
114
  }
203
115
  async function fetchVesselSettings(base, token) {
204
116
  return getJson(`${base}${ROUTE_PREFIX}/vessel-settings`, token);
@@ -301,7 +213,218 @@ function interpretReply(raw) {
301
213
  message: "unexpected access request reply"
302
214
  };
303
215
  }
216
+ // src/discovery.ts
217
+ /**
218
+ * Finds the other Signal K servers on the network, to offer them for pairing.
219
+ *
220
+ * Every Signal K server announces its REST API as `_signalk-http._tcp` (or
221
+ * `_signalk-https._tcp`) over mDNS. The server's own discovery turns these
222
+ * into data-connection suggestions only, so Multihelm asks for them itself
223
+ * while it runs. Found servers are only shown; the user pairs with one.
224
+ */
225
+ var SERVICES = ["_signalk-http._tcp.local", "_signalk-https._tcp.local"];
226
+ var QUERY_INTERVAL_MS = 3e4;
227
+ /** A server not heard of for this long is dropped from the list. */
228
+ var FORGET_AFTER_MS = 18e4;
229
+ function txtRecord(answer) {
230
+ const result = {};
231
+ const data = Array.isArray(answer.data) ? answer.data : [answer.data];
232
+ for (const entry of data) {
233
+ const text = typeof entry === "string" ? entry : Buffer.from(entry).toString("utf-8");
234
+ const eq = text.indexOf("=");
235
+ if (eq > 0) result[text.slice(0, eq)] = text.slice(eq + 1);
236
+ }
237
+ return result;
238
+ }
239
+ function ownAddresses() {
240
+ const result = /* @__PURE__ */ new Set();
241
+ for (const list of Object.values(os.networkInterfaces())) for (const info of list ?? []) result.add(info.address);
242
+ return result;
243
+ }
244
+ var ServerDiscovery = class {
245
+ ownPort;
246
+ mdns = null;
247
+ timer = null;
248
+ instances = /* @__PURE__ */ new Map();
249
+ addresses = /* @__PURE__ */ new Map();
250
+ found = /* @__PURE__ */ new Map();
251
+ constructor(ownPort) {
252
+ this.ownPort = ownPort;
253
+ }
254
+ start() {
255
+ if (this.mdns) return;
256
+ try {
257
+ this.mdns = makeMdns();
258
+ } catch {
259
+ this.mdns = null;
260
+ return;
261
+ }
262
+ this.mdns.on("response", (response) => {
263
+ this.takeRecords([...response.answers, ...response.additionals]);
264
+ });
265
+ this.mdns.on("error", () => {});
266
+ const query = () => {
267
+ this.mdns?.query(SERVICES.map((name) => ({
268
+ name,
269
+ type: "PTR"
270
+ })));
271
+ };
272
+ query();
273
+ this.timer = setInterval(query, QUERY_INTERVAL_MS);
274
+ }
275
+ stop() {
276
+ if (this.timer) {
277
+ clearInterval(this.timer);
278
+ this.timer = null;
279
+ }
280
+ this.mdns?.destroy();
281
+ this.mdns = null;
282
+ }
283
+ list() {
284
+ const now = Date.now();
285
+ for (const [key, server] of this.found) if (now - server.lastSeen > FORGET_AFTER_MS) this.found.delete(key);
286
+ return [...this.found.values()].sort((a, b) => a.name.localeCompare(b.name));
287
+ }
288
+ /** Fold in the records of one mDNS response. */
289
+ takeRecords(records) {
290
+ for (const record of records) if (record.type === "PTR" && SERVICES.includes(record.name)) {
291
+ const instance = record.data;
292
+ if (!this.instances.has(instance)) this.instances.set(instance, {
293
+ service: record.name,
294
+ txt: {}
295
+ });
296
+ }
297
+ for (const record of records) if (record.type === "SRV") {
298
+ const instance = this.instances.get(record.name);
299
+ if (instance) {
300
+ const srv = record.data;
301
+ instance.target = srv.target;
302
+ instance.port = srv.port;
303
+ }
304
+ } else if (record.type === "TXT") {
305
+ const instance = this.instances.get(record.name);
306
+ if (instance) instance.txt = txtRecord(record);
307
+ } else if (record.type === "A") this.addresses.set(record.name, record.data);
308
+ const own = ownAddresses();
309
+ for (const [instance, info] of this.instances) {
310
+ if (!info.target || info.port === void 0) continue;
311
+ const address = this.addresses.get(info.target);
312
+ if (!address) continue;
313
+ if (own.has(address) && info.port === this.ownPort()) continue;
314
+ const url = normalizePeerUrl(`${info.service.startsWith("_signalk-https") ? "https" : "http"}://${address}:${String(info.port)}`);
315
+ if (!url) continue;
316
+ const server = {
317
+ name: instance.replace(`.${info.service}`, ""),
318
+ url,
319
+ lastSeen: Date.now()
320
+ };
321
+ if (info.txt.vname) server.vessel = info.txt.vname;
322
+ this.found.set(url, server);
323
+ }
324
+ }
325
+ };
326
+ // src/config.ts
327
+ var ConfigSchema = Type.Object({
328
+ master: Type.Boolean({
329
+ title: "This server is the boat's master",
330
+ description: "Set this on one server only. Plugins that run on the master alone run here, and the other servers use them through this one.",
331
+ default: false
332
+ }),
333
+ followVessel: Type.Boolean({
334
+ title: "Take the vessel data over from the master",
335
+ description: "Name, MMSI, call sign, dimensions and ship type from Server -> Settings. Changes made here are replaced by the master's.",
336
+ default: true
337
+ }),
338
+ followMetadata: Type.Boolean({
339
+ title: "Take the path metadata over from the master",
340
+ description: "Display names, units, zones and alarm limits set for paths. Changes made here are replaced by the master's.",
341
+ default: true
342
+ }),
343
+ followSourcePriorities: Type.Boolean({
344
+ title: "Take the source priorities over from the master",
345
+ description: "Which source wins for a path, from Data -> Source Priorities. They name sources by connection, so give the NMEA 2000 bus the same connection name on every server. Changes made here are replaced by the master's.",
346
+ default: true
347
+ }),
348
+ historyFromMaster: Type.Boolean({
349
+ title: "Answer this server's History API from the master",
350
+ description: "While the master has a history provider (signalk-questdb, for example), history graphs on this server show the master's history, so it is kept once on the boat. Does nothing on the master, while the master has no history, or before Signal K 2.32.0.",
351
+ default: true
352
+ })
353
+ });
354
+ // src/source-priorities.ts
355
+ function isRecord$1(value) {
356
+ return typeof value === "object" && value !== null && !Array.isArray(value);
357
+ }
358
+ function isText(value) {
359
+ return typeof value === "string" && value !== "";
360
+ }
361
+ function group(value) {
362
+ if (!isRecord$1(value) || !isText(value.id) || !Array.isArray(value.sources) || !value.sources.every(isText) || value.inactive !== void 0 && typeof value.inactive !== "boolean") return null;
363
+ const sources = value.sources;
364
+ return value.inactive === void 0 ? {
365
+ id: value.id,
366
+ sources
367
+ } : {
368
+ id: value.id,
369
+ sources,
370
+ inactive: value.inactive
371
+ };
372
+ }
373
+ /** The server takes a timeout as an integer or a string of one, and keeps a number. */
374
+ function entry(value) {
375
+ if (!isRecord$1(value) || !isText(value.sourceRef)) return null;
376
+ const timeout = typeof value.timeout === "string" && /^-?\d+$/.test(value.timeout) ? Number(value.timeout) : value.timeout;
377
+ return typeof timeout === "number" && Number.isInteger(timeout) ? {
378
+ sourceRef: value.sourceRef,
379
+ timeout
380
+ } : null;
381
+ }
382
+ function allOrNull(items, parse) {
383
+ const parsed = items.map(parse);
384
+ return parsed.every((item) => item !== null) ? parsed : null;
385
+ }
386
+ /**
387
+ * Null unless every part has the shape above: a priorities list cut short
388
+ * would replace a server's whole set with less than the master meant.
389
+ */
390
+ function parseSourcePriorities(raw) {
391
+ if (!isRecord$1(raw) || !Array.isArray(raw.groups) || !isRecord$1(raw.overrides)) return null;
392
+ const groups = allOrNull(raw.groups, group);
393
+ const overrides = {};
394
+ for (const [path, list] of Object.entries(raw.overrides)) {
395
+ const entries = Array.isArray(list) ? allOrNull(list, entry) : null;
396
+ if (!entries) return null;
397
+ overrides[path] = entries;
398
+ }
399
+ const defaults = raw.defaults ?? {};
400
+ if (!groups || !isRecord$1(defaults)) return null;
401
+ const { fallbackMs } = defaults;
402
+ if (fallbackMs === void 0) return {
403
+ groups,
404
+ overrides,
405
+ defaults: {}
406
+ };
407
+ return typeof fallbackMs === "number" && fallbackMs > 0 && Number.isFinite(fallbackMs) ? {
408
+ groups,
409
+ overrides,
410
+ defaults: { fallbackMs }
411
+ } : null;
412
+ }
413
+ /** What this server holds in its settings, read the way `/skServer/priorities` answers. */
414
+ function sourcePrioritiesFromSettings(settings) {
415
+ return parseSourcePriorities({
416
+ groups: settings.priorityGroups ?? [],
417
+ overrides: settings.priorityOverrides ?? {},
418
+ defaults: settings.priorityDefaults ?? {}
419
+ });
420
+ }
304
421
  // src/vessel-settings.ts
422
+ /**
423
+ * What the user set for this vessel on the server: the vessel data from
424
+ * Server -> Settings and the metadata set for paths (display names, units,
425
+ * zones). The server keeps both as its base deltas, sent again at every
426
+ * start; they are the self vessel's part of those deltas.
427
+ */
305
428
  var VESSEL_FIELDS = [
306
429
  "name",
307
430
  "mmsi",
@@ -395,46 +518,104 @@ function parseVesselSettings(raw) {
395
518
  }
396
519
  const meta = {};
397
520
  for (const [path, value] of Object.entries(raw.meta)) if (isMetaPath(path) && isRecord(value)) meta[path] = value;
398
- return {
521
+ const priorities = parseSourcePriorities(raw.priorities);
522
+ return priorities ? {
523
+ vessel,
524
+ meta,
525
+ priorities
526
+ } : {
399
527
  vessel,
400
528
  meta
401
529
  };
402
530
  }
403
531
  // src/follow-master.ts
404
532
  /**
405
- * On a server that is not the master: takes the vessel data and path
406
- * metadata over from the master. They are read from the master with the
407
- * pairing token and written here through this server's own REST API, the
408
- * way its settings pages write them, so they survive a restart. Writing
409
- * needs an admin device token on this server, asked for once; until it is
410
- * approved nothing is written.
533
+ * On a server that is not the master: takes the vessel data, path metadata
534
+ * and source priorities over from the master. They are read from the
535
+ * master with the pairing token and written here through this server's own
536
+ * REST API, the way its settings pages write them, so they survive a
537
+ * restart. Writing needs an admin device token on this server, asked for
538
+ * once; until it is approved nothing is written. Metadata of a path the
539
+ * master has none for stays as it is, unless it was the master's before.
411
540
  */
412
541
  function errorText$2(error) {
413
542
  return error instanceof Error ? error.message : String(error);
414
543
  }
544
+ /** A master where none are set yet would wipe the ones a server kept from before Multihelm. */
545
+ function hasPriorities(priorities) {
546
+ return priorities.groups.length > 0 || Object.keys(priorities.overrides).length > 0;
547
+ }
548
+ /**
549
+ * What was last written here and what this server kept of it, seen a round
550
+ * later. A server may keep a value differently from how it was written (a
551
+ * base delta file with the same path twice keeps the older one in force), so
552
+ * a value is not written again until the master's or this server's changes.
553
+ */
554
+ var WrittenValues = class {
555
+ written = /* @__PURE__ */ new Map();
556
+ /** Whether `target` is to be written over `local`. */
557
+ due(key, target, local) {
558
+ if (isDeepStrictEqual(target, local)) {
559
+ this.written.delete(key);
560
+ return false;
561
+ }
562
+ const last = this.written.get(key);
563
+ if (last && isDeepStrictEqual(last.target, target)) {
564
+ if (!last.kept) {
565
+ last.kept = { value: local };
566
+ return false;
567
+ }
568
+ if (isDeepStrictEqual(last.kept.value, local)) return false;
569
+ }
570
+ return true;
571
+ }
572
+ wrote(key, target) {
573
+ this.written.set(key, { target });
574
+ }
575
+ /** What is not looked at in a round may have changed meanwhile, so it is forgotten. */
576
+ keepOnly(keys) {
577
+ for (const key of this.written.keys()) if (!keys.has(key)) this.written.delete(key);
578
+ }
579
+ };
415
580
  function metaUrl(base, path) {
416
581
  return `${base}/signalk/v1/api/vessels/self/${path.split(".").map((s) => encodeURIComponent(s)).join("/")}/meta`;
417
582
  }
418
583
  var MasterFollower = class {
419
584
  host;
420
585
  access;
586
+ prioritiesWritten = new WrittenValues();
587
+ metaWritten = new WrittenValues();
588
+ /**
589
+ * The paths whose metadata is the master's: all it has, and the ones it
590
+ * had until they are gone here too.
591
+ */
592
+ followedMeta;
593
+ /** The list as last saved; a failed save is tried again the next round. */
594
+ followedMetaSaved;
421
595
  constructor(host) {
422
596
  this.host = host;
423
597
  this.access = host.store.loadOwnAccess();
598
+ const followed = host.store.loadFollowedMeta();
599
+ this.followedMeta = new Set(followed);
600
+ this.followedMetaSaved = JSON.stringify(followed.sort());
424
601
  }
425
602
  /** Whether the user has to approve this server's own access request. */
426
603
  waitingForApproval() {
427
604
  return this.access.state === "waiting-approval";
428
605
  }
606
+ /** The identifier of the access request on this server, as Security -> Access Requests lists it. */
607
+ accessRequestId() {
608
+ return `signalk-multihelm-self-${this.host.serverId}`;
609
+ }
429
610
  /** Whether the user denied it; it is asked for again only after a restart. */
430
611
  denied() {
431
612
  return this.access.state === "denied";
432
613
  }
433
614
  async run() {
434
- const { followVessel, followMeta } = this.host;
615
+ const { followVessel, followMeta, followPriorities } = this.host;
435
616
  const master = this.host.master();
436
617
  const local = this.host.localSettings();
437
- if (!followVessel && !followMeta || !master || !local) return;
618
+ if (!followVessel && !followMeta && !followPriorities || !master || !local) return;
438
619
  let remote;
439
620
  try {
440
621
  remote = parseVesselSettings(await fetchVesselSettings(master.url, master.token));
@@ -444,8 +625,14 @@ var MasterFollower = class {
444
625
  }
445
626
  if (!remote) return;
446
627
  const vesselChanged = followVessel && VESSEL_FIELDS.some((k) => remote.vessel[k] !== local.vessel[k]);
447
- const metaChanged = followMeta ? [.../* @__PURE__ */ new Set([...Object.keys(remote.meta), ...Object.keys(local.meta)])].filter((p) => !isDeepStrictEqual(remote.meta[p], local.meta[p])) : [];
448
- if (!vesselChanged && metaChanged.length === 0) return;
628
+ if (followMeta) {
629
+ this.followedMeta = /* @__PURE__ */ new Set([...Object.keys(remote.meta), ...[...this.followedMeta].filter((p) => local.meta[p] !== void 0)]);
630
+ this.metaWritten.keepOnly(this.followedMeta);
631
+ this.saveFollowedMeta();
632
+ }
633
+ const metaChanged = followMeta ? [...this.followedMeta].filter((p) => this.metaWritten.due(p, remote.meta[p], local.meta[p])) : [];
634
+ const priorities = followPriorities ? this.prioritiesToWrite(remote.priorities, local.priorities) : null;
635
+ if (!vesselChanged && metaChanged.length === 0 && !priorities) return;
449
636
  const token = await this.ownToken();
450
637
  if (token === null) return;
451
638
  const base = this.host.ownUrl();
@@ -454,6 +641,11 @@ var MasterFollower = class {
454
641
  for (const path of metaChanged) {
455
642
  const value = remote.meta[path];
456
643
  await (value === void 0 ? callServer("DELETE", metaUrl(base, path), token) : callServer("PUT", metaUrl(base, path), token, { value }));
644
+ this.metaWritten.wrote(path, value);
645
+ }
646
+ if (priorities) {
647
+ await callServer("PUT", `${base}/skServer/priorities`, token, priorities);
648
+ this.prioritiesWritten.wrote("", priorities);
457
649
  }
458
650
  } catch (error) {
459
651
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.setAccess({
@@ -462,6 +654,22 @@ var MasterFollower = class {
462
654
  });
463
655
  this.host.error(`Multihelm: taking over the master's vessel settings: ${errorText$2(error)}`);
464
656
  }
657
+ if (followMeta) this.saveFollowedMeta();
658
+ }
659
+ saveFollowedMeta() {
660
+ const paths = [...this.followedMeta].sort();
661
+ const text = JSON.stringify(paths);
662
+ if (text === this.followedMetaSaved) return;
663
+ try {
664
+ this.host.store.saveFollowedMeta(paths);
665
+ this.followedMetaSaved = text;
666
+ } catch (error) {
667
+ this.host.error(`Multihelm: saving the paths that follow the master: ${errorText$2(error)}`);
668
+ }
669
+ }
670
+ prioritiesToWrite(remote, local) {
671
+ if (!remote || !hasPriorities(remote) || !local) return null;
672
+ return this.prioritiesWritten.due("", remote, local) ? remote : null;
465
673
  }
466
674
  /** The vessel route writes every field, so the ones that stay here are sent back as they are. */
467
675
  async writeVessel(base, token, vessel) {
@@ -480,7 +688,7 @@ var MasterFollower = class {
480
688
  if (this.access.state === "denied") return null;
481
689
  let result;
482
690
  try {
483
- result = this.access.state === "waiting-approval" && this.access.requestHref ? await pollAccess(base, this.access.requestHref) : await requestAccess(base, `signalk-multihelm-self-${this.host.serverId}`, "Multihelm: take the vessel settings over from the master", "admin");
691
+ result = this.access.state === "waiting-approval" && this.access.requestHref ? await pollAccess(base, this.access.requestHref) : await requestAccess(base, this.accessRequestId(), "Multihelm: take the vessel settings over from the master", "admin");
484
692
  } catch (error) {
485
693
  this.host.debug(`Multihelm: access request on this server: ${errorText$2(error)}`);
486
694
  return null;
@@ -958,7 +1166,19 @@ var ROUND_INTERVAL_MS = 6e4;
958
1166
  * on a timer of its own, so a long round of transfers does not hold it up.
959
1167
  */
960
1168
  var MASTER_CHECK_INTERVAL_MS = 3e4;
961
- 5 * MASTER_CHECK_INTERVAL_MS;
1169
+ /**
1170
+ * A peer set to be the master counts as the master while it answered this
1171
+ * recently, so a few missed answers do not move the role.
1172
+ */
1173
+ var MASTER_STALE_MS = 5 * MASTER_CHECK_INTERVAL_MS;
1174
+ /** Every peer asks every 30 s, so a sighting is saved only now and then. */
1175
+ var PAIRED_BY_SAVE_MS = 6e5;
1176
+ /** Without security anyone may ask, so writes of that list are gathered, never one per request. */
1177
+ var PAIRED_BY_FLUSH_MS = 1e4;
1178
+ /** Without security anyone may ask for `hello`; the list stays small. */
1179
+ var MAX_PAIRED_BY = 32;
1180
+ /** A pairing request waiting for approval is followed this often, so an approval shows at once. */
1181
+ var PAIRING_POLL_MS = 5e3;
962
1182
  async function hashFile(file) {
963
1183
  const hash = crypto.createHash("sha256");
964
1184
  await pipeline(fs.createReadStream(file), hash);
@@ -967,6 +1187,16 @@ async function hashFile(file) {
967
1187
  function errorText$1(error) {
968
1188
  return error instanceof Error ? error.message : String(error);
969
1189
  }
1190
+ /** Said without the address, which the panel shows anyway. */
1191
+ function helloErrorText(error) {
1192
+ if (!(error instanceof PeerHttpError)) return errorText$1(error);
1193
+ switch (error.status) {
1194
+ case 404: return "Multihelm is not running there";
1195
+ case 401:
1196
+ case 403: return "access was revoked on the peer";
1197
+ default: return `HTTP ${String(error.status)}`;
1198
+ }
1199
+ }
970
1200
  function toListed(entry) {
971
1201
  return {
972
1202
  key: entry.key,
@@ -992,6 +1222,14 @@ var Multihelm = class {
992
1222
  stopped = false;
993
1223
  /** Peer URL → when it last answered as set to be the master. */
994
1224
  masterSeen = /* @__PURE__ */ new Map();
1225
+ /** Peer URL → its last `hello`, and when. */
1226
+ answers = /* @__PURE__ */ new Map();
1227
+ /** Peer URL → why its last `hello` failed. */
1228
+ helloErrors = /* @__PURE__ */ new Map();
1229
+ /** Server id → a server that asks this one for its `hello`. */
1230
+ pairedBy;
1231
+ pairedBySavedAt = 0;
1232
+ pairedByTimer = null;
995
1233
  roleListeners = /* @__PURE__ */ new Set();
996
1234
  statusListeners = /* @__PURE__ */ new Set();
997
1235
  /** What the role listeners were last told: role and master id. */
@@ -1000,12 +1238,15 @@ var Multihelm = class {
1000
1238
  announcedStatus = "";
1001
1239
  masterTimer = null;
1002
1240
  checkingMasters = false;
1241
+ pairingTimer = null;
1242
+ pollingPairings = false;
1003
1243
  serverId;
1004
1244
  constructor(store, host) {
1005
1245
  this.store = store;
1006
1246
  this.host = host;
1007
1247
  this.peers = store.loadPeers();
1008
1248
  this.serverId = store.serverId();
1249
+ this.pairedBy = new Map(store.loadPairedBy().map((s) => [s.id, s]));
1009
1250
  }
1010
1251
  start() {
1011
1252
  this.started = true;
@@ -1019,6 +1260,11 @@ var Multihelm = class {
1019
1260
  this.masterTimer = setInterval(() => {
1020
1261
  this.checkMasters();
1021
1262
  }, MASTER_CHECK_INTERVAL_MS);
1263
+ this.pairingTimer = setInterval(() => {
1264
+ this.pollPairings().catch((error) => {
1265
+ this.host.error(`Multihelm: following a pairing request: ${errorText$1(error)}`);
1266
+ });
1267
+ }, PAIRING_POLL_MS);
1022
1268
  }
1023
1269
  stop() {
1024
1270
  this.started = false;
@@ -1026,14 +1272,18 @@ var Multihelm = class {
1026
1272
  for (const timer of [this.timer, this.soon]) if (timer) clearTimeout(timer);
1027
1273
  this.timer = null;
1028
1274
  this.soon = null;
1029
- if (this.masterTimer) {
1030
- clearInterval(this.masterTimer);
1031
- this.masterTimer = null;
1275
+ for (const timer of [this.masterTimer, this.pairingTimer]) if (timer) clearInterval(timer);
1276
+ this.masterTimer = null;
1277
+ this.pairingTimer = null;
1278
+ if (this.pairedByTimer) {
1279
+ clearTimeout(this.pairedByTimer);
1280
+ this.pairedByTimer = null;
1281
+ this.savePairedBy();
1032
1282
  }
1033
1283
  }
1034
1284
  /**
1035
1285
  * Asks every paired peer whether it is set to be the master. Runs outside
1036
- * the work queue and touches nothing but `masterSeen`, so it neither waits
1286
+ * the work queue and touches nothing but what it keeps of the answers, so it neither waits
1037
1287
  * for a round nor races one.
1038
1288
  */
1039
1289
  async checkMasters() {
@@ -1043,11 +1293,13 @@ var Multihelm = class {
1043
1293
  await Promise.all(this.peers.filter((p) => p.state === "paired" && p.id !== "").map(async (peer) => {
1044
1294
  let hello;
1045
1295
  try {
1046
- hello = await fetchHello(peer.url, peer.token);
1047
- } catch {
1296
+ hello = await fetchHello(peer.url, peer.token, this.helloFrom());
1297
+ } catch (error) {
1298
+ if (!this.stopped && this.peers.includes(peer)) this.helloErrors.set(peer.url, helloErrorText(error));
1048
1299
  return;
1049
1300
  }
1050
1301
  if (this.stopped || !this.peers.includes(peer) || hello.serverId !== peer.id) return;
1302
+ this.answered(peer.url, hello);
1051
1303
  if (hello.master) this.masterSeen.set(peer.url, Date.now());
1052
1304
  else this.masterSeen.delete(peer.url);
1053
1305
  }));
@@ -1056,6 +1308,30 @@ var Multihelm = class {
1056
1308
  }
1057
1309
  if (!this.stopped) this.announceRole();
1058
1310
  }
1311
+ /**
1312
+ * Follows up the pairing requests waiting for approval, between rounds. At
1313
+ * most one waits in the queue, so a long round does not pile them up.
1314
+ */
1315
+ async pollPairings() {
1316
+ const waiting = () => this.peers.filter((p) => p.state === "waiting-approval");
1317
+ if (this.pollingPairings || this.stopped || waiting().length === 0) return;
1318
+ this.pollingPairings = true;
1319
+ try {
1320
+ await this.serialize(async () => {
1321
+ let paired = false;
1322
+ for (const peer of waiting()) {
1323
+ if (this.stopped) break;
1324
+ await this.pollPairingLocked(peer);
1325
+ paired ||= peer.state === "paired";
1326
+ }
1327
+ this.store.savePeers(this.peers);
1328
+ this.announceRole();
1329
+ if (paired) this.changedSoon();
1330
+ });
1331
+ } finally {
1332
+ this.pollingPairings = false;
1333
+ }
1334
+ }
1059
1335
  /** Run `task` after every task queued before it. */
1060
1336
  serialize(task) {
1061
1337
  const run = this.queue.then(task, task);
@@ -1209,9 +1485,83 @@ var Multihelm = class {
1209
1485
  name: this.host.serverName(),
1210
1486
  protocol: 1,
1211
1487
  datasets: this.datasetIds(),
1212
- master: this.host.isMaster()
1488
+ master: this.host.isMaster(),
1489
+ ...this.versions()
1213
1490
  };
1214
1491
  }
1492
+ versions() {
1493
+ const { signalk, multihelm } = this.host.versions?.() ?? {};
1494
+ return {
1495
+ ...signalk ? { signalk } : {},
1496
+ ...multihelm ? { multihelm } : {}
1497
+ };
1498
+ }
1499
+ helloFrom() {
1500
+ return {
1501
+ serverId: this.serverId,
1502
+ name: this.host.serverName(),
1503
+ ...this.versions()
1504
+ };
1505
+ }
1506
+ answered(url, hello) {
1507
+ this.answers.set(url, {
1508
+ at: Date.now(),
1509
+ hello
1510
+ });
1511
+ this.helloErrors.delete(url);
1512
+ }
1513
+ /**
1514
+ * Notes a server that asked for this one's `hello`. Its last sighting is
1515
+ * saved with any change to what it is, and otherwise once in a while.
1516
+ */
1517
+ sawPairedServer(from) {
1518
+ if (from.serverId === this.serverId) return;
1519
+ const now = Date.now();
1520
+ const known = this.pairedBy.get(from.serverId);
1521
+ const server = {
1522
+ id: from.serverId,
1523
+ name: from.name,
1524
+ ...from.signalk ? { signalk: from.signalk } : {},
1525
+ ...from.multihelm ? { multihelm: from.multihelm } : {},
1526
+ lastSeen: now
1527
+ };
1528
+ this.pairedBy.set(server.id, server);
1529
+ if (this.pairedBy.size > MAX_PAIRED_BY) {
1530
+ const oldest = [...this.pairedBy.values()].sort((x, y) => x.lastSeen - y.lastSeen)[0];
1531
+ if (oldest) this.pairedBy.delete(oldest.id);
1532
+ }
1533
+ if (!known || known.name !== server.name || known.signalk !== server.signalk || known.multihelm !== server.multihelm || now - this.pairedBySavedAt >= PAIRED_BY_SAVE_MS) this.savePairedBySoon();
1534
+ }
1535
+ /** The servers paired with this one, by name. */
1536
+ pairedByInfo() {
1537
+ const now = Date.now();
1538
+ return [...this.pairedBy.values()].sort((x, y) => x.name.localeCompare(y.name)).map((s) => ({
1539
+ ...s,
1540
+ online: now - s.lastSeen <= MASTER_STALE_MS
1541
+ }));
1542
+ }
1543
+ /** Drops a server from that list; it comes back when it asks again. */
1544
+ forgetPairedBy(id) {
1545
+ const removed = this.pairedBy.delete(id);
1546
+ if (removed) this.savePairedBy();
1547
+ return removed;
1548
+ }
1549
+ savePairedBySoon() {
1550
+ if (this.pairedByTimer) return;
1551
+ this.pairedByTimer = setTimeout(() => {
1552
+ this.pairedByTimer = null;
1553
+ this.savePairedBy();
1554
+ }, PAIRED_BY_FLUSH_MS);
1555
+ this.pairedByTimer.unref();
1556
+ }
1557
+ savePairedBy() {
1558
+ this.pairedBySavedAt = Date.now();
1559
+ try {
1560
+ this.store.savePairedBy([...this.pairedBy.values()]);
1561
+ } catch (error) {
1562
+ this.host.error(`Multihelm: saving the servers paired with this one: ${errorText$1(error)}`);
1563
+ }
1564
+ }
1215
1565
  manifest(datasetId, since) {
1216
1566
  const dataset = this.datasets.get(datasetId);
1217
1567
  return dataset ? manifestSince(dataset.library, since) : null;
@@ -1226,14 +1576,18 @@ var Multihelm = class {
1226
1576
  if (!file?.sha256 || !local || local.size !== file.size || local.mtimeMs !== file.mtimeMs) return null;
1227
1577
  return local.path;
1228
1578
  }
1579
+ /** Errors with one dataset are cleared by that dataset's next sync. */
1580
+ isDatasetError(text) {
1581
+ return [...this.datasets.keys()].some((id) => text.startsWith(`${id}:`));
1582
+ }
1229
1583
  async syncPeerLocked(peer) {
1230
1584
  try {
1231
1585
  for (const dataset of this.datasets.values()) {
1232
1586
  if (this.stopped) return;
1233
1587
  await this.syncDatasetLocked(peer, dataset);
1234
1588
  }
1235
- peer.lastSeen = Date.now();
1236
1589
  peer.lastSync = Date.now();
1590
+ if (peer.lastError !== void 0 && !this.isDatasetError(peer.lastError)) delete peer.lastError;
1237
1591
  } catch (error) {
1238
1592
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {
1239
1593
  peer.state = "needs-pairing";
@@ -1248,7 +1602,10 @@ var Multihelm = class {
1248
1602
  try {
1249
1603
  manifest = await fetchManifest(peer.url, peer.token, id, peer.cursors[id] ?? 0);
1250
1604
  } catch (error) {
1251
- if (error instanceof PeerHttpError && error.status === 404) return;
1605
+ if (error instanceof PeerHttpError && error.status === 404) {
1606
+ if (peer.lastError?.startsWith(`${id}:`)) delete peer.lastError;
1607
+ return;
1608
+ }
1252
1609
  throw error;
1253
1610
  }
1254
1611
  try {
@@ -1386,8 +1743,18 @@ var Multihelm = class {
1386
1743
  if (p.lastSeen !== void 0) info.lastSeen = p.lastSeen;
1387
1744
  if (p.lastSync !== void 0) info.lastSync = p.lastSync;
1388
1745
  if (p.lastError !== void 0) info.lastError = p.lastError;
1746
+ const now = Date.now();
1747
+ const answer = this.answers.get(p.url);
1748
+ if (answer) {
1749
+ info.lastSeen = Math.max(info.lastSeen ?? 0, answer.at);
1750
+ if (answer.hello.signalk) info.signalk = answer.hello.signalk;
1751
+ if (answer.hello.multihelm) info.multihelm = answer.hello.multihelm;
1752
+ }
1753
+ const helloError = this.helloErrors.get(p.url);
1754
+ if (helloError !== void 0 && p.state === "paired") info.lastError = helloError;
1755
+ if (p.state === "paired") info.online = info.lastSeen !== void 0 && now - info.lastSeen <= 15e4;
1389
1756
  const seen = this.masterSeen.get(p.url);
1390
- if (seen !== void 0 && Date.now() - seen <= 15e4) info.master = true;
1757
+ if (seen !== void 0 && now - seen <= 15e4) info.master = true;
1391
1758
  return info;
1392
1759
  }
1393
1760
  /**
@@ -1425,6 +1792,8 @@ var Multihelm = class {
1425
1792
  const before = this.peers.length;
1426
1793
  this.peers = this.peers.filter((p) => p.url !== url);
1427
1794
  this.masterSeen.delete(url);
1795
+ this.answers.delete(url);
1796
+ this.helloErrors.delete(url);
1428
1797
  this.store.savePeers(this.peers);
1429
1798
  this.announceRole();
1430
1799
  return Promise.resolve(this.peers.length !== before);
@@ -1468,7 +1837,7 @@ var Multihelm = class {
1468
1837
  }
1469
1838
  async helloLocked(peer) {
1470
1839
  try {
1471
- const hello = await fetchHello(peer.url, peer.token);
1840
+ const hello = await fetchHello(peer.url, peer.token, this.helloFrom());
1472
1841
  if (hello.serverId === this.serverId) {
1473
1842
  peer.state = "needs-pairing";
1474
1843
  peer.lastError = "this is this server itself";
@@ -1477,10 +1846,11 @@ var Multihelm = class {
1477
1846
  peer.id = hello.serverId;
1478
1847
  peer.name = hello.name;
1479
1848
  peer.lastSeen = Date.now();
1849
+ this.answered(peer.url, hello);
1480
1850
  if (hello.master) this.masterSeen.set(peer.url, peer.lastSeen);
1481
1851
  else this.masterSeen.delete(peer.url);
1482
1852
  } catch (error) {
1483
- peer.lastError = error instanceof PeerHttpError && error.status === 404 ? "Multihelm is not running there" : errorText$1(error);
1853
+ this.helloErrors.set(peer.url, helloErrorText(error));
1484
1854
  }
1485
1855
  }
1486
1856
  };
@@ -1490,10 +1860,26 @@ function queryString(req, name) {
1490
1860
  const value = req.query[name];
1491
1861
  return typeof value === "string" ? value : "";
1492
1862
  }
1863
+ var SERVER_ID = /^[\w-]{1,64}$/;
1864
+ var VERSION = /^[\w.+-]{1,32}$/;
1865
+ /** The server asking, when it said; what does not fit is left out. */
1866
+ function helloFrom(req) {
1867
+ const serverId = queryString(req, "from");
1868
+ const name = queryString(req, "name").trim().slice(0, 100);
1869
+ if (!SERVER_ID.test(serverId) || name === "") return null;
1870
+ const signalk = queryString(req, "signalk");
1871
+ const multihelm = queryString(req, "multihelm");
1872
+ return {
1873
+ serverId,
1874
+ name,
1875
+ ...VERSION.test(signalk) ? { signalk } : {},
1876
+ ...VERSION.test(multihelm) ? { multihelm } : {}
1877
+ };
1878
+ }
1493
1879
  function errorText(error) {
1494
1880
  return error instanceof Error ? error.message : String(error);
1495
1881
  }
1496
- function registerRoutes(router, multihelm, discovered, vesselSettings = () => null, masterProxy = () => null) {
1882
+ function registerRoutes(router, multihelm, discovered, vesselSettings = () => null, masterProxy = () => null, ownAccess = () => null) {
1497
1883
  const scoped = router.access;
1498
1884
  const available = typeof scoped === "function";
1499
1885
  const readonly = available ? scoped.call(router, "readonly") : { get(path, handler) {
@@ -1512,7 +1898,9 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
1512
1898
  res.status(500).json({ error: errorText(error) });
1513
1899
  }
1514
1900
  };
1515
- readonly.get("/hello", running((mh, _req, res) => {
1901
+ readonly.get("/hello", running((mh, req, res) => {
1902
+ const from = helloFrom(req);
1903
+ if (from) mh.sawPairedServer(from);
1516
1904
  res.json(mh.hello());
1517
1905
  }));
1518
1906
  readonly.get("/vessel-settings", running((_mh, _req, res) => {
@@ -1562,17 +1950,21 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
1562
1950
  }
1563
1951
  router.get("/status", (_req, res) => {
1564
1952
  const mh = multihelm();
1565
- res.json({
1953
+ const status = {
1566
1954
  available,
1567
1955
  running: mh !== null,
1568
1956
  serverId: mh?.serverId ?? null,
1957
+ name: mh?.hello().name ?? "",
1569
1958
  role: mh?.role() ?? null,
1570
1959
  master: mh?.master() ?? null,
1571
1960
  masterConflict: mh?.masterConflict() ?? false,
1572
1961
  datasets: mh?.datasetIds() ?? [],
1573
1962
  peers: mh?.peerInfo() ?? [],
1574
- discovered: mh ? discovered() : []
1575
- });
1963
+ pairedBy: mh?.pairedByInfo() ?? [],
1964
+ discovered: mh ? discovered() : [],
1965
+ ownAccess: mh ? ownAccess() : null
1966
+ };
1967
+ res.json(status);
1576
1968
  });
1577
1969
  router.post("/peers", running(async (mh, req, res) => {
1578
1970
  const url = req.body?.url;
@@ -1590,6 +1982,10 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
1590
1982
  const url = queryString(req, "url");
1591
1983
  res.status(await mh.unpair(url) ? 200 : 404).json({ removed: url });
1592
1984
  }));
1985
+ router.delete("/paired-by", running((mh, req, res) => {
1986
+ const id = queryString(req, "id");
1987
+ res.status(mh.forgetPairedBy(id) ? 200 : 404).json({ removed: id });
1988
+ }));
1593
1989
  router.post("/run", running((mh, _req, res) => {
1594
1990
  mh.runRound();
1595
1991
  res.status(202).json({ started: true });
@@ -1634,6 +2030,16 @@ var OwnAccessSchema = Type.Object({
1634
2030
  Type.Literal("denied")
1635
2031
  ])
1636
2032
  });
2033
+ var PathsFileSchema = Type.Array(Type.String());
2034
+ /** A server that asked this one for its `hello`, which a server does while paired with it. */
2035
+ var PairedServerSchema = Type.Object({
2036
+ id: Type.String(),
2037
+ name: Type.String(),
2038
+ signalk: Type.Optional(Type.String()),
2039
+ multihelm: Type.Optional(Type.String()),
2040
+ lastSeen: Type.Number()
2041
+ });
2042
+ var PairedServersFileSchema = Type.Array(PairedServerSchema);
1637
2043
  var LibraryFileSchema = Type.Object({
1638
2044
  seq: Type.Integer({ minimum: 0 }),
1639
2045
  entries: Type.Record(Type.String(), Type.Any())
@@ -1687,6 +2093,21 @@ var MultihelmStore = class {
1687
2093
  saveOwnAccess(access) {
1688
2094
  writeAtomic(path.join(this.dir, "own-access.json"), JSON.stringify(access), 384);
1689
2095
  }
2096
+ /** The paths whose metadata this server takes over from the master. */
2097
+ loadFollowedMeta() {
2098
+ const raw = readJson(path.join(this.dir, "followed-meta.json"));
2099
+ return Value.Check(PathsFileSchema, raw) ? raw : [];
2100
+ }
2101
+ saveFollowedMeta(paths) {
2102
+ writeAtomic(path.join(this.dir, "followed-meta.json"), JSON.stringify(paths));
2103
+ }
2104
+ loadPairedBy() {
2105
+ const raw = readJson(path.join(this.dir, "paired-by.json"));
2106
+ return Value.Check(PairedServersFileSchema, raw) ? raw : [];
2107
+ }
2108
+ savePairedBy(servers) {
2109
+ writeAtomic(path.join(this.dir, "paired-by.json"), JSON.stringify(servers));
2110
+ }
1690
2111
  /** A random id made once per installation: every server of a boat shares its vessel id. */
1691
2112
  serverId() {
1692
2113
  const file = path.join(this.dir, "server-id");
@@ -1701,28 +2122,16 @@ var MultihelmStore = class {
1701
2122
  };
1702
2123
  // src/index.ts
1703
2124
  var PLUGIN_ID = "signalk-multihelm";
1704
- var ConfigSchema = Type.Object({
1705
- master: Type.Boolean({
1706
- title: "This server is the boat's master",
1707
- description: "Set this on one server only. Plugins that run on the master alone run here, and the other servers use them through this one.",
1708
- default: false
1709
- }),
1710
- followVessel: Type.Boolean({
1711
- title: "Take the vessel data over from the master",
1712
- description: "Name, MMSI, call sign, dimensions and ship type from Server -> Settings. Changes made here are replaced by the master's.",
1713
- default: true
1714
- }),
1715
- followMetadata: Type.Boolean({
1716
- title: "Take the path metadata over from the master",
1717
- description: "Display names, units, zones and alarm limits set for paths. Changes made here are replaced by the master's.",
1718
- default: true
1719
- }),
1720
- historyFromMaster: Type.Boolean({
1721
- title: "Answer this server's History API from the master",
1722
- description: "While the master has a history provider (signalk-questdb, for example), history graphs on this server show the master's history, so it is kept once on the boat. Does nothing on the master, while the master has no history, or before Signal K 2.32.0.",
1723
- default: true
1724
- })
1725
- });
2125
+ /** The bundle and the sources both sit one folder below `package.json`. */
2126
+ function multihelmVersion() {
2127
+ try {
2128
+ const file = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
2129
+ const { version } = JSON.parse(fs.readFileSync(file, "utf-8"));
2130
+ return typeof version === "string" ? version : void 0;
2131
+ } catch {
2132
+ return;
2133
+ }
2134
+ }
1726
2135
  var APPROVE_HINT = "approve Multihelm's request under Security -> Access Requests on this server to take the vessel settings over";
1727
2136
  var DENIED_HINT = "the access request on this server was denied, so the vessel settings are not taken over; restart the plugin to ask again";
1728
2137
  function statusText(role, master, conflict) {
@@ -1737,9 +2146,16 @@ function src_default(app) {
1737
2146
  let masterProxy = null;
1738
2147
  let stopRoleStatus = null;
1739
2148
  let stopFollowing = null;
2149
+ let masterFollower = null;
1740
2150
  function localVesselSettings() {
1741
2151
  const deltas = host.config?.baseDeltaEditor?.deltas;
1742
- return deltas === void 0 ? null : vesselSettingsFromDeltas(deltas);
2152
+ if (deltas === void 0) return null;
2153
+ const settings = vesselSettingsFromDeltas(deltas);
2154
+ const priorities = host.config?.settings ? sourcePrioritiesFromSettings(host.config.settings) : null;
2155
+ return priorities ? {
2156
+ ...settings,
2157
+ priorities
2158
+ } : settings;
1743
2159
  }
1744
2160
  /** The port this server listens on, as the server itself works it out. */
1745
2161
  function ownUrl() {
@@ -1747,6 +2163,13 @@ function src_default(app) {
1747
2163
  if (settings?.ssl) return `https://127.0.0.1:${String(Number(process.env.SSLPORT) || settings.sslport || 3443)}`;
1748
2164
  return `http://127.0.0.1:${String(Number(process.env.PORT) || settings?.port || 3e3)}`;
1749
2165
  }
2166
+ function ownAccessState() {
2167
+ if (masterFollower?.waitingForApproval()) return {
2168
+ state: "waiting-approval",
2169
+ request: masterFollower.accessRequestId()
2170
+ };
2171
+ return masterFollower?.denied() ? { state: "denied" } : null;
2172
+ }
1750
2173
  function publish(value) {
1751
2174
  app.emitPropertyValue(PROPERTY_NAME, value);
1752
2175
  }
@@ -1762,6 +2185,10 @@ function src_default(app) {
1762
2185
  const mh = new Multihelm(store, {
1763
2186
  serverName: () => os.hostname(),
1764
2187
  isMaster: () => isMaster,
2188
+ versions: () => ({
2189
+ signalk: host.config?.version,
2190
+ multihelm: multihelmVersion()
2191
+ }),
1765
2192
  debug: (msg) => {
1766
2193
  app.debug(msg);
1767
2194
  },
@@ -1795,6 +2222,7 @@ function src_default(app) {
1795
2222
  master: () => mh.masterAccess(),
1796
2223
  followVessel: settings.followVessel !== false,
1797
2224
  followMeta: settings.followMetadata !== false,
2225
+ followPriorities: settings.followSourcePriorities !== false,
1798
2226
  debug: (msg) => {
1799
2227
  app.debug(msg);
1800
2228
  },
@@ -1802,6 +2230,7 @@ function src_default(app) {
1802
2230
  app.error(msg);
1803
2231
  }
1804
2232
  });
2233
+ masterFollower = follower;
1805
2234
  const showRole = () => {
1806
2235
  const text = statusText(mh.role(), mh.master(), mh.masterConflict());
1807
2236
  if (follower.waitingForApproval()) app.setPluginStatus(`${text}; ${APPROVE_HINT}`);
@@ -1856,6 +2285,7 @@ function src_default(app) {
1856
2285
  stop() {
1857
2286
  stopFollowing?.();
1858
2287
  stopFollowing = null;
2288
+ masterFollower = null;
1859
2289
  stopRoleStatus?.();
1860
2290
  stopRoleStatus = null;
1861
2291
  if (multihelm) publish({ apiVersion: 1 });
@@ -1867,7 +2297,7 @@ function src_default(app) {
1867
2297
  discovery = null;
1868
2298
  },
1869
2299
  registerWithRouter(router) {
1870
- registerRoutes(router, () => multihelm, () => discovery?.list() ?? [], localVesselSettings, () => masterProxy);
2300
+ registerRoutes(router, () => multihelm, () => discovery?.list() ?? [], localVesselSettings, () => masterProxy, ownAccessState);
1871
2301
  }
1872
2302
  };
1873
2303
  }