@kiosko/sdk 0.1.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context.d.ts +1 -0
- package/dist/context.js +1 -0
- package/dist/http.d.ts +55 -0
- package/dist/http.js +118 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/plugin.d.ts +208 -2
- package/dist/plugin.js +7 -0
- package/dist/schema.d.ts +17 -1
- package/dist/schema.js +4 -4
- package/dist/semver.d.ts +25 -0
- package/dist/semver.js +115 -0
- package/dist/system.d.ts +35 -0
- package/dist/system.js +80 -0
- package/dist/testing.d.ts +86 -0
- package/dist/testing.js +149 -0
- package/package.json +6 -1
- package/src/context.ts +2 -1
- package/src/http.ts +136 -0
- package/src/index.ts +3 -0
- package/src/plugin.ts +206 -2
- package/src/schema.ts +19 -4
- package/src/semver.ts +105 -0
- package/src/system.ts +87 -0
- package/src/testing.ts +192 -0
package/src/plugin.ts
CHANGED
|
@@ -88,8 +88,15 @@ export interface BaseContext {
|
|
|
88
88
|
*/
|
|
89
89
|
fmt: Formatters;
|
|
90
90
|
log: Logger;
|
|
91
|
-
/** Where the plugin may keep files (
|
|
91
|
+
/** Where the plugin may keep files that must survive a reboot (settings, history). Created on demand. */
|
|
92
92
|
dataDir: string;
|
|
93
|
+
/**
|
|
94
|
+
* Where the plugin keeps what can be fetched again (downloads, feed copies,
|
|
95
|
+
* photos, tiles). It is RAM (tmpfs), so the constant rewriting never wears
|
|
96
|
+
* the SSD, and it is empty after a reboot. Created on demand. Falls back to
|
|
97
|
+
* `dataDir` where there is no tmpfs. Use this, not `dataDir`, for caches.
|
|
98
|
+
*/
|
|
99
|
+
cacheDir: string;
|
|
93
100
|
/**
|
|
94
101
|
* The user's place, if set in Settings (weather, sun, earthquakes…). Use it
|
|
95
102
|
* by default; offer a place of your own only where a second one makes sense
|
|
@@ -139,10 +146,83 @@ export interface RenderContext<O, D> extends BaseContext, StateContext<O, D> {
|
|
|
139
146
|
canvas: CanvasApi;
|
|
140
147
|
/** The widget is drawn in the editor (gallery thumbnail or live preview) and not on the panel. */
|
|
141
148
|
preview: boolean;
|
|
142
|
-
/**
|
|
149
|
+
/**
|
|
150
|
+
* Set while an animation of this widget is being painted (see
|
|
151
|
+
* `WidgetDefinition.animation`): which frame this call must draw. Without
|
|
152
|
+
* it, paint the widget at rest. The first and the last frame of an
|
|
153
|
+
* animation should look exactly like the still one.
|
|
154
|
+
*/
|
|
155
|
+
anim?: AnimationFrame;
|
|
156
|
+
/** Index of the frame being painted while an animation runs (`anim.i`). */
|
|
143
157
|
frame?: number;
|
|
144
158
|
}
|
|
145
159
|
|
|
160
|
+
/**
|
|
161
|
+
* A short animation a widget asks the runtime to play inside its own tile: a
|
|
162
|
+
* cat's tail flick, a tile sliding in. The runtime plans it (when, one at a
|
|
163
|
+
* time per screen), paints every frame by calling `render` with `ctx.anim`
|
|
164
|
+
* before playing, sends them at `fps` (never above the screen's `maxFps`) and
|
|
165
|
+
* finishes with a real still repaint.
|
|
166
|
+
*/
|
|
167
|
+
export interface AnimationPlan {
|
|
168
|
+
/** What it is (`tail`, `walk`…): for the log and for `render`, which receives it in `ctx.anim.plan`. */
|
|
169
|
+
id: string;
|
|
170
|
+
/** Frames, counting the first and the last (those are the still picture and are not sent). At least 3. */
|
|
171
|
+
frames: number;
|
|
172
|
+
/** Frames per second it was designed for. The screen's `maxFps` caps it. */
|
|
173
|
+
fps: number;
|
|
174
|
+
/** Whatever `render` needs to draw it (who does what). Plain data: it is not interpreted. */
|
|
175
|
+
params?: unknown;
|
|
176
|
+
/**
|
|
177
|
+
* `false`: new data doesn't cut it short (something that must be seen to
|
|
178
|
+
* the end). Default `true`: a data change cancels it and the screen is
|
|
179
|
+
* repainted with the new data.
|
|
180
|
+
*/
|
|
181
|
+
interruptible?: boolean;
|
|
182
|
+
/** Stay still at `at` (0..1 of the animation) for `ms` (a long task being shown), or until interrupted. */
|
|
183
|
+
hold?: { at: number; ms: number };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** The frame `render` must paint (see `RenderContext.anim`). */
|
|
187
|
+
export interface AnimationFrame {
|
|
188
|
+
plan: AnimationPlan;
|
|
189
|
+
/** Frame number, 0..plan.frames-1. */
|
|
190
|
+
i: number;
|
|
191
|
+
/** Progress, 0..1: `i / (frames - 1)`. 0 and 1 are the still picture. */
|
|
192
|
+
t: number;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** What `WidgetDefinition.animationEnded` is told. */
|
|
196
|
+
export interface AnimationEndContext<O, D> extends BaseContext {
|
|
197
|
+
options: O;
|
|
198
|
+
/** The animation that has just ended. */
|
|
199
|
+
plan: AnimationPlan;
|
|
200
|
+
/**
|
|
201
|
+
* `true` if it played to its last frame; `false` if it was cut short (new
|
|
202
|
+
* data, the screen went away) or never got to play.
|
|
203
|
+
*/
|
|
204
|
+
completed: boolean;
|
|
205
|
+
/** The widget's data when it started. */
|
|
206
|
+
data: D | undefined;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** What `WidgetDefinition.animation` is asked with. */
|
|
210
|
+
export interface AnimationContext<O, D> extends StateContext<O, D> {
|
|
211
|
+
/** Where the widget paints (the same `box` its `render` gets), to decide with the layout it will have. */
|
|
212
|
+
box: Box;
|
|
213
|
+
/**
|
|
214
|
+
* Why it is asked: `idle`, every now and then while nothing else happens
|
|
215
|
+
* (see `animationGap`), or `data`, because this instance's data just changed
|
|
216
|
+
* or one of its sources did (see `prev`) and a reaction may be due, like a
|
|
217
|
+
* cat walking to its new spot.
|
|
218
|
+
*/
|
|
219
|
+
trigger: 'idle' | 'data';
|
|
220
|
+
/** What the widget had before the change, for `trigger: 'data'`: its own data and its sources. */
|
|
221
|
+
prev?: { data: D | undefined; sources: Record<string, unknown> };
|
|
222
|
+
/** Random numbers in [0, 1). Use these and not `Math.random`, so tests can seed them. */
|
|
223
|
+
rnd: () => number;
|
|
224
|
+
}
|
|
225
|
+
|
|
146
226
|
/**
|
|
147
227
|
* When the widget must be repainted even though its data didn't change: a
|
|
148
228
|
* clock every second, a countdown every minute. Fewer repaints are fewer
|
|
@@ -185,6 +265,26 @@ export interface WidgetDefinition<OF extends ObjectField<any> = ObjectField<any>
|
|
|
185
265
|
timeoutMs?: number;
|
|
186
266
|
/** Paint. Synchronous and fast: load images in `fetch` and paint them here. */
|
|
187
267
|
render: (g: Graphics, ctx: RenderContext<Infer<OF>, D>) => void;
|
|
268
|
+
/**
|
|
269
|
+
* Asks for a short animation inside the tile, or `null` for none. The
|
|
270
|
+
* runtime calls it only while this widget is the one shown, the screen has
|
|
271
|
+
* room for another animation (several widgets may ask: they wait their turn,
|
|
272
|
+
* and how many play together is up to the runtime) and its `animationGap` /
|
|
273
|
+
* `animationCooldownMs` allow it. It must be cheap and decide from the data alone; the drawing goes in
|
|
274
|
+
* `render`, which gets `ctx.anim` for every frame. Every frame costs USB
|
|
275
|
+
* time: keep them few and short.
|
|
276
|
+
*/
|
|
277
|
+
animation?: (ctx: AnimationContext<Infer<OF>, D>) => AnimationPlan | null;
|
|
278
|
+
/**
|
|
279
|
+
* Called when an animation of this widget ends, whether it played through
|
|
280
|
+
* or not (see `completed`): to remember what it did, like a trophy for
|
|
281
|
+
* a set that got built. Synchronous and quick; keep files under `dataDir`.
|
|
282
|
+
*/
|
|
283
|
+
animationEnded?: (ctx: AnimationEndContext<Infer<OF>, D>) => void;
|
|
284
|
+
/** How long to wait between the `idle` questions of `animation`, a random time in the range. Default 20-60 s. */
|
|
285
|
+
animationGap?: { minMs: number; maxMs: number };
|
|
286
|
+
/** Minimum time from the end of an animation to the next one asked because of a data change. Default 0. */
|
|
287
|
+
animationCooldownMs?: number;
|
|
188
288
|
/** Also a function, when the cadence depends on the options or the data (a carousel every `rotateMs`). */
|
|
189
289
|
redraw?: Redraw | ((ctx: StateContext<Infer<OF>, D>) => Redraw);
|
|
190
290
|
/** Has nothing to show right now (nothing playing, no rain): skipped in its cell's rotation. */
|
|
@@ -261,6 +361,23 @@ export interface SourceDefinition<OF extends ObjectField<any> = ObjectField<any>
|
|
|
261
361
|
*/
|
|
262
362
|
watch?: (ctx: SourceContext<Infer<OF>>, emit: (data: D) => void) => () => void;
|
|
263
363
|
demo?: (ctx: { now: number; locale: string }) => D;
|
|
364
|
+
/**
|
|
365
|
+
* Named lists of values for the editor to offer in options, made from
|
|
366
|
+
* this source's latest data (or its demo data before there is any): the
|
|
367
|
+
* entities of a Home Assistant, the calendars read, the repos seen. A
|
|
368
|
+
* field asks for one with `choices: { source: 'plugin/source', list }`.
|
|
369
|
+
* Plain and quick: they run when the editor opens a form.
|
|
370
|
+
*/
|
|
371
|
+
choices?: Record<string, (data: D, ctx: { locale: string; t: (text: Localized) => string }) => Choice[]>;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** One value the editor offers for an option (see `SourceDefinition.choices`). */
|
|
375
|
+
export interface Choice {
|
|
376
|
+
value: string;
|
|
377
|
+
/** What the person sees, when it isn't the value itself (`Living room` for `sensor.living_room`). */
|
|
378
|
+
label?: string;
|
|
379
|
+
/** Heading to group it under (`Sensors`, `Lights`). */
|
|
380
|
+
group?: string;
|
|
264
381
|
}
|
|
265
382
|
|
|
266
383
|
export interface InterludePlayer {
|
|
@@ -296,6 +413,67 @@ export interface InterludeDefinition<OF extends ObjectField<any> = ObjectField<a
|
|
|
296
413
|
skip?: (ctx: { sources: Record<string, unknown>; now: number; options: Infer<OF> }) => boolean;
|
|
297
414
|
}
|
|
298
415
|
|
|
416
|
+
/**
|
|
417
|
+
* The version of the plugin API this Kiosko speaks. A plugin says which
|
|
418
|
+
* versions it was written for in `PluginDefinition.sdk` (and in its
|
|
419
|
+
* package.json, `"kiosko": { "sdk": "^0.2.0" }`, so it can be refused before
|
|
420
|
+
* it runs); the registry compares them with `satisfies`.
|
|
421
|
+
*/
|
|
422
|
+
export const SDK_VERSION = '0.2.2';
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* What a plugin does on the machine, declared for the person who installs
|
|
426
|
+
* it: the Plugins page and the plugin store show it next to the plugin. It
|
|
427
|
+
* is a promise, not (yet) a fence: plugins run with the user's rights. Keep
|
|
428
|
+
* it honest and small; options with a `risk` (see `Risk`) are listed apart.
|
|
429
|
+
*/
|
|
430
|
+
export interface Permissions {
|
|
431
|
+
/**
|
|
432
|
+
* Hosts it contacts on its own: exact names (`api.github.com`,
|
|
433
|
+
* `*.open-meteo.com`), `user` for the hosts the user types in its options
|
|
434
|
+
* (a feed, a Home Assistant), `lan` for the local network.
|
|
435
|
+
*/
|
|
436
|
+
network?: string[];
|
|
437
|
+
/** Programs it runs (`nvidia-smi`, `pactl`, `ssh`); `user` for a command the user configures. */
|
|
438
|
+
exec?: string[];
|
|
439
|
+
/** Files or folders it reads or writes besides its own `dataDir`/`cacheDir` (`~/.aimonitor/sessions`); `user` for paths the user configures. */
|
|
440
|
+
files?: string[];
|
|
441
|
+
/** Hardware or system services it talks to: `usb`, `audio` (whether the microphone is in use), `mpris` (what is playing), `bluetooth`… */
|
|
442
|
+
devices?: string[];
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** One tile of a page template, in fractions of the page (0..1). */
|
|
446
|
+
export interface TemplateTile {
|
|
447
|
+
x: number;
|
|
448
|
+
y: number;
|
|
449
|
+
w: number;
|
|
450
|
+
h: number;
|
|
451
|
+
/** Widget types, stacked; a bare id (`clock`) is this plugin's own. With options: `['clock', { showDate: true }]`. */
|
|
452
|
+
widgets: (string | [string, Record<string, unknown>])[];
|
|
453
|
+
chrome?: 'card' | 'bare';
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* A starting layout the editor offers under "New page", made of this
|
|
458
|
+
* plugin's widgets (and others', if installed: tiles whose widgets are all
|
|
459
|
+
* missing are left out).
|
|
460
|
+
*/
|
|
461
|
+
export interface PageTemplate {
|
|
462
|
+
/** Unique inside the plugin. */
|
|
463
|
+
id: string;
|
|
464
|
+
name: Localized;
|
|
465
|
+
/** An icon of the editor (Lucide name). */
|
|
466
|
+
icon?: string;
|
|
467
|
+
/** For strips and wide panels. */
|
|
468
|
+
wide: TemplateTile[];
|
|
469
|
+
/** For square-ish panels; defaults to `wide`. */
|
|
470
|
+
square?: TemplateTile[];
|
|
471
|
+
/** For portrait panels; defaults to `wide` turned a quarter (columns become bands). */
|
|
472
|
+
tall?: TemplateTile[];
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
export type Platform = 'linux' | 'darwin' | 'win32';
|
|
476
|
+
|
|
299
477
|
export interface PluginDefinition {
|
|
300
478
|
/** npm-like id: lowercase, digits and dashes. Stable: configs refer to it. */
|
|
301
479
|
id: string;
|
|
@@ -304,11 +482,37 @@ export interface PluginDefinition {
|
|
|
304
482
|
description?: Localized;
|
|
305
483
|
author?: string;
|
|
306
484
|
homepage?: string;
|
|
485
|
+
/** Where its code lives (a git URL): the store links to it. */
|
|
486
|
+
repository?: string;
|
|
307
487
|
license?: string;
|
|
308
488
|
icon?: string;
|
|
489
|
+
/**
|
|
490
|
+
* The plugin API versions it works with, as an npm range (`^0.2.0`).
|
|
491
|
+
* Without it, any Kiosko is assumed to fit. Put the same in package.json
|
|
492
|
+
* (`"kiosko": { "sdk": … }`) so an incompatible plugin is refused before
|
|
493
|
+
* its code runs.
|
|
494
|
+
*/
|
|
495
|
+
sdk?: string;
|
|
496
|
+
/** What it does on the machine (see `Permissions`). */
|
|
497
|
+
permissions?: Permissions;
|
|
498
|
+
/**
|
|
499
|
+
* Sources or widgets of other plugins it needs (`agents/sessions`): the
|
|
500
|
+
* editor says which are missing and offers to install their plugins.
|
|
501
|
+
*/
|
|
502
|
+
requires?: string[];
|
|
503
|
+
/**
|
|
504
|
+
* Sources or widgets of other plugins it uses when they are there, and
|
|
505
|
+
* does without otherwise (the weather in a corner): never asked for, only
|
|
506
|
+
* mentioned.
|
|
507
|
+
*/
|
|
508
|
+
optional?: string[];
|
|
509
|
+
/** The operating systems it works on. Omitted: all. Also npm's `os` in package.json. */
|
|
510
|
+
platforms?: Platform[];
|
|
309
511
|
widgets?: WidgetDefinition<any, any>[];
|
|
310
512
|
sources?: SourceDefinition<any, any>[];
|
|
311
513
|
interludes?: InterludeDefinition<any>[];
|
|
514
|
+
/** Page layouts the editor offers, built from its widgets (see `PageTemplate`). */
|
|
515
|
+
templates?: PageTemplate[];
|
|
312
516
|
}
|
|
313
517
|
|
|
314
518
|
/* Identity helpers: they only exist so TypeScript infers option and data types. */
|
package/src/schema.ts
CHANGED
|
@@ -38,9 +38,24 @@ interface Common<T> {
|
|
|
38
38
|
risk?: Risk | readonly Risk[];
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
+
/**
|
|
42
|
+
* Where the editor finds values to offer for a text field: a named list of
|
|
43
|
+
* a source (see `SourceDefinition.choices`), computed from its live data,
|
|
44
|
+
* e.g. the entities of the user's Home Assistant. The field stays free
|
|
45
|
+
* text: a value that isn't in the list is kept.
|
|
46
|
+
*/
|
|
47
|
+
export interface ChoicesRef {
|
|
48
|
+
/** `plugin/source`. */
|
|
49
|
+
source: string;
|
|
50
|
+
/** The name of the list in that source's `choices`. */
|
|
51
|
+
list: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
41
54
|
export interface StringField extends Common<string> {
|
|
42
55
|
kind: 'string';
|
|
43
56
|
placeholder?: string;
|
|
57
|
+
/** Values to offer, from a source's live data (see `ChoicesRef`). */
|
|
58
|
+
choices?: ChoicesRef;
|
|
44
59
|
multiline?: boolean;
|
|
45
60
|
/** Tokens, URLs with credentials…: masked in the editor and never logged. */
|
|
46
61
|
secret?: boolean;
|
|
@@ -123,9 +138,9 @@ export const t = {
|
|
|
123
138
|
* `repos`, `calendars`, `people`) and give it a `label`; the `help`
|
|
124
139
|
* explaining the patterns comes with it.
|
|
125
140
|
*/
|
|
126
|
-
filter: (o: Opts<ListField<StringField>, 'item'> = {}): ListField<StringField> => ({
|
|
141
|
+
filter: ({ choices, ...o }: Opts<ListField<StringField>, 'item'> & { choices?: ChoicesRef } = {}): ListField<StringField> => ({
|
|
127
142
|
kind: 'list',
|
|
128
|
-
item: { kind: 'string', default: '', placeholder: 'name, group/*, !old-*' },
|
|
143
|
+
item: { kind: 'string', default: '', placeholder: 'name, group/*, !old-*', ...(choices ? { choices } : {}) },
|
|
129
144
|
default: [],
|
|
130
145
|
filter: true,
|
|
131
146
|
help: FILTER_HELP,
|
|
@@ -238,7 +253,7 @@ export function toJsonSchema(f: Field): Record<string, unknown> {
|
|
|
238
253
|
};
|
|
239
254
|
switch (f.kind) {
|
|
240
255
|
case 'string':
|
|
241
|
-
return { ...base, type: 'string', ...(f.format === 'date' ? { format: 'date' } : {}), ...(f.maxLength ? { maxLength: f.maxLength } : {}), 'x-ui': { ...ui, secret: f.secret, multiline: f.multiline, placeholder: f.placeholder, format: f.format } };
|
|
256
|
+
return { ...base, type: 'string', ...(f.format === 'date' ? { format: 'date' } : {}), ...(f.maxLength ? { maxLength: f.maxLength } : {}), 'x-ui': { ...ui, secret: f.secret, multiline: f.multiline, placeholder: f.placeholder, format: f.format, choices: f.choices } };
|
|
242
257
|
case 'color':
|
|
243
258
|
return { ...base, type: 'string', 'x-ui': { ...ui, widget: 'color' } };
|
|
244
259
|
case 'number':
|
|
@@ -248,7 +263,7 @@ export function toJsonSchema(f: Field): Record<string, unknown> {
|
|
|
248
263
|
case 'enum':
|
|
249
264
|
return { ...base, type: 'string', enum: [...f.values], 'x-ui': { ...ui, labels: f.labels } };
|
|
250
265
|
case 'list':
|
|
251
|
-
return { ...base, type: 'array', items: toJsonSchema(f.item), maxItems: f.max, ...(f.filter ? { 'x-ui': { ...ui, widget: 'filter' }, 'x-filter': true } : {}) };
|
|
266
|
+
return { ...base, type: 'array', items: toJsonSchema(f.item), maxItems: f.max, ...(f.filter ? { 'x-ui': { ...ui, widget: 'filter', choices: f.item.kind === 'string' ? f.item.choices : undefined }, 'x-filter': true } : {}) };
|
|
252
267
|
case 'map':
|
|
253
268
|
return { ...base, type: 'object', additionalProperties: { type: 'string' } };
|
|
254
269
|
case 'object':
|
package/src/semver.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Just enough semver to say whether a plugin fits this Kiosko: versions
|
|
3
|
+
* `1.2.3` (a pre-release such as `1.2.3-beta.1` sorts before its release),
|
|
4
|
+
* and ranges as npm writes them in package.json:
|
|
5
|
+
*
|
|
6
|
+
* ^0.2.0 >=0.2.0 <0.3.0 (caret: the left-most non-zero part is fixed)
|
|
7
|
+
* ~0.2.1 >=0.2.1 <0.3.0
|
|
8
|
+
* 0.2 · 0.2.x · * wildcards
|
|
9
|
+
* >=0.2.0 <1 comparators, space-separated (all must hold)
|
|
10
|
+
* ^0.2 || ^1 alternatives
|
|
11
|
+
*
|
|
12
|
+
* No dependencies, so the registry can check a plugin before running it.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
type V = [number, number, number, string];
|
|
16
|
+
|
|
17
|
+
/** `1.2.3` → its parts; null when it isn't a version. */
|
|
18
|
+
export function parseVersion(s: string): V | null {
|
|
19
|
+
const m = /^\s*v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?\s*$/.exec(s);
|
|
20
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ?? ''] : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** -1, 0 or 1. A pre-release sorts before the release of the same numbers. */
|
|
24
|
+
export function compareVersions(a: string, b: string): number {
|
|
25
|
+
const x = parseVersion(a), y = parseVersion(b);
|
|
26
|
+
if (!x || !y) return 0;
|
|
27
|
+
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return (x[i] as number) < (y[i] as number) ? -1 : 1;
|
|
28
|
+
if (x[3] === y[3]) return 0;
|
|
29
|
+
if (!x[3]) return 1;
|
|
30
|
+
if (!y[3]) return -1;
|
|
31
|
+
return x[3] < y[3] ? -1 : 1;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type Cmp = { op: '>=' | '>' | '<=' | '<' | '='; v: string };
|
|
35
|
+
|
|
36
|
+
/** A partial version (`1`, `1.2`, `1.x`) as its parts, `undefined` for the missing or wild ones. */
|
|
37
|
+
function partial(s: string): [number | undefined, number | undefined, number | undefined, string] | null {
|
|
38
|
+
const m = /^\s*v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?\s*$/.exec(s);
|
|
39
|
+
if (!m) return null;
|
|
40
|
+
const n = (p: string | undefined) => (p === undefined || /^[xX*]$/.test(p) ? undefined : Number(p));
|
|
41
|
+
return [n(m[1]), n(m[2]), n(m[3]), m[4] ?? ''];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const ver = (a: number, b: number, c: number, pre = '') => `${a}.${b}.${c}${pre ? `-${pre}` : ''}`;
|
|
45
|
+
|
|
46
|
+
/** One space-separated set of comparators → plain `op version` pairs. */
|
|
47
|
+
function comparators(set: string): Cmp[] | null {
|
|
48
|
+
const out: Cmp[] = [];
|
|
49
|
+
const tokens = set.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/).filter(Boolean);
|
|
50
|
+
if (!tokens.length) return [{ op: '>=', v: '0.0.0' }];
|
|
51
|
+
for (const tk of tokens) {
|
|
52
|
+
const m = /^(>=|<=|>|<|=|\^|~)?(.*)$/.exec(tk)!;
|
|
53
|
+
const op = m[1] ?? '';
|
|
54
|
+
const p = partial(m[2]!);
|
|
55
|
+
if (!p) return null;
|
|
56
|
+
const [ma, mi, pa, pre] = p;
|
|
57
|
+
if (ma === undefined) {
|
|
58
|
+
out.push({ op: '>=', v: '0.0.0' });
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (op === '^') {
|
|
62
|
+
const lo = ver(ma, mi ?? 0, pa ?? 0, pre);
|
|
63
|
+
const hi = ma > 0 || mi === undefined ? ver(ma + 1, 0, 0) : mi > 0 || pa === undefined ? ver(0, mi + 1, 0) : ver(0, 0, pa + 1);
|
|
64
|
+
out.push({ op: '>=', v: lo }, { op: '<', v: `${hi}-0` });
|
|
65
|
+
} else if (op === '~') {
|
|
66
|
+
const lo = ver(ma, mi ?? 0, pa ?? 0, pre);
|
|
67
|
+
const hi = mi === undefined ? ver(ma + 1, 0, 0) : ver(ma, mi + 1, 0);
|
|
68
|
+
out.push({ op: '>=', v: lo }, { op: '<', v: `${hi}-0` });
|
|
69
|
+
} else if (op === '' || op === '=') {
|
|
70
|
+
if (mi === undefined) out.push({ op: '>=', v: ver(ma, 0, 0) }, { op: '<', v: `${ver(ma + 1, 0, 0)}-0` });
|
|
71
|
+
else if (pa === undefined) out.push({ op: '>=', v: ver(ma, mi, 0) }, { op: '<', v: `${ver(ma, mi + 1, 0)}-0` });
|
|
72
|
+
else out.push({ op: '=', v: ver(ma, mi, pa, pre) });
|
|
73
|
+
} else {
|
|
74
|
+
// >1.2 means >=1.3.0; <=1.2 means <1.3.0.
|
|
75
|
+
if (pa === undefined && (op === '>' || op === '<=')) {
|
|
76
|
+
const next = mi === undefined ? ver(ma + 1, 0, 0) : ver(ma, mi + 1, 0);
|
|
77
|
+
out.push(op === '>' ? { op: '>=', v: next } : { op: '<', v: `${next}-0` });
|
|
78
|
+
} else out.push({ op: op as Cmp['op'], v: ver(ma, mi ?? 0, pa ?? 0, pre) });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Whether `version` is in `range`. A pre-release only matches a range that
|
|
86
|
+
* names a pre-release of the same numbers (npm's rule), so `0.3.0-beta` does
|
|
87
|
+
* not quietly satisfy `^0.2`. An unreadable range or version is `false`.
|
|
88
|
+
*/
|
|
89
|
+
export function satisfies(version: string, range: string): boolean {
|
|
90
|
+
const v = parseVersion(version);
|
|
91
|
+
if (!v) return false;
|
|
92
|
+
return range.split('||').some((set) => {
|
|
93
|
+
const cs = comparators(set);
|
|
94
|
+
if (!cs) return false;
|
|
95
|
+
const ok = cs.every(({ op, v: w }) => {
|
|
96
|
+
const c = compareVersions(version, w);
|
|
97
|
+
return op === '>=' ? c >= 0 : op === '>' ? c > 0 : op === '<=' ? c <= 0 : op === '<' ? c < 0 : c === 0;
|
|
98
|
+
});
|
|
99
|
+
if (!ok || !v[3]) return ok;
|
|
100
|
+
return cs.some(({ v: w }) => {
|
|
101
|
+
const x = parseVersion(w);
|
|
102
|
+
return !!x && !!x[3] && x[3] !== '0' && x[0] === v[0] && x[1] === v[1] && x[2] === v[2];
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
}
|
package/src/system.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small helpers for what differs between operating systems, shared by Kiosko
|
|
3
|
+
* and by plugins (`import { expandPath, commandFor } from '@kiosko/sdk'`).
|
|
4
|
+
*/
|
|
5
|
+
import { statSync } from 'node:fs';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { join, win32 } from 'node:path';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `~`, `~/x` (and `~\x`), `$VAR`, `${VAR}` and, on Windows, `%VAR%` expanded.
|
|
11
|
+
* A variable that isn't set stays as written. `os` and `env` are for tests.
|
|
12
|
+
*/
|
|
13
|
+
export function expandPath(p: string, o: { os?: NodeJS.Platform; env?: Record<string, string | undefined>; home?: string } = {}): string {
|
|
14
|
+
const env = o.env ?? process.env;
|
|
15
|
+
let v = p.replace(/\$(?:\{(\w+)\}|(\w+))/g, (whole, a?: string, b?: string) => env[a ?? b ?? ''] ?? whole);
|
|
16
|
+
// `%VAR%` is a Windows thing; on other systems a `%` is just a character.
|
|
17
|
+
if ((o.os ?? process.platform) === 'win32') v = v.replace(/%([^%\r\n]+)%/g, (whole, name: string) => env[name] ?? whole);
|
|
18
|
+
const home = o.home ?? homedir();
|
|
19
|
+
if (v === '~') return home;
|
|
20
|
+
return v.startsWith('~/') || v.startsWith('~\\') ? join(home, v.slice(2)) : v;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** What to hand to `execFile` to run `cmd` with `args`. */
|
|
24
|
+
export interface Command {
|
|
25
|
+
file: string;
|
|
26
|
+
args: string[];
|
|
27
|
+
/** Pass as `windowsVerbatimArguments` to `execFile`/`spawn`. */
|
|
28
|
+
windowsVerbatimArguments?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Characters cmd.exe would interpret inside a batch shim's arguments. */
|
|
32
|
+
const CMD_UNSAFE = /["%\r\n\0]/;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* On Windows, tools installed with npm (`ccusage`, `npx`, `claude`…) are
|
|
36
|
+
* `.cmd` shims, and `execFile('ccusage')` neither finds them (no `PATHEXT`
|
|
37
|
+
* search) nor, since Node 18.20 / 20.12, runs a `.cmd` without a shell.
|
|
38
|
+
* `commandFor` returns the pair to pass to `execFile`: for a `.cmd`/`.bat`
|
|
39
|
+
* (looked up on `PATH`), `cmd.exe /d /s /c "…"` with each argument quoted; for
|
|
40
|
+
* anything else, the command as it was. Elsewhere it changes nothing.
|
|
41
|
+
*
|
|
42
|
+
* const c = commandFor('ccusage', ['daily', '--json']);
|
|
43
|
+
* execFile(c.file, c.args, { windowsHide: true, windowsVerbatimArguments: c.windowsVerbatimArguments }, cb);
|
|
44
|
+
*
|
|
45
|
+
* Throws if an argument holds a quote, a `%` or a line break and the command needs
|
|
46
|
+
* cmd.exe: there is no safe way to pass those through a batch file.
|
|
47
|
+
*/
|
|
48
|
+
export function commandFor(
|
|
49
|
+
cmd: string,
|
|
50
|
+
args: string[],
|
|
51
|
+
o: { os?: NodeJS.Platform; env?: Record<string, string | undefined>; exists?: (path: string) => boolean } = {},
|
|
52
|
+
): Command {
|
|
53
|
+
if ((o.os ?? process.platform) !== 'win32') return { file: cmd, args };
|
|
54
|
+
const env = o.env ?? process.env;
|
|
55
|
+
const exists = o.exists ?? defaultExists;
|
|
56
|
+
const shim = findShim(cmd, env, exists);
|
|
57
|
+
if (!shim) return { file: cmd, args };
|
|
58
|
+
for (const a of args) if (CMD_UNSAFE.test(a)) throw new Error(`argument not allowed for ${cmd}: ${JSON.stringify(a)}`);
|
|
59
|
+
const quote = (s: string) => (/^[\w@+=:,./\\-]+$/.test(s) ? s : `"${s}"`);
|
|
60
|
+
return { file: env.ComSpec || 'cmd.exe', args: ['/d', '/s', '/c', `"${[shim, ...args].map(quote).join(' ')}"`], windowsVerbatimArguments: true };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function defaultExists(path: string): boolean {
|
|
64
|
+
try {
|
|
65
|
+
// Sync and tiny: a handful of PATH entries, once per call.
|
|
66
|
+
return statSync(path).isFile();
|
|
67
|
+
} catch {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The `.cmd`/`.bat` that `cmd` names on Windows, or null if it is (or may be) an executable. */
|
|
73
|
+
function findShim(cmd: string, env: Record<string, string | undefined>, exists: (p: string) => boolean): string | null {
|
|
74
|
+
if (/\.(exe|com)$/i.test(cmd)) return null;
|
|
75
|
+
if (/\.(cmd|bat)$/i.test(cmd) && /[\\/]/.test(cmd)) return exists(cmd) ? cmd : null;
|
|
76
|
+
const dirs = /[\\/]/.test(cmd) ? [''] : (env.PATH ?? env.Path ?? '').split(';').filter(Boolean);
|
|
77
|
+
const exts = (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
|
|
78
|
+
for (const dir of dirs) {
|
|
79
|
+
const base = dir ? win32.join(dir, cmd) : cmd;
|
|
80
|
+
for (const ext of /\.\w+$/.test(cmd) ? [''] : exts) {
|
|
81
|
+
const p = base + ext.toLowerCase();
|
|
82
|
+
if (!exists(p)) continue;
|
|
83
|
+
return /\.(cmd|bat)$/i.test(p) ? p : null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|