signalk-polar-management 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,27 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 - 2026-09-09
4
+
5
+ Initial release.
6
+
7
+ ### Added
8
+
9
+ - Initial extraction from `signalk-polar-performance-plugin`: polar storage, selection, import
10
+ (Jieter/ORC matrix text, Expedition text, ORC active certificates), export (JSON, Jieter, Expedition),
11
+ and a management webapp. Registers as a Signal K Resource Provider for type `polars` and publishes
12
+ `vessels.self.polars.activePolar`.
13
+ - Added a webapp-adjustable polar performance factor published at
14
+ `vessels.self.polars.performanceFactor`, with metadata for both plugin-owned Signal K output paths.
15
+ - Added `GET /polars/:id/curves`, which uses `polar-math` to sample each TWS curve at a fixed angular
16
+ step (5° by default) across the full valid TWA range, so the webapp draws complete polar lines
17
+ including pinch and run extrapolation.
18
+ - Added polar validation and copy endpoints, offline-aware external import handling,
19
+ and a reorganized management webapp with separate active, management, and import pages.
20
+ - Added the Polar Management icon to Signal K plugin metadata and the published package.
21
+ - Added sortable polar tables to the active-polar and management views.
22
+ - Added optional performance-factor scaling to sampled polar curves, including beat, run,
23
+ and maximum-speed targets.
24
+
25
+ ### Fixed
26
+
27
+ - Made the Polar Management icon available in both the Signal K AppStore and the webapp header.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # Polar management
2
+
3
+ This plugin helps you keep your boat's sailing polar data organised in Signal K.
4
+
5
+ If you are not sure what a polar is, think of it as the speed your boat should make in different wind conditions. It is used by sailing apps to estimate performance, compare routes, and help with decisions on the water.
6
+
7
+ This plugin makes it easy to store more than one polar, pick the one you want to use, and manage it from a simple interface.
8
+
9
+ ## Install from the Signal K AppStore
10
+
11
+ 1. Open your Signal K admin UI.
12
+ 2. Go to the AppStore.
13
+ 3. Search for "Polar Management".
14
+ 4. Click Install.
15
+ 5. Follow any normal Signal K prompts to finish the install.
16
+
17
+ No manual command-line installation is needed for the normal AppStore workflow.
18
+
19
+ ## Find a polar for your boat
20
+
21
+ Once the plugin is installed, the next step is to load a polar for your boat.
22
+
23
+ 1. Open the Polar Management page in Signal K.
24
+ 2. Choose the import option.
25
+ 3. Use the ORC import.
26
+ 4. Search by your boat model or hull type.
27
+ 5. Pick the closest match and import it.
28
+
29
+ This is the easiest way to get a suitable polar for your boat before using other sailing apps that depend on it.
30
+
31
+ ## What this plugin does
32
+
33
+ - Keeps your polar data in one place.
34
+ - Lets you save and name different polars.
35
+ - Lets you choose which polar is the active one.
36
+ - Makes it easier to import a polar from a file or an external source.
37
+ - Helps other sailing tools use the correct polar without having to edit raw files by hand.
38
+
39
+ ## Why this is useful
40
+
41
+ This plugin is most useful when used together with other sailing apps in Signal K. Those apps can do the actual performance calculations, routing help, or sailing analysis, but they need a good polar to work with.
Binary file
Binary file
Binary file
package/icon.png ADDED
Binary file
package/index.js ADDED
@@ -0,0 +1,373 @@
1
+ 'use strict'
2
+
3
+ const path = require('path')
4
+ const { validatePolarTable } = require('polar-format')
5
+ const PolarStore = require('./lib/PolarStore')
6
+ const { ImportService, ImportError } = require('./lib/import/ImportService')
7
+ const { ExportService, ExportError } = require('./lib/export/ExportService')
8
+ const { buildCurves, DEFAULT_STEP_DEG } = require('./lib/CurveService')
9
+
10
+ const ACTIVE_POLAR_PATH = 'polars.activePolar'
11
+ const PERFORMANCE_FACTOR_PATH = 'polars.performanceFactor'
12
+ const DEFAULT_PERFORMANCE_FACTOR = 1
13
+ const RESOURCE_TYPE = 'polars'
14
+
15
+ module.exports = (app) => {
16
+ let settings = {}
17
+ let store = null
18
+ let importService = null
19
+ let exportService = null
20
+ let activePolarPublished = false
21
+ let performanceFactorPublished = false
22
+
23
+ const plugin = {
24
+ id: 'signalk-polar-management',
25
+ name: 'Polar Management'
26
+ }
27
+
28
+ function sanitizePerformanceFactor(value) {
29
+ const factor = Number(value)
30
+ if (!Number.isFinite(factor)) return DEFAULT_PERFORMANCE_FACTOR
31
+ return Math.min(1, Math.max(0, factor))
32
+ }
33
+
34
+ function isValidPerformanceFactor(value) {
35
+ const factor = Number(value)
36
+ return Number.isFinite(factor) && factor >= 0 && factor <= 1
37
+ }
38
+
39
+ // Lightweight internet connectivity probe (mirrors signalk-polar-performance-plugin).
40
+ // Attempts a HEAD request to Cloudflare's public DNS (1.1.1.1) with a 3s timeout.
41
+ async function checkInternet() {
42
+ const TIMEOUT_MS = 3000
43
+ try {
44
+ const controller = new AbortController()
45
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
46
+ const response = await fetch('https://1.1.1.1', { method: 'HEAD', signal: controller.signal })
47
+ .finally(() => clearTimeout(timer))
48
+ return response.status < 600
49
+ } catch (_) {
50
+ return false
51
+ }
52
+ }
53
+
54
+ function publishMetadata() {
55
+ app.handleMessage(plugin.id, {
56
+ updates: [{
57
+ meta: [
58
+ {
59
+ path: ACTIVE_POLAR_PATH,
60
+ value: {
61
+ type: 'object',
62
+ displayName: 'Active polar',
63
+ description: 'Pointer to the selected polar resource.'
64
+ }
65
+ },
66
+ {
67
+ path: PERFORMANCE_FACTOR_PATH,
68
+ value: {
69
+ type: 'number',
70
+ units: 'ratio',
71
+ displayName: 'Polar performance factor',
72
+ description: 'Multiplier applied by polar consumers to reduce polar speed values.'
73
+ }
74
+ }
75
+ ]
76
+ }]
77
+ })
78
+ }
79
+
80
+ function publishActivePolar(id) {
81
+ const value = id ? { href: `/resources/${RESOURCE_TYPE}/${id}` } : null
82
+ app.handleMessage(plugin.id, {
83
+ updates: [{ values: [{ path: ACTIVE_POLAR_PATH, value }] }]
84
+ })
85
+ activePolarPublished = !!id
86
+ }
87
+
88
+ function clearActivePolar() {
89
+ if (!activePolarPublished) return
90
+ app.handleMessage(plugin.id, {
91
+ updates: [{ values: [{ path: ACTIVE_POLAR_PATH, value: null }] }]
92
+ })
93
+ activePolarPublished = false
94
+ }
95
+
96
+ function publishPerformanceFactor(value) {
97
+ app.handleMessage(plugin.id, {
98
+ updates: [{ values: [{ path: PERFORMANCE_FACTOR_PATH, value }] }]
99
+ })
100
+ performanceFactorPublished = true
101
+ }
102
+
103
+ function clearPerformanceFactor() {
104
+ if (!performanceFactorPublished) return
105
+ app.handleMessage(plugin.id, {
106
+ updates: [{ values: [{ path: PERFORMANCE_FACTOR_PATH, value: null }] }]
107
+ })
108
+ performanceFactorPublished = false
109
+ }
110
+
111
+ plugin.start = (options) => {
112
+ settings = { activePolar: '', performanceFactor: DEFAULT_PERFORMANCE_FACTOR, ...options }
113
+ settings.performanceFactor = sanitizePerformanceFactor(settings.performanceFactor)
114
+ store = new PolarStore(path.join(app.getDataDirPath(), 'polars'))
115
+ importService = new ImportService(store)
116
+ exportService = new ExportService()
117
+
118
+ publishMetadata()
119
+ publishPerformanceFactor(settings.performanceFactor)
120
+
121
+ if (settings.activePolar && store.exists(settings.activePolar)) {
122
+ publishActivePolar(settings.activePolar)
123
+ } else if (settings.activePolar) {
124
+ app.setPluginError(`Configured active polar '${settings.activePolar}' was not found`)
125
+ }
126
+
127
+ app.registerResourceProvider({
128
+ type: RESOURCE_TYPE,
129
+ methods: {
130
+ listResources: async () => {
131
+ const result = {}
132
+ for (const meta of store.listWithMeta()) {
133
+ const { id, ...rest } = meta
134
+ result[id] = rest
135
+ }
136
+ return result
137
+ },
138
+ getResource: async (id) => {
139
+ if (!store.exists(id)) throw new Error(`Polar not found: ${id}`)
140
+ return store.get(id)
141
+ },
142
+ setResource: async (id, value) => {
143
+ store.save(id, value)
144
+ },
145
+ deleteResource: async (id) => {
146
+ if (settings.activePolar === id) {
147
+ throw new Error(`Cannot delete '${id}': it is the active polar`)
148
+ }
149
+ store.delete(id)
150
+ }
151
+ }
152
+ })
153
+
154
+ app.setPluginStatus(`Managing ${store.list().length} polar(s)`)
155
+ }
156
+
157
+ plugin.stop = () => {
158
+ clearActivePolar()
159
+ clearPerformanceFactor()
160
+ store = null
161
+ importService = null
162
+ exportService = null
163
+ }
164
+
165
+ plugin.schema = () => ({ type: 'object', properties: {} })
166
+
167
+ plugin.registerWithRouter = (router) => {
168
+ router.get('/polars', (req, res) => {
169
+ res.json(store.listWithMeta())
170
+ })
171
+
172
+ router.get('/polars/:id', (req, res) => {
173
+ try {
174
+ res.json({ id: req.params.id, ...store.get(req.params.id) })
175
+ } catch (e) {
176
+ res.status(404).json({ error: e.message })
177
+ }
178
+ })
179
+
180
+ router.get('/polars/:id/curves', (req, res) => {
181
+ const step = req.query.step === undefined ? DEFAULT_STEP_DEG : Number(req.query.step)
182
+ let table
183
+ try {
184
+ table = store.get(req.params.id)
185
+ } catch (e) {
186
+ return res.status(404).json({ error: e.message })
187
+ }
188
+ const performanceFactor = req.query.corrected === 'true' ? settings.performanceFactor : 1
189
+ try {
190
+ res.json({ id: req.params.id, ...buildCurves(table, step, performanceFactor) })
191
+ } catch (e) {
192
+ res.status(400).json({ error: e.message })
193
+ }
194
+ })
195
+
196
+ router.get('/polars/:id/validate', (req, res) => {
197
+ let table
198
+ try {
199
+ table = store.get(req.params.id)
200
+ } catch (e) {
201
+ return res.status(404).json({ error: e.message })
202
+ }
203
+ const result = validatePolarTable(table)
204
+ res.json({
205
+ valid: result.valid,
206
+ errors: result.valid ? [] : result.errors.map(e => `${e.path}: ${e.message}`)
207
+ })
208
+ })
209
+
210
+ router.post('/polars/:id/copy', (req, res) => {
211
+ const newId = req.body?.id
212
+ if (typeof newId !== 'string' || !newId.trim()) {
213
+ return res.status(400).json({ error: "'id' is required" })
214
+ }
215
+ try {
216
+ store.copy(req.params.id, newId)
217
+ res.json({ id: newId })
218
+ } catch (e) {
219
+ res.status(400).json({ error: e.message })
220
+ }
221
+ })
222
+
223
+ router.put('/polars/:id', (req, res) => {
224
+ try {
225
+ store.save(req.params.id, req.body)
226
+ res.json({ id: req.params.id })
227
+ } catch (e) {
228
+ res.status(400).json({ error: e.message })
229
+ }
230
+ })
231
+
232
+ router.delete('/polars/:id', (req, res) => {
233
+ if (settings.activePolar === req.params.id) {
234
+ return res.status(409).json({ error: `Cannot delete '${req.params.id}': it is the active polar` })
235
+ }
236
+ try {
237
+ store.delete(req.params.id)
238
+ res.status(204).end()
239
+ } catch (e) {
240
+ res.status(404).json({ error: e.message })
241
+ }
242
+ })
243
+
244
+ router.post('/polars/:id/rename', (req, res) => {
245
+ const newId = req.body?.id
246
+ if (typeof newId !== 'string' || !newId.trim()) {
247
+ return res.status(400).json({ error: "'id' is required" })
248
+ }
249
+ try {
250
+ store.rename(req.params.id, newId)
251
+ if (settings.activePolar === req.params.id) {
252
+ settings.activePolar = newId
253
+ app.savePluginOptions(settings, () => {})
254
+ publishActivePolar(newId)
255
+ }
256
+ res.json({ id: newId })
257
+ } catch (e) {
258
+ res.status(400).json({ error: e.message })
259
+ }
260
+ })
261
+
262
+ router.get('/internet', async (req, res) => {
263
+ res.json({ online: await checkInternet() })
264
+ })
265
+
266
+ router.get('/activePolar', (req, res) => {
267
+ const id = settings.activePolar || null
268
+ if (!id) {
269
+ return res.json({ id: null, exists: false, valid: false, errors: [] })
270
+ }
271
+ if (!store.exists(id)) {
272
+ return res.json({ id, exists: false, valid: false, errors: [`Configured active polar '${id}' was not found`] })
273
+ }
274
+ const result = validatePolarTable(store.get(id))
275
+ res.json({
276
+ id,
277
+ exists: true,
278
+ valid: result.valid,
279
+ errors: result.valid ? [] : result.errors.map(e => `${e.path}: ${e.message}`)
280
+ })
281
+ })
282
+
283
+ router.put('/activePolar', (req, res) => {
284
+ const id = req.body?.id
285
+ if (id && !store.exists(id)) {
286
+ return res.status(404).json({ error: `Polar not found: ${id}` })
287
+ }
288
+ settings.activePolar = id || ''
289
+ app.savePluginOptions(settings, (err) => {
290
+ if (err) return res.status(500).json({ error: err.message })
291
+ if (id) publishActivePolar(id)
292
+ else clearActivePolar()
293
+ res.json({ id: settings.activePolar || null })
294
+ })
295
+ })
296
+
297
+ router.get('/performanceFactor', (req, res) => {
298
+ res.json({ value: settings.performanceFactor })
299
+ })
300
+
301
+ router.put('/performanceFactor', (req, res) => {
302
+ if (!isValidPerformanceFactor(req.body?.value)) {
303
+ return res.status(400).json({ error: 'Performance factor must be between 0 and 1' })
304
+ }
305
+ settings.performanceFactor = sanitizePerformanceFactor(req.body?.value)
306
+ app.savePluginOptions(settings, (err) => {
307
+ if (err) return res.status(500).json({ error: err.message })
308
+ publishPerformanceFactor(settings.performanceFactor)
309
+ res.json({ value: settings.performanceFactor })
310
+ })
311
+ })
312
+
313
+ router.get('/imports/formats', (req, res) => {
314
+ res.json(importService.listFormats())
315
+ })
316
+
317
+ router.post('/imports/text/:format', (req, res) => {
318
+ try {
319
+ res.json(importService.importText(req.params.format, req.body))
320
+ } catch (e) {
321
+ res.status(e instanceof ImportError ? e.status : 500).json({ error: e.message })
322
+ }
323
+ })
324
+
325
+ router.get('/imports/sources', (req, res) => {
326
+ res.json(importService.listSources())
327
+ })
328
+
329
+ router.get('/imports/sources/:source/search', async (req, res) => {
330
+ if (!await checkInternet()) {
331
+ return res.status(503).json({ error: 'No internet connection — external source imports are unavailable' })
332
+ }
333
+ try {
334
+ res.json(await importService.searchSource(req.params.source, req.query.q))
335
+ } catch (e) {
336
+ res.status(e instanceof ImportError ? e.status : 500).json({ error: e.message })
337
+ }
338
+ })
339
+
340
+ router.post('/imports/sources/:source/items/:externalId', async (req, res) => {
341
+ if (!await checkInternet()) {
342
+ return res.status(503).json({ error: 'No internet connection — external source imports are unavailable' })
343
+ }
344
+ try {
345
+ res.json(await importService.importSource(req.params.source, req.params.externalId, req.body))
346
+ } catch (e) {
347
+ res.status(e instanceof ImportError ? e.status : 500).json({ error: e.message })
348
+ }
349
+ })
350
+
351
+ router.get('/exports/formats', (req, res) => {
352
+ res.json([{ id: 'json', name: 'Canonical JSON', description: 'polar-format canonical document' }, ...exportService.listFormats()])
353
+ })
354
+
355
+ router.get('/polars/:id/export/:format', (req, res) => {
356
+ try {
357
+ const resource = store.get(req.params.id)
358
+ const text = exportService.exportText(req.params.format, resource)
359
+ const contentType = req.params.format === 'json' ? 'application/json' : 'text/plain'
360
+ const ext = req.params.format === 'json' ? 'json' : 'txt'
361
+ res.set('Content-Type', contentType)
362
+ res.set('Content-Disposition', `attachment; filename="${req.params.id}.${ext}"`)
363
+ res.send(text)
364
+ } catch (e) {
365
+ res.status(e instanceof ExportError ? e.status : 404).json({ error: e.message })
366
+ }
367
+ })
368
+ }
369
+
370
+ plugin.getOpenApi = () => require('./openApi.json')
371
+
372
+ return plugin
373
+ }