@kiosko/sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context.d.ts +19 -0
- package/dist/context.js +23 -0
- package/dist/filter.d.ts +26 -0
- package/dist/filter.js +53 -0
- package/dist/format.d.ts +59 -0
- package/dist/format.js +87 -0
- package/dist/i18n.d.ts +9 -0
- package/dist/i18n.js +8 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/list.d.ts +133 -0
- package/dist/list.js +126 -0
- package/dist/location.d.ts +26 -0
- package/dist/location.js +33 -0
- package/dist/plugin.d.ts +314 -0
- package/dist/plugin.js +24 -0
- package/dist/schema.d.ts +155 -0
- package/dist/schema.js +169 -0
- package/dist/theme.d.ts +47 -0
- package/dist/theme.js +49 -0
- package/dist/workday.d.ts +48 -0
- package/dist/workday.js +40 -0
- package/package.json +47 -4
- package/src/context.ts +25 -0
- package/src/filter.ts +56 -0
- package/src/format.ts +123 -0
- package/src/i18n.ts +13 -0
- package/src/index.ts +10 -0
- package/src/list.ts +217 -0
- package/src/location.ts +41 -0
- package/src/plugin.ts +329 -0
- package/src/schema.ts +264 -0
- package/src/theme.ts +98 -0
- package/src/workday.ts +79 -0
- package/README.md +0 -3
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin contract.
|
|
3
|
+
*
|
|
4
|
+
* A plugin is an ES module whose default export is `definePlugin({...})`. It
|
|
5
|
+
* can contribute three kinds of things:
|
|
6
|
+
*
|
|
7
|
+
* - **widgets**: paint inside a rectangle of the screen (a cell of the
|
|
8
|
+
* grid). Optionally fetch their own data on a timer.
|
|
9
|
+
* - **sources**: shared data (agent sessions, system vitals, weather…)
|
|
10
|
+
* read once and handed to every widget that asks for it, so ten widgets
|
|
11
|
+
* showing the CPU don't read /proc ten times.
|
|
12
|
+
* - **interludes**: full-screen animations the screen plays now and then
|
|
13
|
+
* (the 8-bit runner every quarter hour, a video clip…).
|
|
14
|
+
*
|
|
15
|
+
* Everything a widget needs arrives in its context: options already
|
|
16
|
+
* validated, data, theme, fonts, the drawing kit and the canvas factory.
|
|
17
|
+
* A plugin must not import its own copy of @napi-rs/canvas: images from
|
|
18
|
+
* another copy can't be drawn on the panel's canvas.
|
|
19
|
+
*/
|
|
20
|
+
import type { Canvas, Image, SKRSContext2D, createCanvas, loadImage } from '@napi-rs/canvas';
|
|
21
|
+
import type * as Kit from '@loksly/lcd-canvas-kit';
|
|
22
|
+
import type { Formatters } from './format.ts';
|
|
23
|
+
import type { Localized } from './i18n.ts';
|
|
24
|
+
import type { Field, Infer, ObjectField } from './schema.ts';
|
|
25
|
+
import type { Theme } from './theme.ts';
|
|
26
|
+
import type { Workday } from './workday.ts';
|
|
27
|
+
/** The 2D context widgets paint with. Same API as the browser's CanvasRenderingContext2D. */
|
|
28
|
+
export type Graphics = SKRSContext2D;
|
|
29
|
+
export type { Canvas, Image };
|
|
30
|
+
export interface CanvasApi {
|
|
31
|
+
createCanvas: typeof createCanvas;
|
|
32
|
+
loadImage: typeof loadImage;
|
|
33
|
+
}
|
|
34
|
+
/** A rectangle in panel pixels. */
|
|
35
|
+
export interface Box {
|
|
36
|
+
x: number;
|
|
37
|
+
y: number;
|
|
38
|
+
w: number;
|
|
39
|
+
h: number;
|
|
40
|
+
}
|
|
41
|
+
/** Size in panel pixels. */
|
|
42
|
+
export interface Size {
|
|
43
|
+
w: number;
|
|
44
|
+
h: number;
|
|
45
|
+
}
|
|
46
|
+
export type Category = 'agents' | 'system' | 'time' | 'productivity' | 'dev' | 'info' | 'media' | 'scene' | 'fun';
|
|
47
|
+
export declare const CATEGORIES: {
|
|
48
|
+
id: Category;
|
|
49
|
+
label: Localized;
|
|
50
|
+
}[];
|
|
51
|
+
export interface Logger {
|
|
52
|
+
(msg: string): void;
|
|
53
|
+
}
|
|
54
|
+
/** A place on Earth, in degrees. */
|
|
55
|
+
export interface Location {
|
|
56
|
+
latitude: number;
|
|
57
|
+
longitude: number;
|
|
58
|
+
/** Shown by some widgets, e.g. "Madrid". */
|
|
59
|
+
name?: string;
|
|
60
|
+
}
|
|
61
|
+
/** What every context has. */
|
|
62
|
+
export interface BaseContext {
|
|
63
|
+
now: number;
|
|
64
|
+
/** BCP-47 language of the user (`es`, `en-GB`…). */
|
|
65
|
+
locale: string;
|
|
66
|
+
/** Picks the user's language from a `Localized` text. */
|
|
67
|
+
t: (text: Localized) => string;
|
|
68
|
+
/**
|
|
69
|
+
* Times and lengths of time in the user's language and clock (Settings →
|
|
70
|
+
* time format): `fmt.time(at)` "14:05" / "2:05 PM", `fmt.ago(at)`
|
|
71
|
+
* "5 min ago", `fmt.duration(ms)` "1 h 05". Use these rather than your own.
|
|
72
|
+
*/
|
|
73
|
+
fmt: Formatters;
|
|
74
|
+
log: Logger;
|
|
75
|
+
/** Where the plugin may keep files (caches, downloads). Created on demand. */
|
|
76
|
+
dataDir: string;
|
|
77
|
+
/**
|
|
78
|
+
* The user's place, if set in Settings (weather, sun, earthquakes…). Use it
|
|
79
|
+
* by default; offer a place of your own only where a second one makes sense
|
|
80
|
+
* (an advanced override), with an empty or 0,0 value meaning "this one".
|
|
81
|
+
*/
|
|
82
|
+
location?: Location;
|
|
83
|
+
/**
|
|
84
|
+
* The user's working week from Settings: days, start and end, hours due,
|
|
85
|
+
* days with other hours and holidays. Default to it instead of asking for
|
|
86
|
+
* your own schedule; `scheduleOn(ctx.workday, now)` gives one day's.
|
|
87
|
+
*/
|
|
88
|
+
workday: Workday;
|
|
89
|
+
}
|
|
90
|
+
export interface FetchContext<O> extends BaseContext {
|
|
91
|
+
options: O;
|
|
92
|
+
canvas: CanvasApi;
|
|
93
|
+
/** Aborted when the widget is removed, the app stops, or this fetch takes longer than `timeoutMs`. Pass it to `fetch` and child processes. */
|
|
94
|
+
signal: AbortSignal;
|
|
95
|
+
/** How long this fetch may take (the widget's `timeoutMs`), for a per-request budget of your own. */
|
|
96
|
+
timeoutMs: number;
|
|
97
|
+
/** Latest data of the sources the widget declared. */
|
|
98
|
+
sources: Record<string, unknown>;
|
|
99
|
+
}
|
|
100
|
+
export interface StateContext<O, D> {
|
|
101
|
+
options: O;
|
|
102
|
+
data: D | undefined;
|
|
103
|
+
sources: Record<string, unknown>;
|
|
104
|
+
now: number;
|
|
105
|
+
/** True for a work-hours slot, per the user's work schedule. */
|
|
106
|
+
working: boolean;
|
|
107
|
+
/** The user's working week (see `BaseContext.workday`); tests can pass `DEFAULT_WORKDAY`. */
|
|
108
|
+
workday: Workday;
|
|
109
|
+
/** The user's place, if set (see `BaseContext.location`). */
|
|
110
|
+
location?: Location;
|
|
111
|
+
}
|
|
112
|
+
export interface RenderContext<O, D> extends BaseContext, StateContext<O, D> {
|
|
113
|
+
/** Where to paint, already inside the card's padding and title. */
|
|
114
|
+
box: Box;
|
|
115
|
+
theme: Theme;
|
|
116
|
+
/** Families registered on the panel; same as `theme.fonts`. */
|
|
117
|
+
fonts: Theme['fonts'];
|
|
118
|
+
/** Helpers from @loksly/lcd-canvas-kit: tracked text, wrapping, sparklines, weather icons… */
|
|
119
|
+
kit: typeof Kit;
|
|
120
|
+
canvas: CanvasApi;
|
|
121
|
+
/** The widget is drawn in the editor (gallery thumbnail or live preview) and not on the panel. */
|
|
122
|
+
preview: boolean;
|
|
123
|
+
/** Frame index while an animation requested with `animate` is running. */
|
|
124
|
+
frame?: number;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* When the widget must be repainted even though its data didn't change: a
|
|
128
|
+
* clock every second, a countdown every minute. Fewer repaints are fewer
|
|
129
|
+
* frames over USB, so pick the slowest that still looks right.
|
|
130
|
+
*/
|
|
131
|
+
export type Redraw = 'never' | 'minute' | 'second' | {
|
|
132
|
+
everyMs: number;
|
|
133
|
+
};
|
|
134
|
+
export interface WidgetDefinition<OF extends ObjectField<any> = ObjectField<any>, D = unknown> {
|
|
135
|
+
/** Unique inside its plugin: `clock`, `sessions`… The full type is `plugin/widget`. */
|
|
136
|
+
id: string;
|
|
137
|
+
name: Localized;
|
|
138
|
+
description?: Localized;
|
|
139
|
+
/** Name of an icon of the editor (see web/icons) or an inline SVG string. */
|
|
140
|
+
icon?: string;
|
|
141
|
+
category?: Category;
|
|
142
|
+
tags?: string[];
|
|
143
|
+
/**
|
|
144
|
+
* Sizes in panel pixels. `min` is a hard limit enforced by the editor;
|
|
145
|
+
* `preferred` is what it uses when the widget is dropped.
|
|
146
|
+
*/
|
|
147
|
+
size?: {
|
|
148
|
+
min?: Size;
|
|
149
|
+
preferred?: Size;
|
|
150
|
+
max?: Size;
|
|
151
|
+
};
|
|
152
|
+
/** How the cell frames it: a card with optional title (default) or bare, edge to edge (scenes, photos). */
|
|
153
|
+
chrome?: 'card' | 'bare';
|
|
154
|
+
/** Options, as a schema: typed, validated and turned into a form by the editor. */
|
|
155
|
+
options?: OF;
|
|
156
|
+
/** Ids of shared sources (`plugin/source`) whose data the widget receives in `ctx.sources`. */
|
|
157
|
+
sources?: string[];
|
|
158
|
+
/** Own data, per instance. Runs in Node, never blocks the panel. */
|
|
159
|
+
fetch?: (ctx: FetchContext<Infer<OF>>) => Promise<D>;
|
|
160
|
+
/** How often `fetch` runs. Default: 10 minutes. The user can override it. */
|
|
161
|
+
intervalMs?: number;
|
|
162
|
+
/**
|
|
163
|
+
* How often `fetch` runs when that depends on the options or on the latest
|
|
164
|
+
* data (a module that declares its own interval): asked after every fetch;
|
|
165
|
+
* `undefined` keeps `intervalMs`. An interval the user set on the instance
|
|
166
|
+
* wins. Never under 5 s.
|
|
167
|
+
*/
|
|
168
|
+
intervalOf?: (ctx: {
|
|
169
|
+
options: Infer<OF>;
|
|
170
|
+
data: NoInfer<D> | undefined;
|
|
171
|
+
}) => number | undefined;
|
|
172
|
+
/** Longest one `fetch` may take before its `signal` aborts and it counts as failed. Default: 2 minutes. */
|
|
173
|
+
timeoutMs?: number;
|
|
174
|
+
/** Paint. Synchronous and fast: load images in `fetch` and paint them here. */
|
|
175
|
+
render: (g: Graphics, ctx: RenderContext<Infer<OF>, D>) => void;
|
|
176
|
+
/** Also a function, when the cadence depends on the options or the data (a carousel every `rotateMs`). */
|
|
177
|
+
redraw?: Redraw | ((ctx: StateContext<Infer<OF>, D>) => Redraw);
|
|
178
|
+
/** Has nothing to show right now (nothing playing, no rain): skipped in its cell's rotation. */
|
|
179
|
+
visible?: (ctx: StateContext<Infer<OF>, D>) => boolean;
|
|
180
|
+
/**
|
|
181
|
+
* Needs the user now (a meeting about to start): takes its cell over while
|
|
182
|
+
* true, unless the user turned the widget's "keep the tile while urgent"
|
|
183
|
+
* switch (`takeOver`) off. Don't add an option of your own for that.
|
|
184
|
+
*/
|
|
185
|
+
urgent?: (ctx: StateContext<Infer<OF>, D>) => boolean;
|
|
186
|
+
/** Default of the instance's `takeOver` switch (keep the tile while urgent). Default true. */
|
|
187
|
+
takeOver?: boolean;
|
|
188
|
+
/**
|
|
189
|
+
* Has nothing to list right now (no reviews, no tasks). Declaring it gives
|
|
190
|
+
* the widget a "hide when empty" switch (`hideWhenEmpty`): when on, an
|
|
191
|
+
* empty widget is skipped in its tile's rotation like `visible: false`;
|
|
192
|
+
* when off, it paints its empty message (`drawEmpty`). Unlike `visible`,
|
|
193
|
+
* which is the widget's own decision, this one is the user's.
|
|
194
|
+
*/
|
|
195
|
+
empty?: (ctx: StateContext<Infer<OF>, D>) => boolean;
|
|
196
|
+
/** Default of the instance's `hideWhenEmpty` switch. Default false. */
|
|
197
|
+
hideWhenEmpty?: boolean;
|
|
198
|
+
/**
|
|
199
|
+
* Nothing worth lighting the panel for. When every widget of the page is
|
|
200
|
+
* idle and the screen has `sleepWhenIdle`, the panel goes black.
|
|
201
|
+
*/
|
|
202
|
+
idle?: (ctx: StateContext<Infer<OF>, D>) => boolean;
|
|
203
|
+
/**
|
|
204
|
+
* Sample data for the gallery, the editor and the tests, so a widget can
|
|
205
|
+
* be seen before it's configured (no tokens, no network). `options` are
|
|
206
|
+
* sample options used only for gallery thumbnails (e.g. a few countdown
|
|
207
|
+
* dates), never for a widget the user placed.
|
|
208
|
+
*/
|
|
209
|
+
demo?: (ctx: {
|
|
210
|
+
options: Infer<OF>;
|
|
211
|
+
now: number;
|
|
212
|
+
locale: string;
|
|
213
|
+
}) => {
|
|
214
|
+
data?: D;
|
|
215
|
+
sources?: Record<string, unknown>;
|
|
216
|
+
options?: Partial<Infer<OF>>;
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
export interface SourceContext<O> extends BaseContext {
|
|
220
|
+
options: O;
|
|
221
|
+
/**
|
|
222
|
+
* Aborted when the source stops (no widget uses it, options changed, the
|
|
223
|
+
* app stops) and, in `read`, when this read takes longer than `timeoutMs`.
|
|
224
|
+
* Pass it to `fetch` and child processes.
|
|
225
|
+
*/
|
|
226
|
+
signal: AbortSignal;
|
|
227
|
+
/** How often `read` runs (the user's `intervalMs`, clamped to `minIntervalMs`). */
|
|
228
|
+
intervalMs: number;
|
|
229
|
+
/** How long one `read` may take (the user's `timeoutMs`), for a per-request budget of your own. */
|
|
230
|
+
timeoutMs: number;
|
|
231
|
+
}
|
|
232
|
+
export interface SourceDefinition<OF extends ObjectField<any> = ObjectField<any>, D = unknown> {
|
|
233
|
+
/** Unique inside its plugin. Widgets ask for `plugin/source`. */
|
|
234
|
+
id: string;
|
|
235
|
+
name: Localized;
|
|
236
|
+
description?: Localized;
|
|
237
|
+
/** Global options, edited once in Settings → Sources. */
|
|
238
|
+
options?: OF;
|
|
239
|
+
/**
|
|
240
|
+
* Polled every `intervalMs` while some widget uses it. The user can change
|
|
241
|
+
* the interval and the timeout in Settings → Data sources
|
|
242
|
+
* (`sources["plugin/source"].intervalMs` / `.timeoutMs`): don't add options
|
|
243
|
+
* of your own for them.
|
|
244
|
+
*/
|
|
245
|
+
read?: (ctx: SourceContext<Infer<OF>>) => Promise<D>;
|
|
246
|
+
/** Default interval of `read`. Default: 30 s. */
|
|
247
|
+
intervalMs?: number;
|
|
248
|
+
/** Shortest interval the user may set: API rate limits, an expensive command. Default: 5 s (or `intervalMs`, if shorter). */
|
|
249
|
+
minIntervalMs?: number;
|
|
250
|
+
/** Default of the longest one `read` may take before its `signal` aborts and it counts as failed. Default: 2 minutes. */
|
|
251
|
+
timeoutMs?: number;
|
|
252
|
+
/**
|
|
253
|
+
* Push-based alternative (file watchers, sockets): call `emit` with new
|
|
254
|
+
* data, return a function that stops watching.
|
|
255
|
+
*/
|
|
256
|
+
watch?: (ctx: SourceContext<Infer<OF>>, emit: (data: D) => void) => () => void;
|
|
257
|
+
demo?: (ctx: {
|
|
258
|
+
now: number;
|
|
259
|
+
locale: string;
|
|
260
|
+
}) => D;
|
|
261
|
+
}
|
|
262
|
+
export interface InterludePlayer {
|
|
263
|
+
/** Number of frames. */
|
|
264
|
+
frames: number;
|
|
265
|
+
/** Paints frame `i` on a canvas of the full panel size. May be async (to decode a prerendered frame). */
|
|
266
|
+
draw: (g: Graphics, i: number) => void | Promise<void>;
|
|
267
|
+
}
|
|
268
|
+
export interface InterludeContext<O> extends BaseContext {
|
|
269
|
+
options: O;
|
|
270
|
+
width: number;
|
|
271
|
+
height: number;
|
|
272
|
+
/** Deterministic per slot: the same quarter hour plays the same story. */
|
|
273
|
+
seed: number;
|
|
274
|
+
theme: Theme;
|
|
275
|
+
canvas: CanvasApi;
|
|
276
|
+
sources: Record<string, unknown>;
|
|
277
|
+
}
|
|
278
|
+
export interface InterludeDefinition<OF extends ObjectField<any> = ObjectField<any>> {
|
|
279
|
+
id: string;
|
|
280
|
+
name: Localized;
|
|
281
|
+
description?: Localized;
|
|
282
|
+
icon?: string;
|
|
283
|
+
options?: OF;
|
|
284
|
+
sources?: string[];
|
|
285
|
+
/** Frames per second it was designed for. USB panels top out around 12-24 fps. */
|
|
286
|
+
fps: number;
|
|
287
|
+
/** Builds the animation. May be slow (it runs before playing, not during). */
|
|
288
|
+
prepare: (ctx: InterludeContext<Infer<OF>>) => Promise<InterludePlayer | null>;
|
|
289
|
+
/** Don't interrupt now (someone waits for a permission, a meeting is about to start). */
|
|
290
|
+
skip?: (ctx: {
|
|
291
|
+
sources: Record<string, unknown>;
|
|
292
|
+
now: number;
|
|
293
|
+
options: Infer<OF>;
|
|
294
|
+
}) => boolean;
|
|
295
|
+
}
|
|
296
|
+
export interface PluginDefinition {
|
|
297
|
+
/** npm-like id: lowercase, digits and dashes. Stable: configs refer to it. */
|
|
298
|
+
id: string;
|
|
299
|
+
name: Localized;
|
|
300
|
+
version: string;
|
|
301
|
+
description?: Localized;
|
|
302
|
+
author?: string;
|
|
303
|
+
homepage?: string;
|
|
304
|
+
license?: string;
|
|
305
|
+
icon?: string;
|
|
306
|
+
widgets?: WidgetDefinition<any, any>[];
|
|
307
|
+
sources?: SourceDefinition<any, any>[];
|
|
308
|
+
interludes?: InterludeDefinition<any>[];
|
|
309
|
+
}
|
|
310
|
+
export declare function defineWidget<OF extends ObjectField<any> = ObjectField<{}>, D = undefined>(w: WidgetDefinition<OF, D>): WidgetDefinition<OF, D>;
|
|
311
|
+
export declare function defineSource<OF extends ObjectField<any> = ObjectField<{}>, D = unknown>(s: SourceDefinition<OF, D>): SourceDefinition<OF, D>;
|
|
312
|
+
export declare function defineInterlude<OF extends ObjectField<any> = ObjectField<{}>>(i: InterludeDefinition<OF>): InterludeDefinition<OF>;
|
|
313
|
+
export declare function definePlugin(p: PluginDefinition): PluginDefinition;
|
|
314
|
+
export type { Field };
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export const CATEGORIES = [
|
|
2
|
+
{ id: 'agents', label: { en: 'AI agents', es: 'Agentes IA' } },
|
|
3
|
+
{ id: 'system', label: { en: 'System', es: 'Sistema' } },
|
|
4
|
+
{ id: 'time', label: { en: 'Time & calendar', es: 'Tiempo y agenda' } },
|
|
5
|
+
{ id: 'productivity', label: { en: 'Productivity', es: 'Productividad' } },
|
|
6
|
+
{ id: 'dev', label: { en: 'Development', es: 'Desarrollo' } },
|
|
7
|
+
{ id: 'info', label: { en: 'News & world', es: 'Noticias y mundo' } },
|
|
8
|
+
{ id: 'media', label: { en: 'Media', es: 'Multimedia' } },
|
|
9
|
+
{ id: 'scene', label: { en: 'Scenes', es: 'Escenas' } },
|
|
10
|
+
{ id: 'fun', label: { en: 'Fun', es: 'Diversión' } },
|
|
11
|
+
];
|
|
12
|
+
/* Identity helpers: they only exist so TypeScript infers option and data types. */
|
|
13
|
+
export function defineWidget(w) {
|
|
14
|
+
return w;
|
|
15
|
+
}
|
|
16
|
+
export function defineSource(s) {
|
|
17
|
+
return s;
|
|
18
|
+
}
|
|
19
|
+
export function defineInterlude(i) {
|
|
20
|
+
return i;
|
|
21
|
+
}
|
|
22
|
+
export function definePlugin(p) {
|
|
23
|
+
return p;
|
|
24
|
+
}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A tiny, typed schema builder for plugin options.
|
|
3
|
+
*
|
|
4
|
+
* One declaration gives three things at once:
|
|
5
|
+
* - the TypeScript type of the options (`Infer<typeof schema>`),
|
|
6
|
+
* - the defaults and the validation the runtime applies to user config,
|
|
7
|
+
* - the form the editor renders (labels, hints, sliders, colour pickers…).
|
|
8
|
+
*
|
|
9
|
+
* `toJsonSchema` exports a standard JSON Schema (draft 2020-12) with `x-ui`
|
|
10
|
+
* hints, so tools that don't speak TypeScript can still validate a config.
|
|
11
|
+
*/
|
|
12
|
+
import { type Localized } from './i18n.ts';
|
|
13
|
+
/**
|
|
14
|
+
* What a value of a field lets Kiosko do as the user, so a config written by
|
|
15
|
+
* someone else (or by an AI) can be reviewed before it runs:
|
|
16
|
+
*
|
|
17
|
+
* - `exec`: runs a program or loads code (a command, an ssh host, a module);
|
|
18
|
+
* - `network`: contacts a host (a URL, an API host, a feed);
|
|
19
|
+
* - `path`: reads (or writes) a local file or folder.
|
|
20
|
+
*
|
|
21
|
+
* A list when it depends on the value, e.g. `['network', 'path']` for "a URL
|
|
22
|
+
* or a file": a value that looks like a URL counts as `network`, any other as
|
|
23
|
+
* the next one. Only free values need it; a switch that turns on a fixed tool
|
|
24
|
+
* (read git status) doesn't.
|
|
25
|
+
*/
|
|
26
|
+
export type Risk = 'exec' | 'network' | 'path';
|
|
27
|
+
interface Common<T> {
|
|
28
|
+
/** Shown above the input in the editor. */
|
|
29
|
+
label?: Localized;
|
|
30
|
+
/** One line under the input. */
|
|
31
|
+
help?: Localized;
|
|
32
|
+
default: T;
|
|
33
|
+
/** Hide in the editor unless "advanced" is toggled. */
|
|
34
|
+
advanced?: boolean;
|
|
35
|
+
/** See `Risk`. Exported as `x-risk`; `kiosko config import` lists these values before applying a config. */
|
|
36
|
+
risk?: Risk | readonly Risk[];
|
|
37
|
+
}
|
|
38
|
+
export interface StringField extends Common<string> {
|
|
39
|
+
kind: 'string';
|
|
40
|
+
placeholder?: string;
|
|
41
|
+
multiline?: boolean;
|
|
42
|
+
/** Tokens, URLs with credentials…: masked in the editor and never logged. */
|
|
43
|
+
secret?: boolean;
|
|
44
|
+
/** Free text with a format hint: `url`, `path`, `time` (HH:MM), `date` (YYYY-MM-DD). */
|
|
45
|
+
format?: 'url' | 'path' | 'time' | 'date' | 'datetime';
|
|
46
|
+
maxLength?: number;
|
|
47
|
+
}
|
|
48
|
+
export interface NumberField extends Common<number> {
|
|
49
|
+
kind: 'number';
|
|
50
|
+
integer?: boolean;
|
|
51
|
+
min?: number;
|
|
52
|
+
max?: number;
|
|
53
|
+
step?: number;
|
|
54
|
+
/** Shown after the value: `ms`, `px`, `°C`, `%`… */
|
|
55
|
+
unit?: string;
|
|
56
|
+
/** Render as a slider when min and max are known. */
|
|
57
|
+
slider?: boolean;
|
|
58
|
+
}
|
|
59
|
+
export interface BooleanField extends Common<boolean> {
|
|
60
|
+
kind: 'boolean';
|
|
61
|
+
}
|
|
62
|
+
export interface EnumField<V extends string = string> extends Common<V> {
|
|
63
|
+
kind: 'enum';
|
|
64
|
+
values: readonly V[];
|
|
65
|
+
/** Label per value; the raw value otherwise. */
|
|
66
|
+
labels?: Partial<Record<V, Localized>>;
|
|
67
|
+
}
|
|
68
|
+
export interface ColorField extends Common<string> {
|
|
69
|
+
kind: 'color';
|
|
70
|
+
}
|
|
71
|
+
export interface ListField<I extends Field = Field> extends Common<Infer<I>[]> {
|
|
72
|
+
kind: 'list';
|
|
73
|
+
item: I;
|
|
74
|
+
max?: number;
|
|
75
|
+
/** Patterns for `matchFilter` (see `t.filter`): the editor edits them as one line, comma-separated. */
|
|
76
|
+
filter?: boolean;
|
|
77
|
+
}
|
|
78
|
+
export interface ObjectField<P extends Record<string, Field> = Record<string, Field>> extends Common<{
|
|
79
|
+
[K in keyof P]: Infer<P[K]>;
|
|
80
|
+
}> {
|
|
81
|
+
kind: 'object';
|
|
82
|
+
props: P;
|
|
83
|
+
}
|
|
84
|
+
/** A string → string map (aliases, renames…). */
|
|
85
|
+
export interface MapField extends Common<Record<string, string>> {
|
|
86
|
+
kind: 'map';
|
|
87
|
+
keyLabel?: Localized;
|
|
88
|
+
valueLabel?: Localized;
|
|
89
|
+
}
|
|
90
|
+
export type Field = StringField | NumberField | BooleanField | EnumField<string> | ColorField | ListField<any> | ObjectField<any> | MapField;
|
|
91
|
+
/** The TypeScript type a field validates to. */
|
|
92
|
+
export type Infer<F> = F extends ObjectField<infer P> ? {
|
|
93
|
+
[K in keyof P]: Infer<P[K]>;
|
|
94
|
+
} : F extends ListField<infer I> ? Infer<I>[] : F extends EnumField<infer V> ? V : F extends Common<infer T> ? T : never;
|
|
95
|
+
type Opts<F extends {
|
|
96
|
+
kind: string;
|
|
97
|
+
default: unknown;
|
|
98
|
+
}, X extends string = never> = Omit<F, 'kind' | 'default' | X> & {
|
|
99
|
+
default?: F['default'];
|
|
100
|
+
};
|
|
101
|
+
export declare const t: {
|
|
102
|
+
string: (o?: Opts<StringField>) => StringField;
|
|
103
|
+
number: (o?: Opts<NumberField>) => NumberField;
|
|
104
|
+
integer: (o?: Opts<NumberField>) => NumberField;
|
|
105
|
+
boolean: (o?: Opts<BooleanField>) => BooleanField;
|
|
106
|
+
enum: <const V extends string>(values: readonly V[], o?: Opts<EnumField<V>, "values">) => EnumField<V>;
|
|
107
|
+
color: (o?: Opts<ColorField>) => ColorField;
|
|
108
|
+
list: <I extends Field>(item: I, o?: Opts<ListField<I>, "item">) => ListField<I>;
|
|
109
|
+
object: <P extends Record<string, Field>>(props: P, o?: Omit<Opts<ObjectField<P>, "props">, "default">) => ObjectField<P>;
|
|
110
|
+
map: (o?: Opts<MapField>) => MapField;
|
|
111
|
+
/** Duration in milliseconds, edited in seconds or minutes by the editor. */
|
|
112
|
+
duration: (o?: Opts<NumberField>) => NumberField;
|
|
113
|
+
/**
|
|
114
|
+
* Which items to show, as patterns for `matchFilter`: `["web", "acme/*",
|
|
115
|
+
* "!*-old"]`. Empty = all. Name it after what it filters (`projects`,
|
|
116
|
+
* `repos`, `calendars`, `people`) and give it a `label`; the `help`
|
|
117
|
+
* explaining the patterns comes with it.
|
|
118
|
+
*/
|
|
119
|
+
filter: (o?: Opts<ListField<StringField>, "item">) => ListField<StringField>;
|
|
120
|
+
};
|
|
121
|
+
/** The help every `t.filter()` field carries unless it brings its own. */
|
|
122
|
+
export declare const FILTER_HELP: Localized;
|
|
123
|
+
/** The defaults of a field, deep-copied (safe to mutate). */
|
|
124
|
+
export declare function defaultsOf<F extends Field>(f: F): Infer<F>;
|
|
125
|
+
export interface ValidationIssue {
|
|
126
|
+
/** `events.2.date` */
|
|
127
|
+
path: string;
|
|
128
|
+
message: string;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Coerces `value` to the shape of `f`: unknown keys are kept (so a newer
|
|
132
|
+
* config survives an older plugin), wrong types fall back to the default
|
|
133
|
+
* and are reported. Never throws.
|
|
134
|
+
*/
|
|
135
|
+
export declare function validate<F extends Field>(f: F, value: unknown, path?: string): {
|
|
136
|
+
value: Infer<F>;
|
|
137
|
+
issues: ValidationIssue[];
|
|
138
|
+
};
|
|
139
|
+
/** Appended to the description of secret fields in the JSON Schema. */
|
|
140
|
+
export declare const SECRET_NOTE = "Secret: leave it empty (or a placeholder such as \"<token>\"). Kiosko keeps the value it already has, or asks for it in the editor.";
|
|
141
|
+
/**
|
|
142
|
+
* Standard JSON Schema (draft 2020-12) with `x-ui` hints, for tools outside
|
|
143
|
+
* TypeScript: `title`/`description` in English, `x-secret` on secrets and
|
|
144
|
+
* `x-risk` (see `Risk`) on values that run programs, contact hosts or read
|
|
145
|
+
* paths. URLs carry no `format` keyword: an empty value or a placeholder is
|
|
146
|
+
* valid (a secret URL is filled in later), and editors would flag both.
|
|
147
|
+
*/
|
|
148
|
+
export declare function toJsonSchema(f: Field): Record<string, unknown>;
|
|
149
|
+
/** The risks of a field, as a list (empty when it has none). */
|
|
150
|
+
export declare function risksOf(f: {
|
|
151
|
+
risk?: Risk | readonly Risk[];
|
|
152
|
+
} | {
|
|
153
|
+
'x-risk'?: unknown;
|
|
154
|
+
}): Risk[];
|
|
155
|
+
export {};
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A tiny, typed schema builder for plugin options.
|
|
3
|
+
*
|
|
4
|
+
* One declaration gives three things at once:
|
|
5
|
+
* - the TypeScript type of the options (`Infer<typeof schema>`),
|
|
6
|
+
* - the defaults and the validation the runtime applies to user config,
|
|
7
|
+
* - the form the editor renders (labels, hints, sliders, colour pickers…).
|
|
8
|
+
*
|
|
9
|
+
* `toJsonSchema` exports a standard JSON Schema (draft 2020-12) with `x-ui`
|
|
10
|
+
* hints, so tools that don't speak TypeScript can still validate a config.
|
|
11
|
+
*/
|
|
12
|
+
import { localize } from "./i18n.js";
|
|
13
|
+
export const t = {
|
|
14
|
+
string: (o = {}) => ({ kind: 'string', default: '', ...o }),
|
|
15
|
+
number: (o = {}) => ({ kind: 'number', default: o.min ?? 0, ...o }),
|
|
16
|
+
integer: (o = {}) => ({ kind: 'number', integer: true, default: o.min ?? 0, ...o }),
|
|
17
|
+
boolean: (o = {}) => ({ kind: 'boolean', default: false, ...o }),
|
|
18
|
+
enum: (values, o = {}) => ({ kind: 'enum', values, default: values[0], ...o }),
|
|
19
|
+
color: (o = {}) => ({ kind: 'color', default: '#ffffff', ...o }),
|
|
20
|
+
list: (item, o = {}) => ({ kind: 'list', item, default: [], ...o }),
|
|
21
|
+
object: (props, o = {}) => ({ kind: 'object', props, ...o, default: Object.fromEntries(Object.entries(props).map(([k, f]) => [k, clone(f.default)])) }),
|
|
22
|
+
map: (o = {}) => ({ kind: 'map', default: {}, ...o }),
|
|
23
|
+
/** Duration in milliseconds, edited in seconds or minutes by the editor. */
|
|
24
|
+
duration: (o = {}) => ({ kind: 'number', integer: true, unit: 'ms', min: 0, default: 60_000, ...o }),
|
|
25
|
+
/**
|
|
26
|
+
* Which items to show, as patterns for `matchFilter`: `["web", "acme/*",
|
|
27
|
+
* "!*-old"]`. Empty = all. Name it after what it filters (`projects`,
|
|
28
|
+
* `repos`, `calendars`, `people`) and give it a `label`; the `help`
|
|
29
|
+
* explaining the patterns comes with it.
|
|
30
|
+
*/
|
|
31
|
+
filter: (o = {}) => ({
|
|
32
|
+
kind: 'list',
|
|
33
|
+
item: { kind: 'string', default: '', placeholder: 'name, group/*, !old-*' },
|
|
34
|
+
default: [],
|
|
35
|
+
filter: true,
|
|
36
|
+
help: FILTER_HELP,
|
|
37
|
+
...o,
|
|
38
|
+
}),
|
|
39
|
+
};
|
|
40
|
+
/** The help every `t.filter()` field carries unless it brings its own. */
|
|
41
|
+
export const FILTER_HELP = {
|
|
42
|
+
en: 'Empty: all. Names or patterns, comma-separated: * matches anything, a leading ! leaves out (web, acme/*, !*-old).',
|
|
43
|
+
es: 'Vacío: todos. Nombres o patrones separados por comas: * vale por cualquier cosa y un ! delante excluye (web, acme/*, !*-old).',
|
|
44
|
+
};
|
|
45
|
+
function clone(v) {
|
|
46
|
+
return v === undefined ? v : JSON.parse(JSON.stringify(v));
|
|
47
|
+
}
|
|
48
|
+
/** The defaults of a field, deep-copied (safe to mutate). */
|
|
49
|
+
export function defaultsOf(f) {
|
|
50
|
+
return clone(f.default);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Coerces `value` to the shape of `f`: unknown keys are kept (so a newer
|
|
54
|
+
* config survives an older plugin), wrong types fall back to the default
|
|
55
|
+
* and are reported. Never throws.
|
|
56
|
+
*/
|
|
57
|
+
export function validate(f, value, path = '') {
|
|
58
|
+
const issues = [];
|
|
59
|
+
const out = coerce(f, value, path, issues);
|
|
60
|
+
return { value: out, issues };
|
|
61
|
+
}
|
|
62
|
+
function coerce(f, v, path, issues) {
|
|
63
|
+
const bad = (msg) => {
|
|
64
|
+
issues.push({ path: path || '(root)', message: msg });
|
|
65
|
+
return clone(f.default);
|
|
66
|
+
};
|
|
67
|
+
if (v === undefined || v === null)
|
|
68
|
+
return clone(f.default);
|
|
69
|
+
switch (f.kind) {
|
|
70
|
+
case 'string':
|
|
71
|
+
if (typeof v === 'number')
|
|
72
|
+
return String(v);
|
|
73
|
+
if (typeof v !== 'string')
|
|
74
|
+
return bad('expected text');
|
|
75
|
+
return f.maxLength && v.length > f.maxLength ? v.slice(0, f.maxLength) : v;
|
|
76
|
+
case 'color':
|
|
77
|
+
if (typeof v !== 'string')
|
|
78
|
+
return bad('expected a colour');
|
|
79
|
+
return v;
|
|
80
|
+
case 'number': {
|
|
81
|
+
const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v;
|
|
82
|
+
if (typeof n !== 'number' || !Number.isFinite(n))
|
|
83
|
+
return bad('expected a number');
|
|
84
|
+
let x = f.integer ? Math.round(n) : n;
|
|
85
|
+
if (f.min !== undefined && x < f.min)
|
|
86
|
+
x = f.min;
|
|
87
|
+
if (f.max !== undefined && x > f.max)
|
|
88
|
+
x = f.max;
|
|
89
|
+
return x;
|
|
90
|
+
}
|
|
91
|
+
case 'boolean':
|
|
92
|
+
if (typeof v === 'boolean')
|
|
93
|
+
return v;
|
|
94
|
+
if (v === 'true' || v === 'false')
|
|
95
|
+
return v === 'true';
|
|
96
|
+
return bad('expected true/false');
|
|
97
|
+
case 'enum':
|
|
98
|
+
if (typeof v === 'string' && f.values.includes(v))
|
|
99
|
+
return v;
|
|
100
|
+
return bad(`expected one of ${f.values.join(', ')}`);
|
|
101
|
+
case 'list': {
|
|
102
|
+
if (!Array.isArray(v))
|
|
103
|
+
return bad('expected a list');
|
|
104
|
+
const items = v.map((item, i) => coerce(f.item, item, path ? `${path}.${i}` : String(i), issues));
|
|
105
|
+
return f.max !== undefined ? items.slice(0, f.max) : items;
|
|
106
|
+
}
|
|
107
|
+
case 'map': {
|
|
108
|
+
if (typeof v !== 'object' || Array.isArray(v))
|
|
109
|
+
return bad('expected key/value pairs');
|
|
110
|
+
return Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === 'string' || typeof x === 'number').map(([k, x]) => [k, String(x)]));
|
|
111
|
+
}
|
|
112
|
+
case 'object': {
|
|
113
|
+
if (typeof v !== 'object' || Array.isArray(v))
|
|
114
|
+
return bad('expected an object');
|
|
115
|
+
const src = v;
|
|
116
|
+
const out = { ...src };
|
|
117
|
+
for (const [k, sub] of Object.entries(f.props))
|
|
118
|
+
out[k] = coerce(sub, src[k], path ? `${path}.${k}` : k, issues);
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/** Appended to the description of secret fields in the JSON Schema. */
|
|
124
|
+
export const SECRET_NOTE = 'Secret: leave it empty (or a placeholder such as "<token>"). Kiosko keeps the value it already has, or asks for it in the editor.';
|
|
125
|
+
/**
|
|
126
|
+
* Standard JSON Schema (draft 2020-12) with `x-ui` hints, for tools outside
|
|
127
|
+
* TypeScript: `title`/`description` in English, `x-secret` on secrets and
|
|
128
|
+
* `x-risk` (see `Risk`) on values that run programs, contact hosts or read
|
|
129
|
+
* paths. URLs carry no `format` keyword: an empty value or a placeholder is
|
|
130
|
+
* valid (a secret URL is filled in later), and editors would flag both.
|
|
131
|
+
*/
|
|
132
|
+
export function toJsonSchema(f) {
|
|
133
|
+
const ui = { label: f.label, help: f.help, advanced: f.advanced };
|
|
134
|
+
const secret = f.kind === 'string' && !!f.secret;
|
|
135
|
+
const help = f.help === undefined ? undefined : localize(f.help, 'en');
|
|
136
|
+
const description = secret ? [help, SECRET_NOTE].filter(Boolean).join(' ') : help;
|
|
137
|
+
const base = {
|
|
138
|
+
...(f.label === undefined ? {} : { title: localize(f.label, 'en') }),
|
|
139
|
+
...(description ? { description } : {}),
|
|
140
|
+
default: f.default,
|
|
141
|
+
'x-ui': ui,
|
|
142
|
+
...(secret ? { 'x-secret': true } : {}),
|
|
143
|
+
...(f.risk === undefined ? {} : { 'x-risk': typeof f.risk === 'string' ? f.risk : [...f.risk] }),
|
|
144
|
+
};
|
|
145
|
+
switch (f.kind) {
|
|
146
|
+
case 'string':
|
|
147
|
+
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 } };
|
|
148
|
+
case 'color':
|
|
149
|
+
return { ...base, type: 'string', 'x-ui': { ...ui, widget: 'color' } };
|
|
150
|
+
case 'number':
|
|
151
|
+
return { ...base, type: f.integer ? 'integer' : 'number', minimum: f.min, maximum: f.max, 'x-ui': { ...ui, unit: f.unit, step: f.step, slider: f.slider } };
|
|
152
|
+
case 'boolean':
|
|
153
|
+
return { ...base, type: 'boolean' };
|
|
154
|
+
case 'enum':
|
|
155
|
+
return { ...base, type: 'string', enum: [...f.values], 'x-ui': { ...ui, labels: f.labels } };
|
|
156
|
+
case 'list':
|
|
157
|
+
return { ...base, type: 'array', items: toJsonSchema(f.item), maxItems: f.max, ...(f.filter ? { 'x-ui': { ...ui, widget: 'filter' }, 'x-filter': true } : {}) };
|
|
158
|
+
case 'map':
|
|
159
|
+
return { ...base, type: 'object', additionalProperties: { type: 'string' } };
|
|
160
|
+
case 'object':
|
|
161
|
+
return { ...base, type: 'object', properties: Object.fromEntries(Object.entries(f.props).map(([k, sub]) => [k, toJsonSchema(sub)])) };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/** The risks of a field, as a list (empty when it has none). */
|
|
165
|
+
export function risksOf(f) {
|
|
166
|
+
const r = 'risk' in f ? f.risk : f['x-risk'];
|
|
167
|
+
const list = typeof r === 'string' ? [r] : Array.isArray(r) ? r : [];
|
|
168
|
+
return list.filter((x) => x === 'exec' || x === 'network' || x === 'path');
|
|
169
|
+
}
|