@kiosko/sdk 0.2.5 → 0.2.7

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/plugin.d.ts CHANGED
@@ -20,7 +20,7 @@
20
20
  import type { Canvas, Image, SKRSContext2D, createCanvas, loadImage } from '@napi-rs/canvas';
21
21
  import type * as Kit from '@loksly/lcd-canvas-kit';
22
22
  import type { Formatters } from './format.ts';
23
- import type { Localized } from './i18n.ts';
23
+ import type { Localized, PluralForms } from './i18n.ts';
24
24
  import type { Field, Infer, ObjectField } from './schema.ts';
25
25
  import type { Theme } from './theme.ts';
26
26
  import type { Workday } from './workday.ts';
@@ -80,6 +80,18 @@ export interface BaseContext {
80
80
  locale: string;
81
81
  /** Picks the user's language from a `Localized` text. */
82
82
  t: (text: Localized) => string;
83
+ /**
84
+ * `{n} files` with the plural form the user's language asks for:
85
+ * `ctx.plural(n, { en: { one: '{n} file', other: '{n} files' }, 'zh-Hant': { other: '{n} 個檔案' } })`.
86
+ * Use it for any text with a count in it, rather than `n === 1 ? … : …`.
87
+ */
88
+ plural: (n: number, forms: Record<string, PluralForms>) => string;
89
+ /**
90
+ * Which of `available` (language tags) to use for this user: for tables
91
+ * kept one per language (`TABLES[ctx.pickLanguage(Object.keys(TABLES))]`).
92
+ * English when none fits, else the first.
93
+ */
94
+ pickLanguage: (available: readonly string[]) => string;
83
95
  /**
84
96
  * Times and lengths of time in the user's language and clock (Settings →
85
97
  * time format): `fmt.time(at)` "14:05" / "2:05 PM", `fmt.ago(at)`
@@ -220,6 +232,64 @@ export interface AnimationContext<O, D> extends StateContext<O, D> {
220
232
  /** Random numbers in [0, 1). Use these and not `Math.random`, so tests can seed them. */
221
233
  rnd: () => number;
222
234
  }
235
+ /** How much an alert matters: the panel's frame turns blue, amber or red. */
236
+ export type AlertLevel = 'info' | 'warn' | 'critical';
237
+ /** From least to most. */
238
+ export declare const ALERT_LEVELS: readonly AlertLevel[];
239
+ /**
240
+ * Something that must be seen from across the room (the panel has no
241
+ * sound): smoke, a leak, the doorbell, a call, `main` broken, a typhoon
242
+ * warning. Returned by a widget's or a source's `alerts`, decided from its
243
+ * data like `urgent`; Kiosko decides how it is shown: over everything, on
244
+ * every screen whose settings let that level through (the rest keep it in
245
+ * the editor's band), with a flashing frame and the text still and huge.
246
+ * Kiosko 0.2.7 and later; older ones ignore `alerts`.
247
+ */
248
+ export interface Alert {
249
+ /**
250
+ * Stable while it is the same event, new for a new one (`smoke-kitchen`,
251
+ * `pipeline-4711`): an alert the user has seen ("Seen") stays hidden while
252
+ * the plugin keeps returning the same id, and shows again with a new id.
253
+ */
254
+ id: string;
255
+ level: AlertLevel;
256
+ /** A few words, painted as big as the panel allows: "Smoke in the kitchen". */
257
+ title: Localized;
258
+ /** One short line under it: "Sensor 2 · since 14:05". */
259
+ text?: Localized;
260
+ /**
261
+ * Who published it, a few letters, painted small in a corner next to the
262
+ * time: "IGN", "NWS", "AEMET", "气象署". Name the authority when the alert
263
+ * is someone else's: their licences ask for it, and the user must know
264
+ * where it comes from. Kiosko 0.2.7 and later; older ones ignore it.
265
+ */
266
+ source?: Localized;
267
+ /**
268
+ * A second line under `text`, to be read after it: the authority's own
269
+ * instruction ("Move away from the coast and go to high ground"), as it
270
+ * is. Painted smaller than the title and only as far as it fits. Kiosko
271
+ * 0.2.7 and later; older ones ignore it.
272
+ */
273
+ detail?: Localized;
274
+ /**
275
+ * An icon of Lucide's (`flame`, `droplet`, `bell-ring`, `phone-incoming`,
276
+ * `activity`, `cloud-lightning`, `git-branch`…; see docs/plugins.md for
277
+ * those the panel draws) or one or two characters (`震`). Default: by level.
278
+ */
279
+ icon?: string;
280
+ /** When it stops on its own (epoch ms). */
281
+ expiresAt?: number;
282
+ /** Or how long it lasts from when Kiosko first sees it, in ms. */
283
+ ttlMs?: number;
284
+ /** Whether "Seen" (or snoozing it) may hide it. Default true; `false` stays while the plugin returns it. */
285
+ dismissible?: boolean;
286
+ }
287
+ /** What a source's `alerts` is asked with. */
288
+ export interface SourceAlertContext<O, D> {
289
+ data: D | undefined;
290
+ options: O;
291
+ now: number;
292
+ }
223
293
  /**
224
294
  * When the widget must be repainted even though its data didn't change: a
225
295
  * clock every second, a countdown every minute. Fewer repaints are fewer
@@ -305,6 +375,15 @@ export interface WidgetDefinition<OF extends ObjectField<any> = ObjectField<any>
305
375
  urgent?: (ctx: StateContext<Infer<OF>, D>) => boolean;
306
376
  /** Default of the instance's `takeOver` switch (keep the tile while urgent). Default true. */
307
377
  takeOver?: boolean;
378
+ /**
379
+ * Alerts to show full-screen (see `Alert`): a smoke sensor going off, the
380
+ * pipeline of `main` failing. Plain and quick, from the data alone: it is
381
+ * asked for every instance on any page of an enabled screen (not only the
382
+ * one shown) whenever its data changes, and every few seconds. Return `[]`
383
+ * when there is nothing. Several instances of the widget returning the
384
+ * same `id` are one alert. Kiosko 0.2.7 and later.
385
+ */
386
+ alerts?: (ctx: StateContext<Infer<OF>, D>) => Alert[];
308
387
  /**
309
388
  * Has nothing to list right now (no reviews, no tasks). Declaring it gives
310
389
  * the widget a "hide when empty" switch (`hideWhenEmpty`): when on, an
@@ -357,10 +436,10 @@ export interface SourceDefinition<OF extends ObjectField<any> = ObjectField<any>
357
436
  /** Global options, edited once in Settings → Sources. */
358
437
  options?: OF;
359
438
  /**
360
- * Polled every `intervalMs` while some widget uses it. The user can change
361
- * the interval and the timeout in Settings → Data sources
362
- * (`sources["plugin/source"].intervalMs` / `.timeoutMs`): don't add options
363
- * of your own for them.
439
+ * Polled every `intervalMs` while some widget uses it (or always, see
440
+ * `background`). The user can change the interval and the timeout in
441
+ * Settings → Data sources (`sources["plugin/source"].intervalMs` /
442
+ * `.timeoutMs`): don't add options of your own for them.
364
443
  */
365
444
  read?: (ctx: SourceContext<Infer<OF>>) => Promise<D>;
366
445
  /** Default interval of `read`. Default: 30 s. */
@@ -378,6 +457,24 @@ export interface SourceDefinition<OF extends ObjectField<any> = ObjectField<any>
378
457
  now: number;
379
458
  locale: string;
380
459
  }) => D;
460
+ /**
461
+ * Alerts to show full-screen (see `Alert`), from the source's latest data:
462
+ * like a widget's `alerts`, for alerts that belong to the data itself (a
463
+ * Home Assistant smoke sensor, an earthquake report). Asked while the
464
+ * source runs: while some widget uses it, or always if it runs in the
465
+ * `background`. Kiosko 0.2.7 and later.
466
+ */
467
+ alerts?: (ctx: SourceAlertContext<Infer<OF>, D>) => Alert[];
468
+ /**
469
+ * May run with no widget using it, for its `alerts` alone (official
470
+ * warnings, earthquake reports): Settings → Data sources then offers a
471
+ * switch, "Watch for alerts without a widget", off by default
472
+ * (`sources["plugin/source"].background`). While it is on and the plugin
473
+ * is enabled, Kiosko reads (or watches) the source and asks its `alerts`
474
+ * even if no tile shows it. Only with `alerts`; Kiosko 0.2.7 and later,
475
+ * older ones ignore it (the source runs only while a widget uses it).
476
+ */
477
+ background?: boolean;
381
478
  /**
382
479
  * Named lists of values for the editor to offer in options, made from
383
480
  * this source's latest data (or its demo data before there is any): the
@@ -404,8 +501,29 @@ export interface InterludePlayer {
404
501
  /** Paints frame `i` on a canvas of the full panel size. May be async (to decode a prerendered frame). */
405
502
  draw: (g: Graphics, i: number) => void | Promise<void>;
406
503
  }
504
+ /** A button of the Play page's pad: a game controller's, the keyboard's arrows and keys, or the phone's touch pad. */
505
+ export type PadKey = 'up' | 'down' | 'left' | 'right' | 'a' | 'b' | 'x' | 'y' | 'l' | 'r' | 'start' | 'select';
506
+ export declare const PAD_KEYS: readonly PadKey[];
507
+ /** A button pressed or let go on the Play page. */
508
+ export interface PadEvent {
509
+ key: PadKey;
510
+ pressed: boolean;
511
+ }
512
+ /** The player's buttons, for an interlude being played (see `InterludeDefinition.input`). */
513
+ export interface InterludeInput {
514
+ /** Calls `listener` for every button pressed or let go; returns what stops it. */
515
+ on(listener: (e: PadEvent) => void): () => void;
516
+ }
407
517
  export interface InterludeContext<O> extends BaseContext {
408
518
  options: O;
519
+ /**
520
+ * Someone is playing it from the editor's Play page (only for an
521
+ * interlude with `input: true`): their buttons. It then lasts while they
522
+ * play (no `maxSeconds`; a minute without a button ends it), and `frames`
523
+ * may be `Infinity`. Undefined when it plays at its time slot. Kiosko
524
+ * 0.2.7 and later.
525
+ */
526
+ input?: InterludeInput;
409
527
  width: number;
410
528
  height: number;
411
529
  /** Deterministic per slot: the same quarter hour plays the same story. */
@@ -423,6 +541,21 @@ export interface InterludeDefinition<OF extends ObjectField<any> = ObjectField<a
423
541
  sources?: string[];
424
542
  /** Frames per second it was designed for. USB panels top out around 12-24 fps. */
425
543
  fps: number;
544
+ /**
545
+ * It can be played: the editor's Play page offers it, and when started
546
+ * from there `ctx.input` brings the player's buttons. Kiosko 0.2.7 and
547
+ * later.
548
+ */
549
+ input?: boolean;
550
+ /**
551
+ * A short recording for the plugin store, relative to its package
552
+ * (`docs/<id>.webm`, 6–10 s, and a still `docs/<id>.jpg` for where video
553
+ * doesn't play).
554
+ */
555
+ preview?: {
556
+ video?: string;
557
+ poster: string;
558
+ };
426
559
  /** Builds the animation. May be slow (it runs before playing, not during). */
427
560
  prepare: (ctx: InterludeContext<Infer<OF>>) => Promise<InterludePlayer | null>;
428
561
  /** Don't interrupt now (someone waits for a permission, a meeting is about to start). */
@@ -438,7 +571,7 @@ export interface InterludeDefinition<OF extends ObjectField<any> = ObjectField<a
438
571
  * package.json, `"kiosko": { "sdk": "^0.2.0" }`, so it can be refused before
439
572
  * it runs); the registry compares them with `satisfies`.
440
573
  */
441
- export declare const SDK_VERSION = "0.2.5";
574
+ export declare const SDK_VERSION = "0.2.7";
442
575
  /**
443
576
  * What a plugin does on the machine, declared for the person who installs
444
577
  * it: the Plugins page and the plugin store show it next to the plugin. It
@@ -522,11 +655,62 @@ export interface PluginDefinition {
522
655
  optional?: string[];
523
656
  /** The operating systems it works on. Omitted: all. Also npm's `os` in package.json. */
524
657
  platforms?: Platform[];
658
+ /**
659
+ * The languages its texts come in, as BCP 47 tags, English first:
660
+ * `['en', 'es', 'zh-Hant', 'zh-Hans']`. Chinese goes by script (`zh-Hant`
661
+ * for Taiwan and Hong Kong, `zh-Hans` for mainland China), never a bare
662
+ * `zh`. Every `Localized` text of the plugin has them all (the linter
663
+ * says which lack one). Also `kiosko.languages` in package.json, so a
664
+ * catalogue knows without running it. Omitted: the ones its texts use.
665
+ */
666
+ languages?: string[];
525
667
  widgets?: WidgetDefinition<any, any>[];
526
668
  sources?: SourceDefinition<any, any>[];
527
669
  interludes?: InterludeDefinition<any>[];
528
670
  /** Page layouts the editor offers, built from its widgets (see `PageTemplate`). */
529
671
  templates?: PageTemplate[];
672
+ /**
673
+ * The category it is browsed under in the plugin store when it has no
674
+ * widgets of its own (only interludes, say): `fun` or `scene`. With widgets,
675
+ * the store takes theirs.
676
+ */
677
+ category?: Category;
678
+ /**
679
+ * Where it is useful, for the plugin store (see `PluginMarkets`): only in
680
+ * Spain (an electricity tariff), not where its service isn't offered.
681
+ */
682
+ markets?: PluginMarkets;
683
+ /** Where to ask for help. Missing: `bugs` and `homepage` of package.json. */
684
+ support?: {
685
+ issues?: string;
686
+ discussions?: string;
687
+ docs?: string;
688
+ };
689
+ /** How it is sold. Only `free` for now: paid plugins are not there yet. */
690
+ pricing?: {
691
+ model: 'free';
692
+ };
693
+ /** A page to support its author (also `funding` in package.json). */
694
+ funding?: string;
695
+ /** What it costs to run, roughly, for the store (`memoryMb` while painting, `cpu`). */
696
+ resources?: {
697
+ memoryMb?: number;
698
+ cpu?: 'low' | 'medium' | 'high';
699
+ note?: Localized;
700
+ };
701
+ }
702
+ /**
703
+ * Where a plugin is useful, as regions: ISO 3166-1 alpha-2 country codes
704
+ * (`ES`, `TW`) or `EU`. The store marks it ("only useful in Spain") and its
705
+ * "available in my region" filter uses it; it is never hidden from search.
706
+ */
707
+ export interface PluginMarkets {
708
+ /** Only useful here (a country's tariff, a city's metro). */
709
+ only?: string[];
710
+ /** Its service isn't offered here. */
711
+ without?: string[];
712
+ /** What it needs there ("an account with Red Eléctrica"). */
713
+ note?: Localized;
530
714
  }
531
715
  export declare function defineWidget<OF extends ObjectField<any> = ObjectField<{}>, D = undefined>(w: WidgetDefinition<OF, D>): WidgetDefinition<OF, D>;
532
716
  export declare function defineSource<OF extends ObjectField<any> = ObjectField<{}>, D = unknown>(s: SourceDefinition<OF, D>): SourceDefinition<OF, D>;
package/dist/plugin.js CHANGED
@@ -1,21 +1,24 @@
1
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' } },
2
+ { id: 'agents', label: { en: 'AI agents', es: 'Agentes IA', de: 'KI-Agenten', 'zh-Hant': 'AI 代理', 'zh-Hans': 'AI 智能体' } },
3
+ { id: 'system', label: { en: 'System', es: 'Sistema', de: 'System', 'zh-Hant': '系統', 'zh-Hans': '系统' } },
4
+ { id: 'time', label: { en: 'Time & calendar', es: 'Tiempo y agenda', de: 'Zeit & Kalender', 'zh-Hant': '時間與行事曆', 'zh-Hans': '时间与日历' } },
5
+ { id: 'productivity', label: { en: 'Productivity', es: 'Productividad', de: 'Produktivität', 'zh-Hant': '生產力', 'zh-Hans': '效率' } },
6
+ { id: 'dev', label: { en: 'Development', es: 'Desarrollo', de: 'Entwicklung', 'zh-Hant': '開發', 'zh-Hans': '开发' } },
7
+ { id: 'info', label: { en: 'News & world', es: 'Noticias y mundo', de: 'Nachrichten & Welt', 'zh-Hant': '新聞與世界', 'zh-Hans': '新闻与世界' } },
8
+ { id: 'media', label: { en: 'Media', es: 'Multimedia', de: 'Medien', 'zh-Hant': '多媒體', 'zh-Hans': '多媒体' } },
9
+ { id: 'scene', label: { en: 'Scenes', es: 'Escenas', de: 'Szenen', 'zh-Hant': '場景', 'zh-Hans': '场景' } },
10
+ { id: 'fun', label: { en: 'Fun', es: 'Diversión', de: 'Spaß', 'zh-Hant': '趣味', 'zh-Hans': '趣味' } },
11
11
  ];
12
+ /** From least to most. */
13
+ export const ALERT_LEVELS = ['info', 'warn', 'critical'];
14
+ export const PAD_KEYS = ['up', 'down', 'left', 'right', 'a', 'b', 'x', 'y', 'l', 'r', 'start', 'select'];
12
15
  /**
13
16
  * The version of the plugin API this Kiosko speaks. A plugin says which
14
17
  * versions it was written for in `PluginDefinition.sdk` (and in its
15
18
  * package.json, `"kiosko": { "sdk": "^0.2.0" }`, so it can be refused before
16
19
  * it runs); the registry compares them with `satisfies`.
17
20
  */
18
- export const SDK_VERSION = '0.2.5';
21
+ export const SDK_VERSION = '0.2.7';
19
22
  /* Identity helpers: they only exist so TypeScript infers option and data types. */
20
23
  export function defineWidget(w) {
21
24
  return w;
package/dist/schema.js CHANGED
@@ -41,6 +41,9 @@ export const t = {
41
41
  export const FILTER_HELP = {
42
42
  en: 'Empty: all. Names or patterns, comma-separated: * matches anything, a leading ! leaves out (web, acme/*, !*-old).',
43
43
  es: 'Vacío: todos. Nombres o patrones separados por comas: * vale por cualquier cosa y un ! delante excluye (web, acme/*, !*-old).',
44
+ de: 'Leer: alle. Namen oder Muster, durch Kommas getrennt: * steht für alles, ein ! davor schließt aus (web, acme/*, !*-old).',
45
+ 'zh-Hant': '留空:全部。填入名稱或模式,以逗號分隔:* 代表任意字元,開頭加 ! 則排除(web, acme/*, !*-old)。',
46
+ 'zh-Hans': '留空:全部。填写名称或模式,用逗号分隔:* 匹配任意内容,开头加 ! 表示排除(web, acme/*, !*-old)。',
44
47
  };
45
48
  function clone(v) {
46
49
  return v === undefined ? v : JSON.parse(JSON.stringify(v));
package/dist/testing.d.ts CHANGED
@@ -16,7 +16,7 @@
16
16
  */
17
17
  import { type Canvas } from '@napi-rs/canvas';
18
18
  import type { TimeFormat } from './format.ts';
19
- import type { Box, PluginDefinition, WidgetDefinition } from './plugin.ts';
19
+ import type { Alert, Box, PluginDefinition, SourceDefinition, WidgetDefinition } from './plugin.ts';
20
20
  import { type Theme } from './theme.ts';
21
21
  export interface RenderOptions {
22
22
  /** The instance's options (validated against the widget's schema, defaults filled in). Default: the demo's, if any. */
@@ -61,6 +61,24 @@ export interface RenderResult {
61
61
  export declare function renderWidget(w: WidgetDefinition<any, any>, o?: RenderOptions): RenderResult;
62
62
  /** Asks a widget's `urgent`, `idle`, `empty` or `visible` with the same inputs `renderWidget` would use. */
63
63
  export declare function widgetState(w: WidgetDefinition<any, any>, hook: 'urgent' | 'idle' | 'empty' | 'visible', o?: RenderOptions): boolean | undefined;
64
+ /** Asks a widget's `alerts` with the same inputs `renderWidget` would use; `[]` when it has none. */
65
+ export declare function widgetAlerts(w: WidgetDefinition<any, any>, o?: RenderOptions): Alert[];
66
+ export interface SourceAlertOptions {
67
+ /** The source's options (validated against its schema, defaults filled in). */
68
+ options?: Record<string, unknown>;
69
+ /** Its latest data. Default: its `demo` data. */
70
+ data?: unknown;
71
+ now?: number;
72
+ /** For its `demo`. */
73
+ locale?: string;
74
+ /** Use the source's `demo` when `data` isn't given. Default true. */
75
+ demo?: boolean;
76
+ }
77
+ /**
78
+ * Asks a source's `alerts` the way Kiosko does: its options validated with
79
+ * their defaults, its demo data unless given other; `[]` when it has none.
80
+ */
81
+ export declare function sourceAlerts(s: SourceDefinition<any, any>, o?: SourceAlertOptions): Alert[];
64
82
  export interface PluginIssue {
65
83
  /** `plugin/widget`. */
66
84
  type: string;
@@ -71,7 +89,7 @@ export interface PluginIssue {
71
89
  /**
72
90
  * Paints every widget of a plugin with its demo data at its minimum and
73
91
  * 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
92
+ * language given (by default the ones the plugin declares), and lists what went wrong: a `render` that throws, one
75
93
  * that paints nothing, paints outside its box, or takes longer than
76
94
  * `slowMs` (Kiosko warns at 50 ms). An empty list is a pass.
77
95
  */
package/dist/testing.js CHANGED
@@ -97,16 +97,35 @@ export function widgetState(w, hook, o = {}) {
97
97
  const ctx = { options, data, sources, now, working: true, workday: DEFAULT_WORKDAY };
98
98
  return fn(ctx);
99
99
  }
100
+ /** Asks a widget's `alerts` with the same inputs `renderWidget` would use; `[]` when it has none. */
101
+ export function widgetAlerts(w, o = {}) {
102
+ if (!w.alerts)
103
+ return [];
104
+ const { now, options, data, sources } = resolve(w, o);
105
+ return w.alerts({ options, data, sources, now, working: true, workday: DEFAULT_WORKDAY });
106
+ }
107
+ /**
108
+ * Asks a source's `alerts` the way Kiosko does: its options validated with
109
+ * their defaults, its demo data unless given other; `[]` when it has none.
110
+ */
111
+ export function sourceAlerts(s, o = {}) {
112
+ if (!s.alerts)
113
+ return [];
114
+ const now = o.now ?? Date.UTC(2026, 10, 5, 9, 42);
115
+ const options = s.options ? validate(s.options, o.options ?? {}).value : {};
116
+ const data = 'data' in o ? o.data : o.demo === false ? undefined : s.demo?.({ now, locale: o.locale ?? 'en' });
117
+ return s.alerts({ data, options, now });
118
+ }
100
119
  /**
101
120
  * Paints every widget of a plugin with its demo data at its minimum and
102
121
  * 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
122
+ * language given (by default the ones the plugin declares), and lists what went wrong: a `render` that throws, one
104
123
  * that paints nothing, paints outside its box, or takes longer than
105
124
  * `slowMs` (Kiosko warns at 50 ms). An empty list is a pass.
106
125
  */
107
126
  export function checkPlugin(p, o = {}) {
108
127
  const issues = [];
109
- const locales = o.locales ?? ['en', 'es'];
128
+ const locales = o.locales ?? (p.languages?.length ? p.languages : ['en', 'es']);
110
129
  const themes = o.themes ?? THEMES.map((t) => t.id);
111
130
  const slow = o.slowMs ?? 50;
112
131
  for (const w of p.widgets ?? []) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiosko/sdk",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
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",
@@ -15,6 +15,16 @@
15
15
  "types": "./dist/workday.d.ts",
16
16
  "default": "./dist/workday.js"
17
17
  },
18
+ "./languages": {
19
+ "source": "./src/languages.ts",
20
+ "types": "./dist/languages.d.ts",
21
+ "default": "./dist/languages.js"
22
+ },
23
+ "./i18n": {
24
+ "source": "./src/i18n.ts",
25
+ "types": "./dist/i18n.d.ts",
26
+ "default": "./dist/i18n.js"
27
+ },
18
28
  "./format": {
19
29
  "source": "./src/format.ts",
20
30
  "types": "./dist/format.d.ts",
@@ -24,6 +34,11 @@
24
34
  "source": "./src/testing.ts",
25
35
  "types": "./dist/testing.d.ts",
26
36
  "default": "./dist/testing.js"
37
+ },
38
+ "./semver": {
39
+ "source": "./src/semver.ts",
40
+ "types": "./dist/semver.d.ts",
41
+ "default": "./dist/semver.js"
27
42
  }
28
43
  },
29
44
  "files": [
package/src/context.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  * const ctx = { ...createBaseContext({ now, locale: 'es' }), options, signal, intervalMs: 60_000, timeoutMs: 20_000 };
7
7
  */
8
8
  import { createFormatters, type TimeFormat } from './format.ts';
9
- import { localize, type Localized } from './i18n.ts';
9
+ import { localize, pickLocale, plural, type Localized, type PluralForms } 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
 
@@ -16,6 +16,8 @@ export function createBaseContext(o: { now: number; locale?: string; timeFormat?
16
16
  now: o.now,
17
17
  locale,
18
18
  t: (text: Localized) => localize(text, locale),
19
+ plural: (n: number, forms: Record<string, PluralForms>) => plural(n, forms, locale),
20
+ pickLanguage: (available: readonly string[]) => pickLocale(available, locale) ?? (available.includes('en') ? 'en' : available[0] ?? 'en'),
19
21
  fmt: createFormatters({ locale, timeFormat: o.timeFormat ?? 'auto', now: o.now }),
20
22
  log: o.log ?? (() => undefined),
21
23
  dataDir: o.dataDir ?? '',
package/src/format.ts CHANGED
@@ -2,13 +2,15 @@
2
2
  * Times and lengths of time, written the same way by every widget:
3
3
  * `ctx.fmt.time(at)`, `ctx.fmt.ago(at)` and `ctx.fmt.duration(ms)`.
4
4
  *
5
- * They follow the panel's language (English and Spanish words; any other
6
- * language gets the English ones) and the config's `timeFormat`. Hand-written
5
+ * They follow the panel's language (English, Spanish, German, Traditional and
6
+ * Simplified Chinese words; any other language gets the English ones) and the config's `timeFormat`. Hand-written
7
7
  * rather than `Intl.RelativeTimeFormat`: its short forms differ between ICU
8
8
  * versions (Node, Chromium, WebKit), and a panel must paint the same thing in
9
9
  * the editor, the browser demo and on the glass.
10
10
  */
11
11
 
12
+ import { pickLocale } from './i18n.ts';
13
+
12
14
  /** How clock times are written: `auto` follows the language (24 h in Spanish, 12 h in US English). */
13
15
  export type TimeFormat = 'auto' | '24h' | '12h';
14
16
  export const TIME_FORMATS: readonly TimeFormat[] = ['auto', '24h', '12h'];
@@ -18,10 +20,15 @@ export interface Formatters {
18
20
  readonly hour12: boolean;
19
21
  /**
20
22
  * A clock time: `"09:05"` on a 24-hour clock, `"9:05 AM"` (`"9:05 a. m."`)
21
- * on a 12-hour one. `seconds` adds `":07"`; `ampm: false` leaves out
23
+ * on a 12-hour one (`"上午 9:05"` in Chinese). `seconds` adds `":07"`; `ampm: false` leaves out
22
24
  * AM/PM (a big clock that paints it apart).
23
25
  */
24
26
  time(at: number | Date, o?: { seconds?: boolean; ampm?: boolean }): string;
27
+ /**
28
+ * From one clock time to another: `"14:00–15:30"`, `"3:30–4:00 PM"`,
29
+ * `"下午 3:30–4:00"` (AM/PM once when both are in the same half of the day).
30
+ */
31
+ range(from: number | Date, to: number | Date, o?: { seconds?: boolean }): string;
25
32
  /**
26
33
  * How long ago `at` (epoch ms, a Date or an ISO string) was, from `ctx.now`:
27
34
  * `"just now"`, `"5 min ago"`, `"3 h ago"`, `"4 d ago"`, `"2 wk ago"`,
@@ -39,23 +46,76 @@ export interface Formatters {
39
46
  duration(ms: number, o?: { seconds?: boolean; round?: 'down' | 'up' | 'nearest'; compact?: boolean }): string;
40
47
  }
41
48
 
49
+ /**
50
+ * A language's words for times. Every unit gets the number, so a language
51
+ * whose units change with it (Polish, Russian, Arabic) can say so.
52
+ */
42
53
  interface Words {
43
54
  now: string;
44
55
  justNow: string;
45
- ago: (v: string) => string;
46
- wk: string;
56
+ /** `v` is the age already written ("5 min"), `n` its number. */
57
+ ago: (v: string, n: number) => string;
58
+ s: (n: number) => string;
59
+ min: (n: number) => string;
60
+ h: (n: number) => string;
61
+ d: (n: number) => string;
62
+ wk: (n: number) => string;
47
63
  yr: (n: number) => string;
64
+ /** Hours and minutes of a running length: "1 h 05", "1 小時 5 分". */
65
+ hm: (h: number, m: number) => string;
66
+ /** Days and hours: "2 d 3 h". */
67
+ dh: (d: number, h: number) => string;
48
68
  am: string;
49
69
  pm: string;
70
+ /** AM/PM goes before the time (上午 9:05), not after. */
71
+ ampmFirst?: boolean;
50
72
  }
51
73
 
74
+ const latin = (wk: string, yr: (n: number) => string) => ({
75
+ s: (n: number) => `${n} s`,
76
+ min: (n: number) => `${n} min`,
77
+ h: (n: number) => `${n} h`,
78
+ d: (n: number) => `${n} d`,
79
+ wk: (n: number) => `${n} ${wk}`,
80
+ yr: (n: number) => `${n} ${yr(n)}`,
81
+ hm: (h: number, m: number) => `${h} h ${pad2(m)}`,
82
+ dh: (d: number, h: number) => `${d} d ${h} h`,
83
+ });
84
+ // German: abbreviations with a full stop (5 Min., 3 Std.), which also spare the dative after "vor" (vor 2 Tagen); a running length as 1:05 h.
85
+ const german = {
86
+ s: (n: number) => `${n} s`,
87
+ min: (n: number) => `${n} Min.`,
88
+ h: (n: number) => `${n} Std.`,
89
+ d: (n: number) => `${n} T.`,
90
+ wk: (n: number) => `${n} Wo.`,
91
+ yr: (n: number) => `${n} J.`,
92
+ hm: (h: number, m: number) => `${h}:${pad2(m)} h`,
93
+ dh: (d: number, h: number) => `${d} T. ${h} Std.`,
94
+ };
95
+ const chinese = (u: { min: string; h: string; wk: string }) => ({
96
+ s: (n: number) => `${n} 秒`,
97
+ min: (n: number) => `${n} ${u.min}`,
98
+ h: (n: number) => `${n} ${u.h}`,
99
+ d: (n: number) => `${n} 天`,
100
+ wk: (n: number) => `${n} ${u.wk}`,
101
+ yr: (n: number) => `${n} 年`,
102
+ // No leading zero in Chinese: 1 小時 5 分.
103
+ hm: (h: number, m: number) => `${h} ${u.h} ${m} 分`,
104
+ dh: (d: number, h: number) => `${d} 天 ${h} ${u.h}`,
105
+ });
106
+
52
107
  const WORDS: Record<string, Words> = {
53
- en: { now: 'now', justNow: 'just now', ago: (v) => `${v} ago`, wk: 'wk', yr: () => 'yr', am: 'AM', pm: 'PM' },
54
- es: { now: 'ahora', justNow: 'ahora mismo', ago: (v) => `hace ${v}`, wk: 'sem', yr: (n) => (n === 1 ? 'año' : 'años'), am: 'a. m.', pm: 'p. m.' },
108
+ en: { now: 'now', justNow: 'just now', ago: (v) => `${v} ago`, am: 'AM', pm: 'PM', ...latin('wk', () => 'yr') },
109
+ es: { now: 'ahora', justNow: 'ahora mismo', ago: (v) => `hace ${v}`, am: 'a. m.', pm: 'p. m.', ...latin('sem', (n) => (n === 1 ? 'año' : 'años')) },
110
+ de: { now: 'jetzt', justNow: 'gerade eben', ago: (v) => `vor ${v}`, am: 'AM', pm: 'PM', ...german },
111
+ 'zh-Hant': { now: '現在', justNow: '剛剛', ago: (v) => `${v}前`, am: '上午', pm: '下午', ampmFirst: true, ...chinese({ min: '分鐘', h: '小時', wk: '週' }) },
112
+ 'zh-Hans': { now: '现在', justNow: '刚刚', ago: (v) => `${v}前`, am: '上午', pm: '下午', ampmFirst: true, ...chinese({ min: '分钟', h: '小时', wk: '周' }) },
55
113
  };
114
+ /** The languages ctx.fmt has words for (a test checks every language Kiosko speaks is here). */
115
+ export const FORMAT_LANGUAGES = Object.keys(WORDS);
116
+ const LANGS = Object.keys(WORDS);
56
117
 
57
- const langOf = (locale: string) => locale.toLowerCase().split(/[-_]/)[0] ?? 'en';
58
- const wordsFor = (locale: string): Words => WORDS[langOf(locale)] ?? WORDS.en!;
118
+ const wordsFor = (locale: string): Words => WORDS[pickLocale(LANGS, locale) ?? 'en'] ?? WORDS.en!;
59
119
  const pad2 = (n: number) => String(n).padStart(2, '0');
60
120
 
61
121
  const cycles = new Map<string, boolean>();
@@ -89,7 +149,7 @@ function toMs(at: number | Date | string): number {
89
149
  export function createFormatters(o: { locale: string; timeFormat?: TimeFormat; now: number }): Formatters {
90
150
  const w = wordsFor(o.locale);
91
151
  const hour12 = usesHour12(o.locale, o.timeFormat);
92
- return {
152
+ const fmt: Formatters = {
93
153
  hour12,
94
154
  time(at, opts = {}) {
95
155
  const d = new Date(toMs(at));
@@ -97,7 +157,16 @@ export function createFormatters(o: { locale: string; timeFormat?: TimeFormat; n
97
157
  const rest = `:${pad2(d.getMinutes())}${opts.seconds ? `:${pad2(d.getSeconds())}` : ''}`;
98
158
  if (!hour12) return `${pad2(h)}${rest}`;
99
159
  const base = `${h % 12 || 12}${rest}`;
100
- return opts.ampm === false ? base : `${base} ${h < 12 ? w.am : w.pm}`;
160
+ if (opts.ampm === false) return base;
161
+ const mark = h < 12 ? w.am : w.pm;
162
+ return w.ampmFirst ? `${mark} ${base}` : `${base} ${mark}`;
163
+ },
164
+ range(from, to, opts = {}) {
165
+ const a = new Date(toMs(from));
166
+ const b = new Date(toMs(to));
167
+ if (!hour12 || (a.getHours() < 12) !== (b.getHours() < 12)) return `${fmt.time(a, opts)}–${fmt.time(b, opts)}`;
168
+ // The same half of the day: AM/PM once, where the language puts it.
169
+ return w.ampmFirst ? `${fmt.time(a, opts)}–${fmt.time(b, { ...opts, ampm: false })}` : `${fmt.time(a, { ...opts, ampm: false })}–${fmt.time(b, opts)}`;
101
170
  },
102
171
  ago(at, opts = {}) {
103
172
  const suffix = opts.suffix !== false;
@@ -106,18 +175,19 @@ export function createFormatters(o: { locale: string; timeFormat?: TimeFormat; n
106
175
  if (!Number.isFinite(min) || min < 1) return suffix ? w.justNow : w.now;
107
176
  const h = Math.floor(min / 60);
108
177
  const d = Math.floor(h / 24);
109
- const v = min < 60 ? `${min} min` : h < 24 ? `${h} h` : d < 14 ? `${d} d` : d < 365 ? `${Math.floor(d / 7)} ${w.wk}` : `${Math.floor(d / 365)} ${w.yr(Math.floor(d / 365))}`;
110
- return suffix ? w.ago(v) : v;
178
+ const [v, n] = min < 60 ? [w.min(min), min] : h < 24 ? [w.h(h), h] : d < 14 ? [w.d(d), d] : d < 365 ? [w.wk(Math.floor(d / 7)), Math.floor(d / 7)] : [w.yr(Math.floor(d / 365)), Math.floor(d / 365)];
179
+ return suffix ? w.ago(v, n) : v;
111
180
  },
112
181
  duration(ms, opts = {}) {
113
182
  const round = opts.round === 'up' ? Math.ceil : opts.round === 'nearest' ? Math.round : Math.floor;
114
183
  const safe = Number.isFinite(ms) ? Math.max(0, ms) : 0;
115
- if (opts.seconds && safe < 60_000) return `${round(safe / 1000)} s`;
184
+ if (opts.seconds && safe < 60_000) return w.s(round(safe / 1000));
116
185
  const min = round(safe / 60_000);
117
- if (min < 60) return `${min} min`;
186
+ if (min < 60) return w.min(min);
118
187
  const h = Math.floor(min / 60);
119
- if (h < 24) return opts.compact && min % 60 === 0 ? `${h} h` : `${h} h ${pad2(min % 60)}`;
120
- return opts.compact && h % 24 === 0 ? `${h / 24} d` : `${Math.floor(h / 24)} d ${h % 24} h`;
188
+ if (h < 24) return opts.compact && min % 60 === 0 ? w.h(h) : w.hm(h, min % 60);
189
+ return opts.compact && h % 24 === 0 ? w.d(h / 24) : w.dh(Math.floor(h / 24), h % 24);
121
190
  },
122
191
  };
192
+ return fmt;
123
193
  }