signalk-siparu 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.
Files changed (62) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +65 -0
  3. package/package.json +47 -0
  4. package/plugin/dist/ais.js +121 -0
  5. package/plugin/dist/charts.js +126 -0
  6. package/plugin/dist/config.js +187 -0
  7. package/plugin/dist/contract.js +12 -0
  8. package/plugin/dist/index.js +292 -0
  9. package/plugin/dist/metrics.js +254 -0
  10. package/plugin/dist/pairing.js +193 -0
  11. package/plugin/dist/query.js +121 -0
  12. package/plugin/dist/rest.js +178 -0
  13. package/plugin/dist/rollup.js +370 -0
  14. package/plugin/dist/store.js +171 -0
  15. package/plugin/dist/time.js +28 -0
  16. package/plugin/dist/voyage.js +270 -0
  17. package/plugin/dist/voyagelog.js +269 -0
  18. package/public/assets/Logbook-CREU8sGe.js +1 -0
  19. package/public/assets/Map-04Cjpqvt.js +104 -0
  20. package/public/assets/Voyage-Xsr6a6DP.js +1 -0
  21. package/public/assets/archivo-latin-300-normal-AMs-pvbP.woff2 +0 -0
  22. package/public/assets/archivo-latin-300-normal-BRswihEa.woff +0 -0
  23. package/public/assets/archivo-latin-400-normal-Bl602Mgc.woff +0 -0
  24. package/public/assets/archivo-latin-400-normal-C81ewxNO.woff2 +0 -0
  25. package/public/assets/archivo-latin-500-normal-CGugC8dq.woff2 +0 -0
  26. package/public/assets/archivo-latin-500-normal-pkzA7jw9.woff +0 -0
  27. package/public/assets/archivo-latin-600-normal-3BBy0ZsW.woff2 +0 -0
  28. package/public/assets/archivo-latin-600-normal-DwYieO8P.woff +0 -0
  29. package/public/assets/archivo-latin-700-normal-D9cHMWGj.woff2 +0 -0
  30. package/public/assets/archivo-latin-700-normal-lT5TFe7H.woff +0 -0
  31. package/public/assets/archivo-latin-800-normal-DZa_k145.woff +0 -0
  32. package/public/assets/archivo-latin-800-normal-cB6v3kRN.woff2 +0 -0
  33. package/public/assets/archivo-latin-ext-300-normal-0WwdIqab.woff2 +0 -0
  34. package/public/assets/archivo-latin-ext-300-normal-D3llZCfd.woff +0 -0
  35. package/public/assets/archivo-latin-ext-400-normal-B5tPZzqW.woff2 +0 -0
  36. package/public/assets/archivo-latin-ext-400-normal-DrmqtLj6.woff +0 -0
  37. package/public/assets/archivo-latin-ext-500-normal-D7mXw3Kz.woff +0 -0
  38. package/public/assets/archivo-latin-ext-500-normal-RFhg4CpD.woff2 +0 -0
  39. package/public/assets/archivo-latin-ext-600-normal-D7uErJuz.woff +0 -0
  40. package/public/assets/archivo-latin-ext-600-normal-Dm61iqcg.woff2 +0 -0
  41. package/public/assets/archivo-latin-ext-700-normal-CgyfnKjw.woff +0 -0
  42. package/public/assets/archivo-latin-ext-700-normal-DD_nkw6b.woff2 +0 -0
  43. package/public/assets/archivo-latin-ext-800-normal-B9NTbsU1.woff +0 -0
  44. package/public/assets/archivo-latin-ext-800-normal-BC6piDwP.woff2 +0 -0
  45. package/public/assets/index-BaRFPcmb.css +1 -0
  46. package/public/assets/index-ukqYc_b7.js +21 -0
  47. package/public/assets/jetbrains-mono-latin-300-normal-BYcAiAh2.woff +0 -0
  48. package/public/assets/jetbrains-mono-latin-300-normal-DuMDZskh.woff2 +0 -0
  49. package/public/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  50. package/public/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  51. package/public/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  52. package/public/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  53. package/public/assets/jetbrains-mono-latin-600-normal-BfsvjouI.woff +0 -0
  54. package/public/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  55. package/public/assets/rolldown-runtime-CNC7AqOf.js +1 -0
  56. package/public/assets/style-B2k4QVOw.css +1 -0
  57. package/public/assets/style-xd60AbLN.js +762 -0
  58. package/public/assets/tz-DxphYhHy.js +1 -0
  59. package/public/assets/visibleInterval-CFxPzgzx.js +1 -0
  60. package/public/favicon.svg +7 -0
  61. package/public/index.html +20 -0
  62. package/public/manifest.webmanifest +18 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # Siparu
2
+
3
+ Kept aboard, proven ashore. A Signal K plugin that records your boat's bridge
4
+ data — position, speed, heading, wind, depth — into an on-board history with
5
+ voyage detection, and serves it through a built-in dashboard (PWA) and a
6
+ read-only REST API.
7
+
8
+ ## Principles
9
+
10
+ - **Read-only.** The plugin never writes to your boat: no deltas are emitted,
11
+ no PUT handlers registered, no action handlers, no NMEA out. The CI proves it
12
+ on every commit — grep this codebase and see for yourself.
13
+ - **Your data stays on board.** History is stored on the boat, in plain NDJSON
14
+ files with hourly/daily summaries. Nothing leaves the vessel unless you pair
15
+ it, and pairing takes a deliberate tap at the helm — after which the boat
16
+ sends its current position and name to the portal you paired it with, and
17
+ nothing else. Unpair and it stops. The history never leaves.
18
+ - **Zero runtime dependencies, pure JavaScript.** No native modules, so it
19
+ installs cleanly from the Signal K AppStore on anything from a Raspberry Pi
20
+ to a Victron Cerbo GX (Venus OS Large).
21
+ - **Compatibility floor:** Node 20 + signalk-server 2.18.
22
+
23
+ ## REST API
24
+
25
+ Mounted at `/plugins/siparu`:
26
+
27
+ | Endpoint | Description |
28
+ |---|---|
29
+ | `GET /live` | Current state of all recorded paths + data age |
30
+ | `GET /snapshots?bucket=1\|60\|360\|1440&from=&to=&limit=&offset=&order=` | History rows. `bucket=1` serves raw rows (today only); larger buckets read materialized rollups |
31
+ | `GET /health` | Recording status, signature diagnosis, per-path freshness, storage usage, rollup state |
32
+ | `GET /voyages?limit=` | Auto-detected voyages, newest first |
33
+ | `GET /voyages/current` | Currently open voyage, or `null` |
34
+ | `GET /voyages/stats` | Today / yesterday / rolling 7 days / season aggregates |
35
+ | `GET /voyages/:id/track` | Minute-cadence GPS track of one voyage |
36
+
37
+ The reading surface above is GET-only. The one exception is pairing, which
38
+ moves the plugin's own state and never touches the vessel's:
39
+
40
+ | Endpoint | Description |
41
+ |---|---|
42
+ | `GET /pair/status` | Current pairing state |
43
+ | `POST /pair/start` | Ask the relay for a code to show at the helm |
44
+ | `POST /pair/approve` · `POST /pair/deny` | Answer a claim — the tap at the helm |
45
+ | `POST /pair/reset` | Unpair |
46
+
47
+ Voyage detection opens after sustained movement, closes after sustained
48
+ stillness, and folds short docking manoeuvres into the preceding voyage. Its
49
+ behavior is pinned by a golden-fixture test against a reference
50
+ implementation on ten days of real vessel data (`plugin/test/fixtures/`).
51
+
52
+ All timestamps are epoch milliseconds (UTC). Values use Signal K's SI units
53
+ (m/s, radians, Kelvin, Pascal).
54
+
55
+ ## Development
56
+
57
+ ```
58
+ npm install
59
+ npm run build # compile plugin TypeScript to plugin/dist
60
+ npm test # unit tests (vitest)
61
+ ```
62
+
63
+ ## License
64
+
65
+ Apache-2.0
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "signalk-siparu",
3
+ "version": "0.1.0",
4
+ "description": "Siparu \u2014 kept aboard, proven ashore. An impartial, timestamped record of every voyage: position, wind, depth and logbook, written on the boat and readable from anywhere. Read-only Signal K plugin with a built-in PWA.",
5
+ "keywords": [
6
+ "signalk-node-server-plugin",
7
+ "signalk-webapp"
8
+ ],
9
+ "main": "plugin/dist/index.js",
10
+ "files": [
11
+ "plugin/dist",
12
+ "public"
13
+ ],
14
+ "signalk-plugin-enabled-by-default": true,
15
+ "signalk": {
16
+ "displayName": "Siparu"
17
+ },
18
+ "author": "Siparu",
19
+ "homepage": "https://siparu.app",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/Tjockfan/siparu.git"
23
+ },
24
+ "bugs": {
25
+ "url": "https://github.com/Tjockfan/siparu/issues"
26
+ },
27
+ "license": "Apache-2.0",
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "scripts": {
32
+ "build": "tsc -p plugin/tsconfig.json",
33
+ "watch": "tsc -p plugin/tsconfig.json --watch",
34
+ "test": "vitest run",
35
+ "prepack": "npm run build:all",
36
+ "build:webapp": "npm --prefix webapp run build",
37
+ "build:all": "npm run build && npm run build:webapp",
38
+ "ci:build": "npm --prefix webapp ci && npm run build:all"
39
+ },
40
+ "devDependencies": {
41
+ "@signalk/server-api": "^2.30.0",
42
+ "@types/express": "^4.17.21",
43
+ "@types/node": "^20.19.0",
44
+ "typescript": "^5.9.0",
45
+ "vitest": "^4.1.0"
46
+ }
47
+ }
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildAisFeed = buildAisFeed;
4
+ exports.clampAisQuery = clampAisQuery;
5
+ const rollup_1 = require("./rollup");
6
+ const MS_TO_KN = 1.9438;
7
+ /** Full-model node: {value, timestamp, ...} or a plain value. */
8
+ function nodeValue(node) {
9
+ if (node && typeof node === 'object' && 'value' in node) {
10
+ return node.value;
11
+ }
12
+ return node;
13
+ }
14
+ function dig(obj, ...path) {
15
+ let cur = obj;
16
+ for (const k of path) {
17
+ if (!cur || typeof cur !== 'object')
18
+ return undefined;
19
+ cur = cur[k];
20
+ }
21
+ return nodeValue(cur);
22
+ }
23
+ function num(v) {
24
+ return typeof v === 'number' && Number.isFinite(v) ? v : null;
25
+ }
26
+ function deg(rad) {
27
+ const r = num(rad);
28
+ if (r === null)
29
+ return null;
30
+ return Math.round((((r * 180) / Math.PI) % 360) * 10) / 10;
31
+ }
32
+ function kn(ms) {
33
+ const m = num(ms);
34
+ if (m === null)
35
+ return null;
36
+ return Math.round(m * MS_TO_KN * 10) / 10;
37
+ }
38
+ /**
39
+ * AIS text (name/ship_type/nav_state) renders in map popups. XSS
40
+ * defense-in-depth: strip markup characters server-side too — the frontend
41
+ * escapes as well, this is the second layer.
42
+ */
43
+ function cleanStr(v) {
44
+ if (v === null || v === undefined)
45
+ return null;
46
+ const s = String(v).replace(/[<>"'`]/g, '').trim();
47
+ return s || null;
48
+ }
49
+ function tsMs(iso) {
50
+ if (typeof iso !== 'string')
51
+ return null;
52
+ const t = Date.parse(iso);
53
+ return Number.isFinite(t) ? t : null;
54
+ }
55
+ function buildAisFeed(vessels, selfContext, now, q) {
56
+ if (!vessels || typeof vessels !== 'object')
57
+ return { targets: [], own: null, count: 0 };
58
+ const dict = vessels;
59
+ const selfKey = selfContext.replace(/^vessels\./, '').trim();
60
+ const selfV = dict[selfKey];
61
+ const ownPos = dig(selfV?.navigation, 'position');
62
+ const ownLat = num(ownPos?.latitude);
63
+ const ownLon = num(ownPos?.longitude);
64
+ // Without our own position the distance filter is impossible; an explicit
65
+ // error beats silently drawing far-away traffic as "nearby".
66
+ if (ownLat === null || ownLon === null) {
67
+ return { targets: [], own: null, count: 0, error: 'no-self-position' };
68
+ }
69
+ const cutoff = now - q.maxAgeMin * 60_000;
70
+ const targets = [];
71
+ for (const [key, v] of Object.entries(dict)) {
72
+ if (key === selfKey || !v || typeof v !== 'object')
73
+ continue;
74
+ const vessel = v;
75
+ const nav = (vessel.navigation ?? {});
76
+ const pos = dig(nav, 'position');
77
+ const lat = num(pos?.latitude);
78
+ const lon = num(pos?.longitude);
79
+ if (lat === null || lon === null)
80
+ continue;
81
+ const posBlock = nav.position;
82
+ const ts = posBlock ? tsMs(posBlock.timestamp) : null;
83
+ if (ts !== null && ts < cutoff)
84
+ continue;
85
+ const dist = (0, rollup_1.haversineNm)(ownLat, ownLon, lat, lon);
86
+ if (dist > q.maxNm)
87
+ continue;
88
+ const design = (vessel.design ?? {});
89
+ const shipType = dig(design, 'aisShipType');
90
+ const length = dig(design, 'length');
91
+ targets.push({
92
+ mmsi: String(vessel.mmsi ?? key.split(':').pop()),
93
+ name: cleanStr(dig(vessel, 'name')),
94
+ lat,
95
+ lon,
96
+ sog_kn: kn(dig(nav, 'speedOverGround')),
97
+ cog_deg: deg(dig(nav, 'courseOverGroundTrue')),
98
+ heading_deg: deg(dig(nav, 'headingTrue')),
99
+ nav_state: cleanStr(dig(nav, 'state')),
100
+ ais_class: cleanStr(dig(vessel.sensors, 'ais', 'class')),
101
+ ship_type: cleanStr(shipType && typeof shipType === 'object' ? shipType.name : null),
102
+ length_m: num(length?.overall),
103
+ distance_nm: Math.round(dist * 100) / 100,
104
+ ts
105
+ });
106
+ }
107
+ targets.sort((a, b) => (a.distance_nm ?? 0) - (b.distance_nm ?? 0));
108
+ return {
109
+ targets: targets.slice(0, q.limit),
110
+ own: { lat: ownLat, lon: ownLon },
111
+ count: Math.min(targets.length, q.limit)
112
+ };
113
+ }
114
+ function clampAisQuery(maxNm, maxAgeMin, limit) {
115
+ const clamp = (v, d, lo, hi) => typeof v === 'number' && Number.isFinite(v) ? Math.min(Math.max(v, lo), hi) : d;
116
+ return {
117
+ maxNm: clamp(maxNm, 5, 0.5, 50),
118
+ maxAgeMin: clamp(maxAgeMin, 15, 1, 120),
119
+ limit: clamp(limit, 30, 1, 400)
120
+ };
121
+ }
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.chartsDir = chartsDir;
37
+ exports.resolveMapConfig = resolveMapConfig;
38
+ exports.safeChartPath = safeChartPath;
39
+ exports.chartContentType = chartContentType;
40
+ /**
41
+ * Chart asset resolution + safe file serving.
42
+ *
43
+ * The webapp map loads four kinds of assets: a basemap PMTiles, an optional
44
+ * seamark PMTiles, glyph PBFs and a sprite sheet. Each resolves to either a
45
+ * local file under `<dataDir>/charts/` (offline charts, dropped in by the
46
+ * user or a future download feature) or the configured remote tile server.
47
+ * /map-config reports the resolved URLs; the webapp never guesses.
48
+ *
49
+ * Serving stays GET-only and read-only like every other route.
50
+ */
51
+ const fs = __importStar(require("node:fs"));
52
+ const path = __importStar(require("node:path"));
53
+ /** URL prefix the server mounts our router on — used for local asset URLs. */
54
+ const MOUNT = '/plugins/siparu';
55
+ function chartsDir(dataDir) {
56
+ return path.join(dataDir, 'charts');
57
+ }
58
+ /** Resolve every map asset to a local or remote URL. Sync fs is fine here:
59
+ * called once per /map-config request against at most four stat'ed paths. */
60
+ function resolveMapConfig(dataDir, remoteBaseUrl) {
61
+ const dir = chartsDir(dataDir);
62
+ const has = (rel) => {
63
+ try {
64
+ return fs.statSync(path.join(dir, rel)).isFile();
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ };
70
+ const hasDir = (rel) => {
71
+ try {
72
+ return fs.statSync(path.join(dir, rel)).isDirectory();
73
+ }
74
+ catch {
75
+ return false;
76
+ }
77
+ };
78
+ const localBasemap = has('basemap.pmtiles');
79
+ const localSeamark = has('seamark.pmtiles');
80
+ const localFonts = hasDir('fonts');
81
+ const localSprites = hasDir('sprites');
82
+ return {
83
+ basemap: localBasemap ? `${MOUNT}/charts/basemap.pmtiles` : `${remoteBaseUrl}/basemap.pmtiles`,
84
+ seamark: localSeamark ? `${MOUNT}/charts/seamark.pmtiles` : `${remoteBaseUrl}/seamark.pmtiles`,
85
+ glyphs: localFonts
86
+ ? `${MOUNT}/charts/fonts/{fontstack}/{range}.pbf`
87
+ : `${remoteBaseUrl}/fonts/{fontstack}/{range}.pbf`,
88
+ sprite: localSprites ? `${MOUNT}/charts/sprites` : `${remoteBaseUrl}/sprites`,
89
+ local: { basemap: localBasemap, seamark: localSeamark, fonts: localFonts, sprites: localSprites }
90
+ };
91
+ }
92
+ const SERVABLE_EXT = new Set(['.pmtiles', '.pbf', '.json', '.png']);
93
+ /**
94
+ * Map a request path (everything after /charts/) to an absolute file path
95
+ * inside the charts dir. Returns null for traversal attempts, absolute
96
+ * paths, or extensions we do not serve.
97
+ */
98
+ function safeChartPath(dataDir, rel) {
99
+ let decoded;
100
+ try {
101
+ decoded = decodeURIComponent(rel);
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ if (decoded.includes('\0') || decoded.startsWith('/'))
107
+ return null;
108
+ const dir = chartsDir(dataDir);
109
+ const abs = path.normalize(path.join(dir, decoded));
110
+ // normalize()d path must stay inside the charts dir (kills `..` and
111
+ // absolute-path tricks in one check).
112
+ if (abs !== dir && !abs.startsWith(dir + path.sep))
113
+ return null;
114
+ if (!SERVABLE_EXT.has(path.extname(abs).toLowerCase()))
115
+ return null;
116
+ return abs;
117
+ }
118
+ /** Content types express would not guess for our extensions. */
119
+ function chartContentType(absPath) {
120
+ const ext = path.extname(absPath).toLowerCase();
121
+ if (ext === '.pmtiles')
122
+ return 'application/octet-stream';
123
+ if (ext === '.pbf')
124
+ return 'application/x-protobuf';
125
+ return undefined; // .json/.png: express sendFile sets these itself
126
+ }