@kiosko/sdk 0.0.0-stage → 0.2.1

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/src/plugin.ts ADDED
@@ -0,0 +1,429 @@
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
+
28
+ /** The 2D context widgets paint with. Same API as the browser's CanvasRenderingContext2D. */
29
+ export type Graphics = SKRSContext2D;
30
+ export type { Canvas, Image };
31
+
32
+ export interface CanvasApi {
33
+ createCanvas: typeof createCanvas;
34
+ loadImage: typeof loadImage;
35
+ }
36
+
37
+ /** A rectangle in panel pixels. */
38
+ export interface Box {
39
+ x: number;
40
+ y: number;
41
+ w: number;
42
+ h: number;
43
+ }
44
+
45
+ /** Size in panel pixels. */
46
+ export interface Size {
47
+ w: number;
48
+ h: number;
49
+ }
50
+
51
+ export type Category = 'agents' | 'system' | 'time' | 'productivity' | 'dev' | 'info' | 'media' | 'scene' | 'fun';
52
+
53
+ export const CATEGORIES: { id: Category; label: Localized }[] = [
54
+ { id: 'agents', label: { en: 'AI agents', es: 'Agentes IA' } },
55
+ { id: 'system', label: { en: 'System', es: 'Sistema' } },
56
+ { id: 'time', label: { en: 'Time & calendar', es: 'Tiempo y agenda' } },
57
+ { id: 'productivity', label: { en: 'Productivity', es: 'Productividad' } },
58
+ { id: 'dev', label: { en: 'Development', es: 'Desarrollo' } },
59
+ { id: 'info', label: { en: 'News & world', es: 'Noticias y mundo' } },
60
+ { id: 'media', label: { en: 'Media', es: 'Multimedia' } },
61
+ { id: 'scene', label: { en: 'Scenes', es: 'Escenas' } },
62
+ { id: 'fun', label: { en: 'Fun', es: 'Diversión' } },
63
+ ];
64
+
65
+ export interface Logger {
66
+ (msg: string): void;
67
+ }
68
+
69
+ /** A place on Earth, in degrees. */
70
+ export interface Location {
71
+ latitude: number;
72
+ longitude: number;
73
+ /** Shown by some widgets, e.g. "Madrid". */
74
+ name?: string;
75
+ }
76
+
77
+ /** What every context has. */
78
+ export interface BaseContext {
79
+ now: number;
80
+ /** BCP-47 language of the user (`es`, `en-GB`…). */
81
+ locale: string;
82
+ /** Picks the user's language from a `Localized` text. */
83
+ t: (text: Localized) => string;
84
+ /**
85
+ * Times and lengths of time in the user's language and clock (Settings →
86
+ * time format): `fmt.time(at)` "14:05" / "2:05 PM", `fmt.ago(at)`
87
+ * "5 min ago", `fmt.duration(ms)` "1 h 05". Use these rather than your own.
88
+ */
89
+ fmt: Formatters;
90
+ log: Logger;
91
+ /** Where the plugin may keep files that must survive a reboot (settings, history). Created on demand. */
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;
100
+ /**
101
+ * The user's place, if set in Settings (weather, sun, earthquakes…). Use it
102
+ * by default; offer a place of your own only where a second one makes sense
103
+ * (an advanced override), with an empty or 0,0 value meaning "this one".
104
+ */
105
+ location?: Location;
106
+ /**
107
+ * The user's working week from Settings: days, start and end, hours due,
108
+ * days with other hours and holidays. Default to it instead of asking for
109
+ * your own schedule; `scheduleOn(ctx.workday, now)` gives one day's.
110
+ */
111
+ workday: Workday;
112
+ }
113
+
114
+ export interface FetchContext<O> extends BaseContext {
115
+ options: O;
116
+ canvas: CanvasApi;
117
+ /** Aborted when the widget is removed, the app stops, or this fetch takes longer than `timeoutMs`. Pass it to `fetch` and child processes. */
118
+ signal: AbortSignal;
119
+ /** How long this fetch may take (the widget's `timeoutMs`), for a per-request budget of your own. */
120
+ timeoutMs: number;
121
+ /** Latest data of the sources the widget declared. */
122
+ sources: Record<string, unknown>;
123
+ }
124
+
125
+ export interface StateContext<O, D> {
126
+ options: O;
127
+ data: D | undefined;
128
+ sources: Record<string, unknown>;
129
+ now: number;
130
+ /** True for a work-hours slot, per the user's work schedule. */
131
+ working: boolean;
132
+ /** The user's working week (see `BaseContext.workday`); tests can pass `DEFAULT_WORKDAY`. */
133
+ workday: Workday;
134
+ /** The user's place, if set (see `BaseContext.location`). */
135
+ location?: Location;
136
+ }
137
+
138
+ export interface RenderContext<O, D> extends BaseContext, StateContext<O, D> {
139
+ /** Where to paint, already inside the card's padding and title. */
140
+ box: Box;
141
+ theme: Theme;
142
+ /** Families registered on the panel; same as `theme.fonts`. */
143
+ fonts: Theme['fonts'];
144
+ /** Helpers from @loksly/lcd-canvas-kit: tracked text, wrapping, sparklines, weather icons… */
145
+ kit: typeof Kit;
146
+ canvas: CanvasApi;
147
+ /** The widget is drawn in the editor (gallery thumbnail or live preview) and not on the panel. */
148
+ preview: boolean;
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`). */
157
+ frame?: number;
158
+ }
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
+
226
+ /**
227
+ * When the widget must be repainted even though its data didn't change: a
228
+ * clock every second, a countdown every minute. Fewer repaints are fewer
229
+ * frames over USB, so pick the slowest that still looks right.
230
+ */
231
+ export type Redraw = 'never' | 'minute' | 'second' | { everyMs: number };
232
+
233
+ export interface WidgetDefinition<OF extends ObjectField<any> = ObjectField<any>, D = unknown> {
234
+ /** Unique inside its plugin: `clock`, `sessions`… The full type is `plugin/widget`. */
235
+ id: string;
236
+ name: Localized;
237
+ description?: Localized;
238
+ /** Name of an icon of the editor (see web/icons) or an inline SVG string. */
239
+ icon?: string;
240
+ category?: Category;
241
+ tags?: string[];
242
+ /**
243
+ * Sizes in panel pixels. `min` is a hard limit enforced by the editor;
244
+ * `preferred` is what it uses when the widget is dropped.
245
+ */
246
+ size?: { min?: Size; preferred?: Size; max?: Size };
247
+ /** How the cell frames it: a card with optional title (default) or bare, edge to edge (scenes, photos). */
248
+ chrome?: 'card' | 'bare';
249
+ /** Options, as a schema: typed, validated and turned into a form by the editor. */
250
+ options?: OF;
251
+ /** Ids of shared sources (`plugin/source`) whose data the widget receives in `ctx.sources`. */
252
+ sources?: string[];
253
+ /** Own data, per instance. Runs in Node, never blocks the panel. */
254
+ fetch?: (ctx: FetchContext<Infer<OF>>) => Promise<D>;
255
+ /** How often `fetch` runs. Default: 10 minutes. The user can override it. */
256
+ intervalMs?: number;
257
+ /**
258
+ * How often `fetch` runs when that depends on the options or on the latest
259
+ * data (a module that declares its own interval): asked after every fetch;
260
+ * `undefined` keeps `intervalMs`. An interval the user set on the instance
261
+ * wins. Never under 5 s.
262
+ */
263
+ intervalOf?: (ctx: { options: Infer<OF>; data: NoInfer<D> | undefined }) => number | undefined;
264
+ /** Longest one `fetch` may take before its `signal` aborts and it counts as failed. Default: 2 minutes. */
265
+ timeoutMs?: number;
266
+ /** Paint. Synchronous and fast: load images in `fetch` and paint them here. */
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;
288
+ /** Also a function, when the cadence depends on the options or the data (a carousel every `rotateMs`). */
289
+ redraw?: Redraw | ((ctx: StateContext<Infer<OF>, D>) => Redraw);
290
+ /** Has nothing to show right now (nothing playing, no rain): skipped in its cell's rotation. */
291
+ visible?: (ctx: StateContext<Infer<OF>, D>) => boolean;
292
+ /**
293
+ * Needs the user now (a meeting about to start): takes its cell over while
294
+ * true, unless the user turned the widget's "keep the tile while urgent"
295
+ * switch (`takeOver`) off. Don't add an option of your own for that.
296
+ */
297
+ urgent?: (ctx: StateContext<Infer<OF>, D>) => boolean;
298
+ /** Default of the instance's `takeOver` switch (keep the tile while urgent). Default true. */
299
+ takeOver?: boolean;
300
+ /**
301
+ * Has nothing to list right now (no reviews, no tasks). Declaring it gives
302
+ * the widget a "hide when empty" switch (`hideWhenEmpty`): when on, an
303
+ * empty widget is skipped in its tile's rotation like `visible: false`;
304
+ * when off, it paints its empty message (`drawEmpty`). Unlike `visible`,
305
+ * which is the widget's own decision, this one is the user's.
306
+ */
307
+ empty?: (ctx: StateContext<Infer<OF>, D>) => boolean;
308
+ /** Default of the instance's `hideWhenEmpty` switch. Default false. */
309
+ hideWhenEmpty?: boolean;
310
+ /**
311
+ * Nothing worth lighting the panel for. When every widget of the page is
312
+ * idle and the screen has `sleepWhenIdle`, the panel goes black.
313
+ */
314
+ idle?: (ctx: StateContext<Infer<OF>, D>) => boolean;
315
+ /**
316
+ * Sample data for the gallery, the editor and the tests, so a widget can
317
+ * be seen before it's configured (no tokens, no network). `options` are
318
+ * sample options used only for gallery thumbnails (e.g. a few countdown
319
+ * dates), never for a widget the user placed.
320
+ */
321
+ demo?: (ctx: { options: Infer<OF>; now: number; locale: string }) => { data?: D; sources?: Record<string, unknown>; options?: Partial<Infer<OF>> };
322
+ }
323
+
324
+ export interface SourceContext<O> extends BaseContext {
325
+ options: O;
326
+ /**
327
+ * Aborted when the source stops (no widget uses it, options changed, the
328
+ * app stops) and, in `read`, when this read takes longer than `timeoutMs`.
329
+ * Pass it to `fetch` and child processes.
330
+ */
331
+ signal: AbortSignal;
332
+ /** How often `read` runs (the user's `intervalMs`, clamped to `minIntervalMs`). */
333
+ intervalMs: number;
334
+ /** How long one `read` may take (the user's `timeoutMs`), for a per-request budget of your own. */
335
+ timeoutMs: number;
336
+ }
337
+
338
+ export interface SourceDefinition<OF extends ObjectField<any> = ObjectField<any>, D = unknown> {
339
+ /** Unique inside its plugin. Widgets ask for `plugin/source`. */
340
+ id: string;
341
+ name: Localized;
342
+ description?: Localized;
343
+ /** Global options, edited once in Settings → Sources. */
344
+ options?: OF;
345
+ /**
346
+ * Polled every `intervalMs` while some widget uses it. The user can change
347
+ * the interval and the timeout in Settings → Data sources
348
+ * (`sources["plugin/source"].intervalMs` / `.timeoutMs`): don't add options
349
+ * of your own for them.
350
+ */
351
+ read?: (ctx: SourceContext<Infer<OF>>) => Promise<D>;
352
+ /** Default interval of `read`. Default: 30 s. */
353
+ intervalMs?: number;
354
+ /** Shortest interval the user may set: API rate limits, an expensive command. Default: 5 s (or `intervalMs`, if shorter). */
355
+ minIntervalMs?: number;
356
+ /** Default of the longest one `read` may take before its `signal` aborts and it counts as failed. Default: 2 minutes. */
357
+ timeoutMs?: number;
358
+ /**
359
+ * Push-based alternative (file watchers, sockets): call `emit` with new
360
+ * data, return a function that stops watching.
361
+ */
362
+ watch?: (ctx: SourceContext<Infer<OF>>, emit: (data: D) => void) => () => void;
363
+ demo?: (ctx: { now: number; locale: string }) => D;
364
+ }
365
+
366
+ export interface InterludePlayer {
367
+ /** Number of frames. */
368
+ frames: number;
369
+ /** Paints frame `i` on a canvas of the full panel size. May be async (to decode a prerendered frame). */
370
+ draw: (g: Graphics, i: number) => void | Promise<void>;
371
+ }
372
+
373
+ export interface InterludeContext<O> extends BaseContext {
374
+ options: O;
375
+ width: number;
376
+ height: number;
377
+ /** Deterministic per slot: the same quarter hour plays the same story. */
378
+ seed: number;
379
+ theme: Theme;
380
+ canvas: CanvasApi;
381
+ sources: Record<string, unknown>;
382
+ }
383
+
384
+ export interface InterludeDefinition<OF extends ObjectField<any> = ObjectField<any>> {
385
+ id: string;
386
+ name: Localized;
387
+ description?: Localized;
388
+ icon?: string;
389
+ options?: OF;
390
+ sources?: string[];
391
+ /** Frames per second it was designed for. USB panels top out around 12-24 fps. */
392
+ fps: number;
393
+ /** Builds the animation. May be slow (it runs before playing, not during). */
394
+ prepare: (ctx: InterludeContext<Infer<OF>>) => Promise<InterludePlayer | null>;
395
+ /** Don't interrupt now (someone waits for a permission, a meeting is about to start). */
396
+ skip?: (ctx: { sources: Record<string, unknown>; now: number; options: Infer<OF> }) => boolean;
397
+ }
398
+
399
+ export interface PluginDefinition {
400
+ /** npm-like id: lowercase, digits and dashes. Stable: configs refer to it. */
401
+ id: string;
402
+ name: Localized;
403
+ version: string;
404
+ description?: Localized;
405
+ author?: string;
406
+ homepage?: string;
407
+ license?: string;
408
+ icon?: string;
409
+ widgets?: WidgetDefinition<any, any>[];
410
+ sources?: SourceDefinition<any, any>[];
411
+ interludes?: InterludeDefinition<any>[];
412
+ }
413
+
414
+ /* Identity helpers: they only exist so TypeScript infers option and data types. */
415
+
416
+ export function defineWidget<OF extends ObjectField<any> = ObjectField<{}>, D = undefined>(w: WidgetDefinition<OF, D>): WidgetDefinition<OF, D> {
417
+ return w;
418
+ }
419
+ export function defineSource<OF extends ObjectField<any> = ObjectField<{}>, D = unknown>(s: SourceDefinition<OF, D>): SourceDefinition<OF, D> {
420
+ return s;
421
+ }
422
+ export function defineInterlude<OF extends ObjectField<any> = ObjectField<{}>>(i: InterludeDefinition<OF>): InterludeDefinition<OF> {
423
+ return i;
424
+ }
425
+ export function definePlugin(p: PluginDefinition): PluginDefinition {
426
+ return p;
427
+ }
428
+
429
+ export type { Field };