@kiosko/sdk 0.2.1 → 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/http.d.ts ADDED
@@ -0,0 +1,55 @@
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
+ export declare class HttpError extends Error {
17
+ readonly status: number;
18
+ readonly url: string;
19
+ /** When the server says to come back (rate limits), epoch ms. */
20
+ readonly retryAt?: number;
21
+ constructor(message: string, o: {
22
+ status: number;
23
+ url: string;
24
+ retryAt?: number;
25
+ });
26
+ }
27
+ export interface HttpRequest {
28
+ signal?: AbortSignal;
29
+ headers?: Record<string, string>;
30
+ method?: string;
31
+ body?: string;
32
+ /** Don't use or keep the conditional-request cache for this call. */
33
+ noCache?: boolean;
34
+ }
35
+ export interface HttpResponse<T> {
36
+ data: T;
37
+ status: number;
38
+ /** False when the server said "not modified" and the remembered body was returned. */
39
+ fresh: boolean;
40
+ headers: Headers;
41
+ }
42
+ export interface HttpClient {
43
+ json<T = unknown>(url: string, req?: HttpRequest): Promise<HttpResponse<T>>;
44
+ text(url: string, req?: HttpRequest): Promise<HttpResponse<string>>;
45
+ /** Until when a host is resting because it rate-limited us (epoch ms), if it is. */
46
+ resting(url: string): number | undefined;
47
+ }
48
+ /** 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). */
49
+ export declare function retryAtOf(headers: Headers, now: number): number | undefined;
50
+ export declare function createHttp(o?: {
51
+ agent?: string;
52
+ fetch?: typeof fetch;
53
+ now?: () => number;
54
+ maxCached?: number;
55
+ }): HttpClient;
package/dist/http.js ADDED
@@ -0,0 +1,118 @@
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
+ export class HttpError extends Error {
17
+ status;
18
+ url;
19
+ /** When the server says to come back (rate limits), epoch ms. */
20
+ retryAt;
21
+ constructor(message, o) {
22
+ super(message);
23
+ this.name = 'HttpError';
24
+ this.status = o.status;
25
+ this.url = o.url;
26
+ if (o.retryAt !== undefined)
27
+ this.retryAt = o.retryAt;
28
+ }
29
+ }
30
+ /** 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). */
31
+ export function retryAtOf(headers, now) {
32
+ const ra = headers.get('retry-after');
33
+ if (ra) {
34
+ const s = Number(ra);
35
+ if (Number.isFinite(s))
36
+ return now + Math.max(0, s) * 1000;
37
+ const at = Date.parse(ra);
38
+ if (Number.isFinite(at))
39
+ return at;
40
+ }
41
+ const reset = Number(headers.get('x-ratelimit-reset'));
42
+ if (headers.get('x-ratelimit-remaining') === '0' && Number.isFinite(reset) && reset > 0)
43
+ return reset * 1000;
44
+ return undefined;
45
+ }
46
+ const hostOf = (url) => {
47
+ try {
48
+ return new URL(url).host;
49
+ }
50
+ catch {
51
+ return url;
52
+ }
53
+ };
54
+ export function createHttp(o = {}) {
55
+ const doFetch = o.fetch ?? fetch;
56
+ const now = o.now ?? Date.now;
57
+ const agent = `${o.agent ? `${o.agent} ` : ''}Kiosko (+https://kioskolcd.dev)`;
58
+ const cache = new Map();
59
+ const rest = new Map();
60
+ const max = o.maxCached ?? 200;
61
+ async function request(url, req = {}) {
62
+ const host = hostOf(url);
63
+ const until = rest.get(host);
64
+ if (until !== undefined) {
65
+ if (until > now())
66
+ throw new HttpError(`${host} asked to wait until ${new Date(until).toISOString()}`, { status: 429, url, retryAt: until });
67
+ rest.delete(host);
68
+ }
69
+ const method = req.method ?? 'GET';
70
+ const cacheable = method === 'GET' && !req.noCache;
71
+ const hit = cacheable ? cache.get(url) : undefined;
72
+ const headers = { 'User-Agent': agent, ...req.headers };
73
+ if (hit?.etag)
74
+ headers['If-None-Match'] = hit.etag;
75
+ if (hit?.modified)
76
+ headers['If-Modified-Since'] = hit.modified;
77
+ const res = await doFetch(url, { method, headers, ...(req.body !== undefined ? { body: req.body } : {}), ...(req.signal ? { signal: req.signal } : {}) });
78
+ if (res.status === 304 && hit)
79
+ return { data: hit.body, status: 304, fresh: false, headers: res.headers };
80
+ const retryAt = retryAtOf(res.headers, now());
81
+ if (res.status === 429 || res.status === 503 || (res.status === 403 && retryAt !== undefined)) {
82
+ const at = retryAt ?? now() + 60_000;
83
+ rest.set(host, at);
84
+ throw new HttpError(`HTTP ${res.status} from ${host}: rate-limited until ${new Date(at).toISOString()}`, { status: res.status, url, retryAt: at });
85
+ }
86
+ if (!res.ok)
87
+ throw new HttpError(`HTTP ${res.status} from ${host}`, { status: res.status, url });
88
+ const body = await res.text();
89
+ if (cacheable) {
90
+ const etag = res.headers.get('etag') ?? undefined;
91
+ const modified = res.headers.get('last-modified') ?? undefined;
92
+ if (etag || modified) {
93
+ cache.delete(url);
94
+ cache.set(url, { ...(etag ? { etag } : {}), ...(modified ? { modified } : {}), body });
95
+ // Oldest out first.
96
+ while (cache.size > max)
97
+ cache.delete(cache.keys().next().value);
98
+ }
99
+ }
100
+ return { data: body, status: res.status, fresh: true, headers: res.headers };
101
+ }
102
+ return {
103
+ text: request,
104
+ async json(url, req) {
105
+ const r = await request(url, { ...req, headers: { Accept: 'application/json', ...req?.headers } });
106
+ try {
107
+ return { ...r, data: JSON.parse(r.data) };
108
+ }
109
+ catch {
110
+ throw new HttpError(`not JSON from ${hostOf(url)}`, { status: r.status, url });
111
+ }
112
+ },
113
+ resting(url) {
114
+ const at = rest.get(hostOf(url));
115
+ return at !== undefined && at > now() ? at : undefined;
116
+ },
117
+ };
118
+ }
package/dist/index.d.ts CHANGED
@@ -9,3 +9,5 @@ export * from './filter.ts';
9
9
  export * from './context.ts';
10
10
  export * from './location.ts';
11
11
  export * from './system.ts';
12
+ export * from './semver.ts';
13
+ export * from './http.ts';
package/dist/index.js CHANGED
@@ -9,3 +9,5 @@ export * from "./filter.js";
9
9
  export * from "./context.js";
10
10
  export * from "./location.js";
11
11
  export * from "./system.js";
12
+ export * from "./semver.js";
13
+ export * from "./http.js";
package/dist/plugin.d.ts CHANGED
@@ -363,6 +363,25 @@ export interface SourceDefinition<OF extends ObjectField<any> = ObjectField<any>
363
363
  now: number;
364
364
  locale: string;
365
365
  }) => D;
366
+ /**
367
+ * Named lists of values for the editor to offer in options, made from
368
+ * this source's latest data (or its demo data before there is any): the
369
+ * entities of a Home Assistant, the calendars read, the repos seen. A
370
+ * field asks for one with `choices: { source: 'plugin/source', list }`.
371
+ * Plain and quick: they run when the editor opens a form.
372
+ */
373
+ choices?: Record<string, (data: D, ctx: {
374
+ locale: string;
375
+ t: (text: Localized) => string;
376
+ }) => Choice[]>;
377
+ }
378
+ /** One value the editor offers for an option (see `SourceDefinition.choices`). */
379
+ export interface Choice {
380
+ value: string;
381
+ /** What the person sees, when it isn't the value itself (`Living room` for `sensor.living_room`). */
382
+ label?: string;
383
+ /** Heading to group it under (`Sensors`, `Lights`). */
384
+ group?: string;
366
385
  }
367
386
  export interface InterludePlayer {
368
387
  /** Number of frames. */
@@ -398,6 +417,62 @@ export interface InterludeDefinition<OF extends ObjectField<any> = ObjectField<a
398
417
  options: Infer<OF>;
399
418
  }) => boolean;
400
419
  }
420
+ /**
421
+ * The version of the plugin API this Kiosko speaks. A plugin says which
422
+ * versions it was written for in `PluginDefinition.sdk` (and in its
423
+ * package.json, `"kiosko": { "sdk": "^0.2.0" }`, so it can be refused before
424
+ * it runs); the registry compares them with `satisfies`.
425
+ */
426
+ export declare const SDK_VERSION = "0.2.2";
427
+ /**
428
+ * What a plugin does on the machine, declared for the person who installs
429
+ * it: the Plugins page and the plugin store show it next to the plugin. It
430
+ * is a promise, not (yet) a fence: plugins run with the user's rights. Keep
431
+ * it honest and small; options with a `risk` (see `Risk`) are listed apart.
432
+ */
433
+ export interface Permissions {
434
+ /**
435
+ * Hosts it contacts on its own: exact names (`api.github.com`,
436
+ * `*.open-meteo.com`), `user` for the hosts the user types in its options
437
+ * (a feed, a Home Assistant), `lan` for the local network.
438
+ */
439
+ network?: string[];
440
+ /** Programs it runs (`nvidia-smi`, `pactl`, `ssh`); `user` for a command the user configures. */
441
+ exec?: string[];
442
+ /** Files or folders it reads or writes besides its own `dataDir`/`cacheDir` (`~/.aimonitor/sessions`); `user` for paths the user configures. */
443
+ files?: string[];
444
+ /** Hardware or system services it talks to: `usb`, `audio` (whether the microphone is in use), `mpris` (what is playing), `bluetooth`… */
445
+ devices?: string[];
446
+ }
447
+ /** One tile of a page template, in fractions of the page (0..1). */
448
+ export interface TemplateTile {
449
+ x: number;
450
+ y: number;
451
+ w: number;
452
+ h: number;
453
+ /** Widget types, stacked; a bare id (`clock`) is this plugin's own. With options: `['clock', { showDate: true }]`. */
454
+ widgets: (string | [string, Record<string, unknown>])[];
455
+ chrome?: 'card' | 'bare';
456
+ }
457
+ /**
458
+ * A starting layout the editor offers under "New page", made of this
459
+ * plugin's widgets (and others', if installed: tiles whose widgets are all
460
+ * missing are left out).
461
+ */
462
+ export interface PageTemplate {
463
+ /** Unique inside the plugin. */
464
+ id: string;
465
+ name: Localized;
466
+ /** An icon of the editor (Lucide name). */
467
+ icon?: string;
468
+ /** For strips and wide panels. */
469
+ wide: TemplateTile[];
470
+ /** For square-ish panels; defaults to `wide`. */
471
+ square?: TemplateTile[];
472
+ /** For portrait panels; defaults to `wide` turned a quarter (columns become bands). */
473
+ tall?: TemplateTile[];
474
+ }
475
+ export type Platform = 'linux' | 'darwin' | 'win32';
401
476
  export interface PluginDefinition {
402
477
  /** npm-like id: lowercase, digits and dashes. Stable: configs refer to it. */
403
478
  id: string;
@@ -406,11 +481,37 @@ export interface PluginDefinition {
406
481
  description?: Localized;
407
482
  author?: string;
408
483
  homepage?: string;
484
+ /** Where its code lives (a git URL): the store links to it. */
485
+ repository?: string;
409
486
  license?: string;
410
487
  icon?: string;
488
+ /**
489
+ * The plugin API versions it works with, as an npm range (`^0.2.0`).
490
+ * Without it, any Kiosko is assumed to fit. Put the same in package.json
491
+ * (`"kiosko": { "sdk": … }`) so an incompatible plugin is refused before
492
+ * its code runs.
493
+ */
494
+ sdk?: string;
495
+ /** What it does on the machine (see `Permissions`). */
496
+ permissions?: Permissions;
497
+ /**
498
+ * Sources or widgets of other plugins it needs (`agents/sessions`): the
499
+ * editor says which are missing and offers to install their plugins.
500
+ */
501
+ requires?: string[];
502
+ /**
503
+ * Sources or widgets of other plugins it uses when they are there, and
504
+ * does without otherwise (the weather in a corner): never asked for, only
505
+ * mentioned.
506
+ */
507
+ optional?: string[];
508
+ /** The operating systems it works on. Omitted: all. Also npm's `os` in package.json. */
509
+ platforms?: Platform[];
411
510
  widgets?: WidgetDefinition<any, any>[];
412
511
  sources?: SourceDefinition<any, any>[];
413
512
  interludes?: InterludeDefinition<any>[];
513
+ /** Page layouts the editor offers, built from its widgets (see `PageTemplate`). */
514
+ templates?: PageTemplate[];
414
515
  }
415
516
  export declare function defineWidget<OF extends ObjectField<any> = ObjectField<{}>, D = undefined>(w: WidgetDefinition<OF, D>): WidgetDefinition<OF, D>;
416
517
  export declare function defineSource<OF extends ObjectField<any> = ObjectField<{}>, D = unknown>(s: SourceDefinition<OF, D>): SourceDefinition<OF, D>;
package/dist/plugin.js CHANGED
@@ -9,6 +9,13 @@ export const CATEGORIES = [
9
9
  { id: 'scene', label: { en: 'Scenes', es: 'Escenas' } },
10
10
  { id: 'fun', label: { en: 'Fun', es: 'Diversión' } },
11
11
  ];
12
+ /**
13
+ * The version of the plugin API this Kiosko speaks. A plugin says which
14
+ * versions it was written for in `PluginDefinition.sdk` (and in its
15
+ * package.json, `"kiosko": { "sdk": "^0.2.0" }`, so it can be refused before
16
+ * it runs); the registry compares them with `satisfies`.
17
+ */
18
+ export const SDK_VERSION = '0.2.2';
12
19
  /* Identity helpers: they only exist so TypeScript infers option and data types. */
13
20
  export function defineWidget(w) {
14
21
  return w;
package/dist/schema.d.ts CHANGED
@@ -35,9 +35,23 @@ interface Common<T> {
35
35
  /** See `Risk`. Exported as `x-risk`; `kiosko config import` lists these values before applying a config. */
36
36
  risk?: Risk | readonly Risk[];
37
37
  }
38
+ /**
39
+ * Where the editor finds values to offer for a text field: a named list of
40
+ * a source (see `SourceDefinition.choices`), computed from its live data,
41
+ * e.g. the entities of the user's Home Assistant. The field stays free
42
+ * text: a value that isn't in the list is kept.
43
+ */
44
+ export interface ChoicesRef {
45
+ /** `plugin/source`. */
46
+ source: string;
47
+ /** The name of the list in that source's `choices`. */
48
+ list: string;
49
+ }
38
50
  export interface StringField extends Common<string> {
39
51
  kind: 'string';
40
52
  placeholder?: string;
53
+ /** Values to offer, from a source's live data (see `ChoicesRef`). */
54
+ choices?: ChoicesRef;
41
55
  multiline?: boolean;
42
56
  /** Tokens, URLs with credentials…: masked in the editor and never logged. */
43
57
  secret?: boolean;
@@ -116,7 +130,9 @@ export declare const t: {
116
130
  * `repos`, `calendars`, `people`) and give it a `label`; the `help`
117
131
  * explaining the patterns comes with it.
118
132
  */
119
- filter: (o?: Opts<ListField<StringField>, "item">) => ListField<StringField>;
133
+ filter: ({ choices, ...o }?: Opts<ListField<StringField>, "item"> & {
134
+ choices?: ChoicesRef;
135
+ }) => ListField<StringField>;
120
136
  };
121
137
  /** The help every `t.filter()` field carries unless it brings its own. */
122
138
  export declare const FILTER_HELP: Localized;
package/dist/schema.js CHANGED
@@ -28,9 +28,9 @@ export const t = {
28
28
  * `repos`, `calendars`, `people`) and give it a `label`; the `help`
29
29
  * explaining the patterns comes with it.
30
30
  */
31
- filter: (o = {}) => ({
31
+ filter: ({ choices, ...o } = {}) => ({
32
32
  kind: 'list',
33
- item: { kind: 'string', default: '', placeholder: 'name, group/*, !old-*' },
33
+ item: { kind: 'string', default: '', placeholder: 'name, group/*, !old-*', ...(choices ? { choices } : {}) },
34
34
  default: [],
35
35
  filter: true,
36
36
  help: FILTER_HELP,
@@ -144,7 +144,7 @@ export function toJsonSchema(f) {
144
144
  };
145
145
  switch (f.kind) {
146
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 } };
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, choices: f.choices } };
148
148
  case 'color':
149
149
  return { ...base, type: 'string', 'x-ui': { ...ui, widget: 'color' } };
150
150
  case 'number':
@@ -154,7 +154,7 @@ export function toJsonSchema(f) {
154
154
  case 'enum':
155
155
  return { ...base, type: 'string', enum: [...f.values], 'x-ui': { ...ui, labels: f.labels } };
156
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 } : {}) };
157
+ 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 } : {}) };
158
158
  case 'map':
159
159
  return { ...base, type: 'object', additionalProperties: { type: 'string' } };
160
160
  case 'object':
@@ -0,0 +1,25 @@
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
+ type V = [number, number, number, string];
15
+ /** `1.2.3` → its parts; null when it isn't a version. */
16
+ export declare function parseVersion(s: string): V | null;
17
+ /** -1, 0 or 1. A pre-release sorts before the release of the same numbers. */
18
+ export declare function compareVersions(a: string, b: string): number;
19
+ /**
20
+ * Whether `version` is in `range`. A pre-release only matches a range that
21
+ * names a pre-release of the same numbers (npm's rule), so `0.3.0-beta` does
22
+ * not quietly satisfy `^0.2`. An unreadable range or version is `false`.
23
+ */
24
+ export declare function satisfies(version: string, range: string): boolean;
25
+ export {};
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,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[];