@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/semver.js ADDED
@@ -0,0 +1,115 @@
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
+ /** `1.2.3` → its parts; null when it isn't a version. */
15
+ export function parseVersion(s) {
16
+ const m = /^\s*v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?\s*$/.exec(s);
17
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ?? ''] : null;
18
+ }
19
+ /** -1, 0 or 1. A pre-release sorts before the release of the same numbers. */
20
+ export function compareVersions(a, b) {
21
+ const x = parseVersion(a), y = parseVersion(b);
22
+ if (!x || !y)
23
+ return 0;
24
+ for (let i = 0; i < 3; i++)
25
+ if (x[i] !== y[i])
26
+ return x[i] < y[i] ? -1 : 1;
27
+ if (x[3] === y[3])
28
+ return 0;
29
+ if (!x[3])
30
+ return 1;
31
+ if (!y[3])
32
+ return -1;
33
+ return x[3] < y[3] ? -1 : 1;
34
+ }
35
+ /** A partial version (`1`, `1.2`, `1.x`) as its parts, `undefined` for the missing or wild ones. */
36
+ function partial(s) {
37
+ const m = /^\s*v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?\s*$/.exec(s);
38
+ if (!m)
39
+ return null;
40
+ const n = (p) => (p === undefined || /^[xX*]$/.test(p) ? undefined : Number(p));
41
+ return [n(m[1]), n(m[2]), n(m[3]), m[4] ?? ''];
42
+ }
43
+ const ver = (a, b, c, pre = '') => `${a}.${b}.${c}${pre ? `-${pre}` : ''}`;
44
+ /** One space-separated set of comparators → plain `op version` pairs. */
45
+ function comparators(set) {
46
+ const out = [];
47
+ const tokens = set.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/).filter(Boolean);
48
+ if (!tokens.length)
49
+ return [{ op: '>=', v: '0.0.0' }];
50
+ for (const tk of tokens) {
51
+ const m = /^(>=|<=|>|<|=|\^|~)?(.*)$/.exec(tk);
52
+ const op = m[1] ?? '';
53
+ const p = partial(m[2]);
54
+ if (!p)
55
+ 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
+ }
66
+ else if (op === '~') {
67
+ const lo = ver(ma, mi ?? 0, pa ?? 0, pre);
68
+ const hi = mi === undefined ? ver(ma + 1, 0, 0) : ver(ma, mi + 1, 0);
69
+ out.push({ op: '>=', v: lo }, { op: '<', v: `${hi}-0` });
70
+ }
71
+ else if (op === '' || op === '=') {
72
+ if (mi === undefined)
73
+ out.push({ op: '>=', v: ver(ma, 0, 0) }, { op: '<', v: `${ver(ma + 1, 0, 0)}-0` });
74
+ else if (pa === undefined)
75
+ out.push({ op: '>=', v: ver(ma, mi, 0) }, { op: '<', v: `${ver(ma, mi + 1, 0)}-0` });
76
+ else
77
+ out.push({ op: '=', v: ver(ma, mi, pa, pre) });
78
+ }
79
+ else {
80
+ // >1.2 means >=1.3.0; <=1.2 means <1.3.0.
81
+ if (pa === undefined && (op === '>' || op === '<=')) {
82
+ const next = mi === undefined ? ver(ma + 1, 0, 0) : ver(ma, mi + 1, 0);
83
+ out.push(op === '>' ? { op: '>=', v: next } : { op: '<', v: `${next}-0` });
84
+ }
85
+ else
86
+ out.push({ op: op, v: ver(ma, mi ?? 0, pa ?? 0, pre) });
87
+ }
88
+ }
89
+ return out;
90
+ }
91
+ /**
92
+ * Whether `version` is in `range`. A pre-release only matches a range that
93
+ * names a pre-release of the same numbers (npm's rule), so `0.3.0-beta` does
94
+ * not quietly satisfy `^0.2`. An unreadable range or version is `false`.
95
+ */
96
+ export function satisfies(version, range) {
97
+ const v = parseVersion(version);
98
+ if (!v)
99
+ return false;
100
+ return range.split('||').some((set) => {
101
+ const cs = comparators(set);
102
+ if (!cs)
103
+ return false;
104
+ const ok = cs.every(({ op, v: w }) => {
105
+ const c = compareVersions(version, w);
106
+ return op === '>=' ? c >= 0 : op === '>' ? c > 0 : op === '<=' ? c <= 0 : op === '<' ? c < 0 : c === 0;
107
+ });
108
+ if (!ok || !v[3])
109
+ return ok;
110
+ return cs.some(({ v: w }) => {
111
+ const x = parseVersion(w);
112
+ return !!x && !!x[3] && x[3] !== '0' && x[0] === v[0] && x[1] === v[1] && x[2] === v[2];
113
+ });
114
+ });
115
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * `~`, `~/x` (and `~\x`), `$VAR`, `${VAR}` and, on Windows, `%VAR%` expanded.
3
+ * A variable that isn't set stays as written. `os` and `env` are for tests.
4
+ */
5
+ export declare function expandPath(p: string, o?: {
6
+ os?: NodeJS.Platform;
7
+ env?: Record<string, string | undefined>;
8
+ home?: string;
9
+ }): string;
10
+ /** What to hand to `execFile` to run `cmd` with `args`. */
11
+ export interface Command {
12
+ file: string;
13
+ args: string[];
14
+ /** Pass as `windowsVerbatimArguments` to `execFile`/`spawn`. */
15
+ windowsVerbatimArguments?: boolean;
16
+ }
17
+ /**
18
+ * On Windows, tools installed with npm (`ccusage`, `npx`, `claude`…) are
19
+ * `.cmd` shims, and `execFile('ccusage')` neither finds them (no `PATHEXT`
20
+ * search) nor, since Node 18.20 / 20.12, runs a `.cmd` without a shell.
21
+ * `commandFor` returns the pair to pass to `execFile`: for a `.cmd`/`.bat`
22
+ * (looked up on `PATH`), `cmd.exe /d /s /c "…"` with each argument quoted; for
23
+ * anything else, the command as it was. Elsewhere it changes nothing.
24
+ *
25
+ * const c = commandFor('ccusage', ['daily', '--json']);
26
+ * execFile(c.file, c.args, { windowsHide: true, windowsVerbatimArguments: c.windowsVerbatimArguments }, cb);
27
+ *
28
+ * Throws if an argument holds a quote, a `%` or a line break and the command needs
29
+ * cmd.exe: there is no safe way to pass those through a batch file.
30
+ */
31
+ export declare function commandFor(cmd: string, args: string[], o?: {
32
+ os?: NodeJS.Platform;
33
+ env?: Record<string, string | undefined>;
34
+ exists?: (path: string) => boolean;
35
+ }): Command;
package/dist/system.js ADDED
@@ -0,0 +1,80 @@
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
+ * `~`, `~/x` (and `~\x`), `$VAR`, `${VAR}` and, on Windows, `%VAR%` expanded.
10
+ * A variable that isn't set stays as written. `os` and `env` are for tests.
11
+ */
12
+ export function expandPath(p, o = {}) {
13
+ const env = o.env ?? process.env;
14
+ let v = p.replace(/\$(?:\{(\w+)\}|(\w+))/g, (whole, a, b) => env[a ?? b ?? ''] ?? whole);
15
+ // `%VAR%` is a Windows thing; on other systems a `%` is just a character.
16
+ if ((o.os ?? process.platform) === 'win32')
17
+ v = v.replace(/%([^%\r\n]+)%/g, (whole, name) => env[name] ?? whole);
18
+ const home = o.home ?? homedir();
19
+ if (v === '~')
20
+ return home;
21
+ return v.startsWith('~/') || v.startsWith('~\\') ? join(home, v.slice(2)) : v;
22
+ }
23
+ /** Characters cmd.exe would interpret inside a batch shim's arguments. */
24
+ const CMD_UNSAFE = /["%\r\n\0]/;
25
+ /**
26
+ * On Windows, tools installed with npm (`ccusage`, `npx`, `claude`…) are
27
+ * `.cmd` shims, and `execFile('ccusage')` neither finds them (no `PATHEXT`
28
+ * search) nor, since Node 18.20 / 20.12, runs a `.cmd` without a shell.
29
+ * `commandFor` returns the pair to pass to `execFile`: for a `.cmd`/`.bat`
30
+ * (looked up on `PATH`), `cmd.exe /d /s /c "…"` with each argument quoted; for
31
+ * anything else, the command as it was. Elsewhere it changes nothing.
32
+ *
33
+ * const c = commandFor('ccusage', ['daily', '--json']);
34
+ * execFile(c.file, c.args, { windowsHide: true, windowsVerbatimArguments: c.windowsVerbatimArguments }, cb);
35
+ *
36
+ * Throws if an argument holds a quote, a `%` or a line break and the command needs
37
+ * cmd.exe: there is no safe way to pass those through a batch file.
38
+ */
39
+ export function commandFor(cmd, args, o = {}) {
40
+ if ((o.os ?? process.platform) !== 'win32')
41
+ return { file: cmd, args };
42
+ const env = o.env ?? process.env;
43
+ const exists = o.exists ?? defaultExists;
44
+ const shim = findShim(cmd, env, exists);
45
+ if (!shim)
46
+ return { file: cmd, args };
47
+ for (const a of args)
48
+ if (CMD_UNSAFE.test(a))
49
+ throw new Error(`argument not allowed for ${cmd}: ${JSON.stringify(a)}`);
50
+ const quote = (s) => (/^[\w@+=:,./\\-]+$/.test(s) ? s : `"${s}"`);
51
+ return { file: env.ComSpec || 'cmd.exe', args: ['/d', '/s', '/c', `"${[shim, ...args].map(quote).join(' ')}"`], windowsVerbatimArguments: true };
52
+ }
53
+ function defaultExists(path) {
54
+ try {
55
+ // Sync and tiny: a handful of PATH entries, once per call.
56
+ return statSync(path).isFile();
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ /** The `.cmd`/`.bat` that `cmd` names on Windows, or null if it is (or may be) an executable. */
63
+ function findShim(cmd, env, exists) {
64
+ if (/\.(exe|com)$/i.test(cmd))
65
+ return null;
66
+ if (/\.(cmd|bat)$/i.test(cmd) && /[\\/]/.test(cmd))
67
+ return exists(cmd) ? cmd : null;
68
+ const dirs = /[\\/]/.test(cmd) ? [''] : (env.PATH ?? env.Path ?? '').split(';').filter(Boolean);
69
+ const exts = (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
70
+ for (const dir of dirs) {
71
+ const base = dir ? win32.join(dir, cmd) : cmd;
72
+ for (const ext of /\.\w+$/.test(cmd) ? [''] : exts) {
73
+ const p = base + ext.toLowerCase();
74
+ if (!exists(p))
75
+ continue;
76
+ return /\.(cmd|bat)$/i.test(p) ? p : null;
77
+ }
78
+ }
79
+ return null;
80
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Helpers for plugin tests (Node only: they paint with @napi-rs/canvas).
3
+ *
4
+ * import { renderWidget, checkPlugin } from '@kiosko/sdk/testing';
5
+ *
6
+ * const r = renderWidget(forecast, { size: { w: 600, h: 300 }, locale: 'es' });
7
+ * assert.deepEqual(r.texts.slice(0, 2), ['13°', 'Parcialmente nublado']);
8
+ * assert.equal(r.outside, 0);
9
+ *
10
+ * assert.deepEqual(checkPlugin(plugin), []); // every widget, several sizes, themes and languages
11
+ *
12
+ * A widget is painted the way Kiosko paints it (same context, same drawing
13
+ * kit), with its `demo` data unless given other, and every text it draws
14
+ * through the kit is collected in order. It is painted with a margin around
15
+ * its box, so what it draws outside (which the panel would clip) is counted.
16
+ */
17
+ import { type Canvas } from '@napi-rs/canvas';
18
+ import type { TimeFormat } from './format.ts';
19
+ import type { Box, PluginDefinition, WidgetDefinition } from './plugin.ts';
20
+ import { type Theme } from './theme.ts';
21
+ export interface RenderOptions {
22
+ /** The instance's options (validated against the widget's schema, defaults filled in). Default: the demo's, if any. */
23
+ options?: Record<string, unknown>;
24
+ /** The widget's own data. Default: its demo data. */
25
+ data?: unknown;
26
+ /** Data of its sources, by type. Default: its demo's. */
27
+ sources?: Record<string, unknown>;
28
+ /** The box it paints in. Default: its preferred size, else 480×300. */
29
+ size?: {
30
+ w: number;
31
+ h: number;
32
+ };
33
+ locale?: string;
34
+ /** A theme or its id (`midnight`, `paper`…). Default: the first. */
35
+ theme?: string | Theme;
36
+ now?: number;
37
+ timeFormat?: TimeFormat;
38
+ /** Painted for the editor's preview rather than the panel. */
39
+ preview?: boolean;
40
+ /** Use the widget's `demo` for what isn't given. Default true. */
41
+ demo?: boolean;
42
+ }
43
+ export interface RenderResult {
44
+ /** Every text drawn with `kit.drawTracked`, in order. */
45
+ texts: string[];
46
+ /** The picture: the box with `margin` pixels around it. */
47
+ canvas: Canvas;
48
+ /** Where the box is on `canvas`. */
49
+ box: Box;
50
+ margin: number;
51
+ /** Pixels painted outside the box (the panel would cut them off). */
52
+ outside: number;
53
+ /** How long `render` took. */
54
+ ms: number;
55
+ /** What `render` threw, if it did. */
56
+ error?: string;
57
+ /** The box alone, as PNG. */
58
+ png(): Buffer;
59
+ }
60
+ /** Paints a widget alone and says what it drew. Never throws: a failing `render` is reported in `error`. */
61
+ export declare function renderWidget(w: WidgetDefinition<any, any>, o?: RenderOptions): RenderResult;
62
+ /** Asks a widget's `urgent`, `idle`, `empty` or `visible` with the same inputs `renderWidget` would use. */
63
+ export declare function widgetState(w: WidgetDefinition<any, any>, hook: 'urgent' | 'idle' | 'empty' | 'visible', o?: RenderOptions): boolean | undefined;
64
+ export interface PluginIssue {
65
+ /** `plugin/widget`. */
66
+ type: string;
67
+ /** `600x300 midnight es`. */
68
+ where: string;
69
+ problem: string;
70
+ }
71
+ /**
72
+ * Paints every widget of a plugin with its demo data at its minimum and
73
+ * preferred sizes and a wide and a tall one, in every theme and in each
74
+ * language given, and lists what went wrong: a `render` that throws, one
75
+ * that paints nothing, paints outside its box, or takes longer than
76
+ * `slowMs` (Kiosko warns at 50 ms). An empty list is a pass.
77
+ */
78
+ export declare function checkPlugin(p: PluginDefinition, o?: {
79
+ locales?: string[];
80
+ themes?: string[];
81
+ slowMs?: number;
82
+ extraSizes?: {
83
+ w: number;
84
+ h: number;
85
+ }[];
86
+ }): PluginIssue[];
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Helpers for plugin tests (Node only: they paint with @napi-rs/canvas).
3
+ *
4
+ * import { renderWidget, checkPlugin } from '@kiosko/sdk/testing';
5
+ *
6
+ * const r = renderWidget(forecast, { size: { w: 600, h: 300 }, locale: 'es' });
7
+ * assert.deepEqual(r.texts.slice(0, 2), ['13°', 'Parcialmente nublado']);
8
+ * assert.equal(r.outside, 0);
9
+ *
10
+ * assert.deepEqual(checkPlugin(plugin), []); // every widget, several sizes, themes and languages
11
+ *
12
+ * A widget is painted the way Kiosko paints it (same context, same drawing
13
+ * kit), with its `demo` data unless given other, and every text it draws
14
+ * through the kit is collected in order. It is painted with a margin around
15
+ * its box, so what it draws outside (which the panel would clip) is counted.
16
+ */
17
+ import { createCanvas, loadImage } from '@napi-rs/canvas';
18
+ import * as kit from '@loksly/lcd-canvas-kit';
19
+ import { createBaseContext } from "./context.js";
20
+ import { validate } from "./schema.js";
21
+ import { THEMES, themeById } from "./theme.js";
22
+ import { DEFAULT_WORKDAY } from "./workday.js";
23
+ const MARGIN = 24;
24
+ function resolve(w, o) {
25
+ const now = o.now ?? Date.UTC(2026, 10, 5, 9, 42);
26
+ const locale = o.locale ?? 'en';
27
+ const demoOpts = w.options ? validate(w.options, {}).value : {};
28
+ const demo = o.demo === false ? undefined : w.demo?.({ options: demoOpts, now, locale });
29
+ const options = w.options ? validate(w.options, o.options ?? demo?.options ?? {}).value : {};
30
+ const data = 'data' in o ? o.data : demo?.data;
31
+ const sources = o.sources ?? demo?.sources ?? {};
32
+ return { now, locale, options, data, sources };
33
+ }
34
+ /** Paints a widget alone and says what it drew. Never throws: a failing `render` is reported in `error`. */
35
+ export function renderWidget(w, o = {}) {
36
+ const { now, locale, options, data, sources } = resolve(w, o);
37
+ const size = o.size ?? w.size?.preferred ?? { w: 480, h: 300 };
38
+ const theme = typeof o.theme === 'object' ? o.theme : themeById(o.theme);
39
+ const texts = [];
40
+ const spy = { ...kit, drawTracked: (...a) => (texts.push(a[1]), kit.drawTracked(...a)) };
41
+ const canvas = createCanvas(size.w + 2 * MARGIN, size.h + 2 * MARGIN);
42
+ const g = canvas.getContext('2d');
43
+ const box = { x: MARGIN, y: MARGIN, w: size.w, h: size.h };
44
+ const ctx = {
45
+ ...createBaseContext({ now, locale, ...(o.timeFormat ? { timeFormat: o.timeFormat } : {}) }),
46
+ options,
47
+ data,
48
+ sources,
49
+ working: true,
50
+ box,
51
+ theme,
52
+ fonts: theme.fonts,
53
+ kit: spy,
54
+ canvas: { createCanvas, loadImage },
55
+ preview: !!o.preview,
56
+ };
57
+ const t0 = performance.now();
58
+ let error;
59
+ try {
60
+ w.render(g, ctx);
61
+ }
62
+ catch (err) {
63
+ error = err instanceof Error ? err.message : String(err);
64
+ }
65
+ const ms = performance.now() - t0;
66
+ const px = g.getImageData(0, 0, canvas.width, canvas.height).data;
67
+ let outside = 0;
68
+ for (let y = 0; y < canvas.height; y++) {
69
+ for (let x = 0; x < canvas.width; x++) {
70
+ if (x >= box.x && x < box.x + box.w && y >= box.y && y < box.y + box.h)
71
+ continue;
72
+ if (px[(y * canvas.width + x) * 4 + 3] > 24)
73
+ outside++;
74
+ }
75
+ }
76
+ return {
77
+ texts,
78
+ canvas,
79
+ box,
80
+ margin: MARGIN,
81
+ outside,
82
+ ms,
83
+ ...(error !== undefined ? { error } : {}),
84
+ png() {
85
+ const out = createCanvas(box.w, box.h);
86
+ out.getContext('2d').drawImage(canvas, -box.x, -box.y);
87
+ return out.toBuffer('image/png');
88
+ },
89
+ };
90
+ }
91
+ /** Asks a widget's `urgent`, `idle`, `empty` or `visible` with the same inputs `renderWidget` would use. */
92
+ export function widgetState(w, hook, o = {}) {
93
+ const fn = w[hook];
94
+ if (!fn)
95
+ return undefined;
96
+ const { now, options, data, sources } = resolve(w, o);
97
+ const ctx = { options, data, sources, now, working: true, workday: DEFAULT_WORKDAY };
98
+ return fn(ctx);
99
+ }
100
+ /**
101
+ * Paints every widget of a plugin with its demo data at its minimum and
102
+ * preferred sizes and a wide and a tall one, in every theme and in each
103
+ * language given, and lists what went wrong: a `render` that throws, one
104
+ * that paints nothing, paints outside its box, or takes longer than
105
+ * `slowMs` (Kiosko warns at 50 ms). An empty list is a pass.
106
+ */
107
+ export function checkPlugin(p, o = {}) {
108
+ const issues = [];
109
+ const locales = o.locales ?? ['en', 'es'];
110
+ const themes = o.themes ?? THEMES.map((t) => t.id);
111
+ const slow = o.slowMs ?? 50;
112
+ for (const w of p.widgets ?? []) {
113
+ const type = `${p.id}/${w.id}`;
114
+ const pref = w.size?.preferred ?? { w: 480, h: 300 };
115
+ const min = w.size?.min ?? { w: Math.round(pref.w / 2), h: Math.round(pref.h / 2) };
116
+ const sizes = [min, pref, { w: Math.max(pref.w * 2, 900), h: Math.max(min.h, 120) }, { w: Math.max(min.w, 200), h: Math.max(pref.h * 2, 500) }, ...(o.extraSizes ?? [])];
117
+ for (const size of sizes) {
118
+ for (const theme of themes) {
119
+ for (const locale of locales) {
120
+ const where = `${size.w}x${size.h} ${theme} ${locale}`;
121
+ const r = renderWidget(w, { size, theme, locale });
122
+ if (r.error)
123
+ issues.push({ type, where, problem: `render threw: ${r.error}` });
124
+ else if (r.outside > 0)
125
+ issues.push({ type, where, problem: `painted ${r.outside} px outside its box` });
126
+ // The first paint pays for loading fonts and compiling code; on the panel a widget paints
127
+ // again and again. Slow means slow every time: the best of three.
128
+ if (r.ms > slow && !r.error) {
129
+ const ms = Math.min(r.ms, renderWidget(w, { size, theme, locale }).ms, renderWidget(w, { size, theme, locale }).ms);
130
+ if (ms > slow)
131
+ issues.push({ type, where, problem: `render took ${Math.round(ms)} ms` });
132
+ }
133
+ }
134
+ }
135
+ }
136
+ // Something must show with the demo data, at least at the preferred size.
137
+ const r = renderWidget(w, { size: pref });
138
+ if (!r.error) {
139
+ const px = r.canvas.getContext('2d').getImageData(r.box.x, r.box.y, r.box.w, r.box.h).data;
140
+ let inked = 0;
141
+ for (let i = 3; i < px.length; i += 4)
142
+ if (px[i] > 24)
143
+ inked++;
144
+ if (!inked)
145
+ issues.push({ type, where: `${pref.w}x${pref.h}`, problem: 'painted nothing with its demo data (add a `demo`)' });
146
+ }
147
+ }
148
+ return issues;
149
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiosko/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.2",
4
4
  "description": "Plugin SDK for Kiosko: define widgets, data sources and interludes for small always-on LCD panels.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -19,6 +19,11 @@
19
19
  "source": "./src/format.ts",
20
20
  "types": "./dist/format.d.ts",
21
21
  "default": "./dist/format.js"
22
+ },
23
+ "./testing": {
24
+ "source": "./src/testing.ts",
25
+ "types": "./dist/testing.d.ts",
26
+ "default": "./dist/testing.js"
22
27
  }
23
28
  },
24
29
  "files": [
package/src/context.ts CHANGED
@@ -10,7 +10,7 @@ import { localize, type Localized } from './i18n.ts';
10
10
  import type { BaseContext, Location, Logger } from './plugin.ts';
11
11
  import { DEFAULT_WORKDAY, type Workday } from './workday.ts';
12
12
 
13
- export function createBaseContext(o: { now: number; locale?: string; timeFormat?: TimeFormat; workday?: Workday; location?: Location; log?: Logger; dataDir?: string }): BaseContext {
13
+ export function createBaseContext(o: { now: number; locale?: string; timeFormat?: TimeFormat; workday?: Workday; location?: Location; log?: Logger; dataDir?: string; cacheDir?: string }): BaseContext {
14
14
  const locale = o.locale ?? 'en';
15
15
  return {
16
16
  now: o.now,
@@ -19,6 +19,7 @@ export function createBaseContext(o: { now: number; locale?: string; timeFormat?
19
19
  fmt: createFormatters({ locale, timeFormat: o.timeFormat ?? 'auto', now: o.now }),
20
20
  log: o.log ?? (() => undefined),
21
21
  dataDir: o.dataDir ?? '',
22
+ cacheDir: o.cacheDir ?? o.dataDir ?? '',
22
23
  ...(o.location ? { location: o.location } : {}),
23
24
  workday: o.workday ?? DEFAULT_WORKDAY,
24
25
  };
package/src/http.ts ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * A small HTTP client for sources and fetches, so every plugin talks to
3
+ * APIs the same polite way:
4
+ *
5
+ * const http = createHttp({ agent: 'kiosko-plugin-weather/1.2.0' });
6
+ * const { data } = await http.json<Forecast>(url, { signal: ctx.signal });
7
+ *
8
+ * - Conditional requests: it remembers each URL's ETag / Last-Modified and
9
+ * body; a 304 gives the body it had, without downloading it again.
10
+ * - Rate limits: a 429 or 503 with `Retry-After` (or GitHub's
11
+ * `X-RateLimit-Reset`) throws an `HttpError` with `retryAt`, and until
12
+ * then calls to that host fail at once without contacting it.
13
+ * - The caller's `signal` (Kiosko aborts it after the source's timeout).
14
+ * - A User-Agent naming the plugin and Kiosko, never the person.
15
+ */
16
+
17
+ export class HttpError extends Error {
18
+ readonly status: number;
19
+ readonly url: string;
20
+ /** When the server says to come back (rate limits), epoch ms. */
21
+ readonly retryAt?: number;
22
+ constructor(message: string, o: { status: number; url: string; retryAt?: number }) {
23
+ super(message);
24
+ this.name = 'HttpError';
25
+ this.status = o.status;
26
+ this.url = o.url;
27
+ if (o.retryAt !== undefined) this.retryAt = o.retryAt;
28
+ }
29
+ }
30
+
31
+ export interface HttpRequest {
32
+ signal?: AbortSignal;
33
+ headers?: Record<string, string>;
34
+ method?: string;
35
+ body?: string;
36
+ /** Don't use or keep the conditional-request cache for this call. */
37
+ noCache?: boolean;
38
+ }
39
+
40
+ export interface HttpResponse<T> {
41
+ data: T;
42
+ status: number;
43
+ /** False when the server said "not modified" and the remembered body was returned. */
44
+ fresh: boolean;
45
+ headers: Headers;
46
+ }
47
+
48
+ export interface HttpClient {
49
+ json<T = unknown>(url: string, req?: HttpRequest): Promise<HttpResponse<T>>;
50
+ text(url: string, req?: HttpRequest): Promise<HttpResponse<string>>;
51
+ /** Until when a host is resting because it rate-limited us (epoch ms), if it is. */
52
+ resting(url: string): number | undefined;
53
+ }
54
+
55
+ /** How long to wait from the response's own words, if it says: `Retry-After` (seconds or a date) or `X-RateLimit-Reset` (epoch seconds). */
56
+ export function retryAtOf(headers: Headers, now: number): number | undefined {
57
+ const ra = headers.get('retry-after');
58
+ if (ra) {
59
+ const s = Number(ra);
60
+ if (Number.isFinite(s)) return now + Math.max(0, s) * 1000;
61
+ const at = Date.parse(ra);
62
+ if (Number.isFinite(at)) return at;
63
+ }
64
+ const reset = Number(headers.get('x-ratelimit-reset'));
65
+ if (headers.get('x-ratelimit-remaining') === '0' && Number.isFinite(reset) && reset > 0) return reset * 1000;
66
+ return undefined;
67
+ }
68
+
69
+ const hostOf = (url: string) => {
70
+ try {
71
+ return new URL(url).host;
72
+ } catch {
73
+ return url;
74
+ }
75
+ };
76
+
77
+ export function createHttp(o: { agent?: string; fetch?: typeof fetch; now?: () => number; maxCached?: number } = {}): HttpClient {
78
+ const doFetch = o.fetch ?? fetch;
79
+ const now = o.now ?? Date.now;
80
+ const agent = `${o.agent ? `${o.agent} ` : ''}Kiosko (+https://kioskolcd.dev)`;
81
+ const cache = new Map<string, { etag?: string; modified?: string; body: string }>();
82
+ const rest = new Map<string, number>();
83
+ const max = o.maxCached ?? 200;
84
+
85
+ async function request(url: string, req: HttpRequest = {}): Promise<HttpResponse<string>> {
86
+ const host = hostOf(url);
87
+ const until = rest.get(host);
88
+ if (until !== undefined) {
89
+ if (until > now()) throw new HttpError(`${host} asked to wait until ${new Date(until).toISOString()}`, { status: 429, url, retryAt: until });
90
+ rest.delete(host);
91
+ }
92
+ const method = req.method ?? 'GET';
93
+ const cacheable = method === 'GET' && !req.noCache;
94
+ const hit = cacheable ? cache.get(url) : undefined;
95
+ const headers: Record<string, string> = { 'User-Agent': agent, ...req.headers };
96
+ if (hit?.etag) headers['If-None-Match'] = hit.etag;
97
+ if (hit?.modified) headers['If-Modified-Since'] = hit.modified;
98
+ const res = await doFetch(url, { method, headers, ...(req.body !== undefined ? { body: req.body } : {}), ...(req.signal ? { signal: req.signal } : {}) });
99
+ if (res.status === 304 && hit) return { data: hit.body, status: 304, fresh: false, headers: res.headers };
100
+ const retryAt = retryAtOf(res.headers, now());
101
+ if (res.status === 429 || res.status === 503 || (res.status === 403 && retryAt !== undefined)) {
102
+ const at = retryAt ?? now() + 60_000;
103
+ rest.set(host, at);
104
+ throw new HttpError(`HTTP ${res.status} from ${host}: rate-limited until ${new Date(at).toISOString()}`, { status: res.status, url, retryAt: at });
105
+ }
106
+ if (!res.ok) throw new HttpError(`HTTP ${res.status} from ${host}`, { status: res.status, url });
107
+ const body = await res.text();
108
+ if (cacheable) {
109
+ const etag = res.headers.get('etag') ?? undefined;
110
+ const modified = res.headers.get('last-modified') ?? undefined;
111
+ if (etag || modified) {
112
+ cache.delete(url);
113
+ cache.set(url, { ...(etag ? { etag } : {}), ...(modified ? { modified } : {}), body });
114
+ // Oldest out first.
115
+ while (cache.size > max) cache.delete(cache.keys().next().value!);
116
+ }
117
+ }
118
+ return { data: body, status: res.status, fresh: true, headers: res.headers };
119
+ }
120
+
121
+ return {
122
+ text: request,
123
+ async json<T>(url: string, req?: HttpRequest) {
124
+ const r = await request(url, { ...req, headers: { Accept: 'application/json', ...req?.headers } });
125
+ try {
126
+ return { ...r, data: JSON.parse(r.data) as T };
127
+ } catch {
128
+ throw new HttpError(`not JSON from ${hostOf(url)}`, { status: r.status, url });
129
+ }
130
+ },
131
+ resting(url: string) {
132
+ const at = rest.get(hostOf(url));
133
+ return at !== undefined && at > now() ? at : undefined;
134
+ },
135
+ };
136
+ }
package/src/index.ts CHANGED
@@ -8,3 +8,6 @@ export * from './list.ts';
8
8
  export * from './filter.ts';
9
9
  export * from './context.ts';
10
10
  export * from './location.ts';
11
+ export * from './system.ts';
12
+ export * from './semver.ts';
13
+ export * from './http.ts';