kiosko 0.2.6 → 0.2.8

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.
@@ -0,0 +1,3954 @@
1
+ import { createRequire as __kioskoRequire } from 'node:module'; const require = __kioskoRequire(import.meta.url);
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
7
+
8
+ // packages/sdk/src/workday.ts
9
+ var DEFAULT_WORKDAY = { days: [1, 2, 3, 4, 5], start: "09:00", end: "17:00", hours: 8, holidays: [], byDay: {} };
10
+ function minutesOf(hhmm) {
11
+ const m = /^(\d{1,2}):(\d{2})/.exec(hhmm ?? "");
12
+ return m ? Number(m[1]) * 60 + Number(m[2]) : 0;
13
+ }
14
+ function dayKey(at) {
15
+ const d = new Date(at);
16
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
17
+ }
18
+ function scheduleOn(w, at) {
19
+ const day = new Date(at).getDay();
20
+ const own = w.byDay?.[String(day)] ?? {};
21
+ const start = own.start || w.start;
22
+ const end = own.end || w.end;
23
+ const holiday = (w.holidays ?? []).includes(dayKey(at));
24
+ const working = w.days.includes(day) && !holiday;
25
+ return { working, holiday, start, end, startMin: minutesOf(start), endMin: minutesOf(end), hours: working ? own.hours ?? w.hours ?? 0 : 0 };
26
+ }
27
+ function isWorkingAt(w, at) {
28
+ const s = scheduleOn(w, at);
29
+ if (!s.working) return false;
30
+ const d = new Date(at);
31
+ const mins = d.getHours() * 60 + d.getMinutes();
32
+ return mins >= s.startMin && mins < s.endMin;
33
+ }
34
+
35
+ // packages/core/src/layout/grid.ts
36
+ function toPx(r, grid, width, height) {
37
+ const innerW = width - 2 * grid.padding;
38
+ const innerH = height - 2 * grid.padding;
39
+ const colW = (innerW + grid.gap) / grid.cols;
40
+ const rowH = (innerH + grid.gap) / grid.rows;
41
+ const x0 = Math.round(grid.padding + r.x * colW);
42
+ const y0 = Math.round(grid.padding + r.y * rowH);
43
+ const x1 = Math.round(grid.padding + (r.x + r.w) * colW - grid.gap);
44
+ const y1 = Math.round(grid.padding + (r.y + r.h) * rowH - grid.gap);
45
+ return { x: x0, y: y0, w: Math.max(1, x1 - x0), h: Math.max(1, y1 - y0) };
46
+ }
47
+
48
+ // packages/core/src/config/model.ts
49
+ var CONFIG_VERSION = 1;
50
+ var ZOOM = { min: 0.5, max: 2, step: 0.1 };
51
+ function zoomOf(inst) {
52
+ const z = inst.zoom;
53
+ if (typeof z !== "number" || !Number.isFinite(z)) return 1;
54
+ return Math.round(Math.min(ZOOM.max, Math.max(ZOOM.min, z)) * 100) / 100;
55
+ }
56
+ var READING_CM = { near: 40, normal: 60, far: 90 };
57
+ var DEFAULT_CONFIG = {
58
+ version: CONFIG_VERSION,
59
+ locale: "auto",
60
+ timeFormat: "auto",
61
+ theme: "midnight",
62
+ workday: { ...DEFAULT_WORKDAY, days: [...DEFAULT_WORKDAY.days], holidays: [], byDay: {} },
63
+ sources: {},
64
+ plugins: { disabled: [] },
65
+ screens: [],
66
+ server: { host: "127.0.0.1", port: 7420 }
67
+ };
68
+ var PANEL_PRESETS = [
69
+ { id: "trofeo-916", name: "Trofeo Vision 9.16\u2033", width: 1920, height: 462, diagonalIn: 9.16, maker: "Thermalright", tested: true },
70
+ { id: "trofeo-113", name: "Trofeo Vision 11.3\u2033", width: 1920, height: 400, diagonalIn: 11.3, maker: "Thermalright" },
71
+ // The id of the size it was before it had its model's name: kept.
72
+ { id: "wide-1280x480", name: "Trofeo Vision 6.86\u2033", width: 1280, height: 480, diagonalIn: 6.86, maker: "Thermalright" },
73
+ { id: "fan-bracket-vision-1", name: "Fan Bracket Vision-1", width: 854, height: 480, diagonalIn: 5.66, maker: "Thermalright" },
74
+ { id: "gpu-bracket-458", name: "GPU Bracket LCD 4.58\u2033", width: 320, height: 960, diagonalIn: 4.58, maker: "Thermalright" },
75
+ { id: "fan-frame-vision-1", name: "Fan Frame Vision-1 3.69\u2033", width: 640, height: 172, diagonalIn: 3.69, maker: "Thermalright" },
76
+ { id: "wide-1920x480", name: "Wide bar 1920\xD7480", width: 1920, height: 480, diagonalIn: 9.16 },
77
+ { id: "wide-1600x720", name: "1600\xD7720", width: 1600, height: 720, diagonalIn: 8.8 },
78
+ { id: "square-480", name: "Square 480\xD7480", width: 480, height: 480, diagonalIn: 3.4 },
79
+ { id: "square-320", name: "Square 320\xD7320", width: 320, height: 320, diagonalIn: 2.1 },
80
+ { id: "small-320x240", name: "Small 320\xD7240", width: 320, height: 240, diagonalIn: 2.4 },
81
+ { id: "round-480", name: "Round 480\xD7480 (AIO)", width: 480, height: 480, diagonalIn: 2.8, shape: "round" }
82
+ ];
83
+ function mmPerPx(s) {
84
+ const known = PANEL_PRESETS.find((p) => p.width === s.width && p.height === s.height || p.width === s.height && p.height === s.width);
85
+ const diag = s.diagonalIn ?? known?.diagonalIn;
86
+ if (!diag) return 25.4 / 200;
87
+ return diag * 25.4 / Math.hypot(s.width, s.height);
88
+ }
89
+ function legibleCjkPx(s) {
90
+ const mm = READING_CM[s.readingDistance ?? "normal"] * 10 * Math.tan(10 / 60 * Math.PI / 180);
91
+ return Math.round(mm / 0.88 / mmPerPx(s));
92
+ }
93
+ function isWorking(workday, now) {
94
+ return isWorkingAt(workday, now);
95
+ }
96
+ function whenMatches(when, working) {
97
+ return !when || when === "always" || when === "work" === working;
98
+ }
99
+ function* widgetsOf(screen) {
100
+ for (const page of screen.pages) for (const tile of page.tiles) for (const widget of tile.widgets) yield { page, tile, widget };
101
+ }
102
+
103
+ // packages/core/src/paths.ts
104
+ import { existsSync } from "node:fs";
105
+ import { homedir as homedir2, platform } from "node:os";
106
+
107
+ // packages/sdk/src/plugin.ts
108
+ var PAD_KEYS = ["up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select"];
109
+ var SDK_VERSION = "0.2.8";
110
+ function defineWidget(w) {
111
+ return w;
112
+ }
113
+ function definePlugin(p) {
114
+ return p;
115
+ }
116
+
117
+ // packages/sdk/src/i18n.ts
118
+ var ALIASES = { iw: "he", in: "id", ji: "yi", tl: "fil", no: "nb", cmn: "zh" };
119
+ var READS = { yue: "zh", nn: "nb" };
120
+ function parseLocale(tag) {
121
+ if (!tag) return null;
122
+ let t2 = tag.trim();
123
+ const latin2 = /@latin\b/i.test(t2);
124
+ t2 = t2.replace(/[.@].*$/, "").replace(/_/g, "-");
125
+ if (!t2 || t2 === "C" || t2 === "POSIX") return null;
126
+ try {
127
+ let l = new Intl.Locale(Intl.getCanonicalLocales(t2)[0]);
128
+ const alias = ALIASES[l.language];
129
+ if (alias) l = new Intl.Locale(alias, { ...l.script ? { script: l.script } : {}, ...l.region ? { region: l.region } : {} });
130
+ if (latin2 && !l.script) l = new Intl.Locale(l.language, { script: "Latn", ...l.region ? { region: l.region } : {} });
131
+ return l;
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+ var LATAM = /* @__PURE__ */ new Set(["419", "AR", "BO", "CL", "CO", "CR", "CU", "DO", "EC", "GT", "HN", "MX", "NI", "PA", "PE", "PR", "PY", "SV", "US", "UY", "VE"]);
137
+ var PT_PT = /* @__PURE__ */ new Set(["PT", "AO", "MZ", "CV", "GW", "ST", "TL", "MO", "GQ", "LU", "CH"]);
138
+ function pickLocale(available2, locale) {
139
+ if (!locale || !available2.length) return void 0;
140
+ const exact = available2.find((k) => k.toLowerCase() === locale.replace(/_/g, "-").toLowerCase());
141
+ if (exact) return exact;
142
+ const want = parseLocale(locale);
143
+ if (!want) return void 0;
144
+ const w = want.maximize();
145
+ const lang = READS[w.language] ?? w.language;
146
+ const fits = available2.map((k) => ({ k, l: parseLocale(k) })).filter((c) => !!c.l).map((c) => ({ ...c, m: c.l.maximize() })).filter((c) => (READS[c.m.language] ?? c.m.language) === lang && c.m.script === w.script);
147
+ if (!fits.length) return void 0;
148
+ const same = (a, b) => a.baseName === b.baseName;
149
+ const byTag = fits.find((c) => same(c.l, want));
150
+ if (byTag) return byTag.k;
151
+ if (w.region) {
152
+ const byRegion = fits.find((c) => c.m.region === w.region && c.l.region);
153
+ if (byRegion) return byRegion.k;
154
+ const usual = (r) => lang === "es" && LATAM.has(w.region) ? ["419", "MX"].includes(r) : lang === "pt" && PT_PT.has(w.region) ? r === "PT" : false;
155
+ const variant = fits.find((c) => c.l.region && usual(c.l.region));
156
+ if (variant) return variant.k;
157
+ }
158
+ const plain = [...fits].sort((a, b) => a.l.baseName.split("-").length - b.l.baseName.split("-").length);
159
+ return plain[0].k;
160
+ }
161
+ function plural(n, forms, locale = "en") {
162
+ const key = pickLocale(Object.keys(forms), locale) ?? (forms.en ? "en" : Object.keys(forms)[0]);
163
+ const f = forms[key];
164
+ let rule = "other";
165
+ try {
166
+ rule = new Intl.PluralRules(key).select(n);
167
+ } catch {
168
+ }
169
+ const text2 = f[rule] ?? f.other;
170
+ let num = String(n);
171
+ try {
172
+ num = new Intl.NumberFormat(key).format(n);
173
+ } catch {
174
+ }
175
+ return text2.replaceAll("{n}", num);
176
+ }
177
+ function localize(text2, locale = "en") {
178
+ if (text2 === void 0) return "";
179
+ if (typeof text2 === "string") return text2;
180
+ const key = pickLocale(Object.keys(text2), locale);
181
+ return (key ? text2[key] : void 0) ?? text2.en ?? Object.values(text2).find((v) => typeof v === "string") ?? "";
182
+ }
183
+ function hanScript(locale) {
184
+ const l = parseLocale(locale || "en");
185
+ if (!l) return null;
186
+ const full = l.maximize();
187
+ switch (READS[full.language] ?? full.language) {
188
+ case "zh":
189
+ if (full.script === "Hant") return full.region === "HK" || full.region === "MO" ? "Hant-HK" : "Hant";
190
+ return "Hans";
191
+ case "ja":
192
+ return "Jpan";
193
+ case "ko":
194
+ return "Kore";
195
+ default:
196
+ return null;
197
+ }
198
+ }
199
+ function errorMessage(err, locale = "en") {
200
+ if (err instanceof Error && "text" in err && err.text !== void 0) return localize(err.text, locale);
201
+ return err instanceof Error ? err.message : String(err);
202
+ }
203
+
204
+ // packages/sdk/src/schema.ts
205
+ var t = {
206
+ string: (o = {}) => ({ kind: "string", default: "", ...o }),
207
+ number: (o = {}) => ({ kind: "number", default: o.min ?? 0, ...o }),
208
+ integer: (o = {}) => ({ kind: "number", integer: true, default: o.min ?? 0, ...o }),
209
+ boolean: (o = {}) => ({ kind: "boolean", default: false, ...o }),
210
+ enum: (values, o = {}) => ({ kind: "enum", values, default: values[0], ...o }),
211
+ color: (o = {}) => ({ kind: "color", default: "#ffffff", ...o }),
212
+ list: (item, o = {}) => ({ kind: "list", item, default: [], ...o }),
213
+ object: (props, o = {}) => ({ kind: "object", props, ...o, default: Object.fromEntries(Object.entries(props).map(([k, f]) => [k, clone(f.default)])) }),
214
+ map: (o = {}) => ({ kind: "map", default: {}, ...o }),
215
+ /** Duration in milliseconds, edited in seconds or minutes by the editor. */
216
+ duration: (o = {}) => ({ kind: "number", integer: true, unit: "ms", min: 0, default: 6e4, ...o }),
217
+ /**
218
+ * Which items to show, as patterns for `matchFilter`: `["web", "acme/*",
219
+ * "!*-old"]`. Empty = all. Name it after what it filters (`projects`,
220
+ * `repos`, `calendars`, `people`) and give it a `label`; the `help`
221
+ * explaining the patterns comes with it.
222
+ */
223
+ filter: ({ choices, ...o } = {}) => ({
224
+ kind: "list",
225
+ item: { kind: "string", default: "", placeholder: "name, group/*, !old-*", ...choices ? { choices } : {} },
226
+ default: [],
227
+ filter: true,
228
+ help: FILTER_HELP,
229
+ ...o
230
+ })
231
+ };
232
+ var FILTER_HELP = {
233
+ en: "Empty: all. Names or patterns, comma-separated: * matches anything, a leading ! leaves out (web, acme/*, !*-old).",
234
+ es: "Vac\xEDo: todos. Nombres o patrones separados por comas: * vale por cualquier cosa y un ! delante excluye (web, acme/*, !*-old).",
235
+ de: "Leer: alle. Namen oder Muster, durch Kommas getrennt: * steht f\xFCr alles, ein ! davor schlie\xDFt aus (web, acme/*, !*-old).",
236
+ "zh-Hant": "\u7559\u7A7A\uFF1A\u5168\u90E8\u3002\u586B\u5165\u540D\u7A31\u6216\u6A21\u5F0F\uFF0C\u4EE5\u9017\u865F\u5206\u9694\uFF1A* \u4EE3\u8868\u4EFB\u610F\u5B57\u5143\uFF0C\u958B\u982D\u52A0 ! \u5247\u6392\u9664\uFF08web, acme/*, !*-old\uFF09\u3002",
237
+ "zh-Hans": "\u7559\u7A7A\uFF1A\u5168\u90E8\u3002\u586B\u5199\u540D\u79F0\u6216\u6A21\u5F0F\uFF0C\u7528\u9017\u53F7\u5206\u9694\uFF1A* \u5339\u914D\u4EFB\u610F\u5185\u5BB9\uFF0C\u5F00\u5934\u52A0 ! \u8868\u793A\u6392\u9664\uFF08web, acme/*, !*-old\uFF09\u3002"
238
+ };
239
+ function clone(v) {
240
+ return v === void 0 ? v : JSON.parse(JSON.stringify(v));
241
+ }
242
+ function validate(f, value, path = "") {
243
+ const issues = [];
244
+ const out = coerce(f, value, path, issues);
245
+ return { value: out, issues };
246
+ }
247
+ function coerce(f, v, path, issues) {
248
+ const bad = (msg) => {
249
+ issues.push({ path: path || "(root)", message: msg });
250
+ return clone(f.default);
251
+ };
252
+ if (v === void 0 || v === null) return clone(f.default);
253
+ switch (f.kind) {
254
+ case "string":
255
+ if (typeof v === "number") return String(v);
256
+ if (typeof v !== "string") return bad("expected text");
257
+ return f.maxLength && v.length > f.maxLength ? v.slice(0, f.maxLength) : v;
258
+ case "color":
259
+ if (typeof v !== "string") return bad("expected a colour");
260
+ return v;
261
+ case "number": {
262
+ const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v;
263
+ if (typeof n !== "number" || !Number.isFinite(n)) return bad("expected a number");
264
+ let x = f.integer ? Math.round(n) : n;
265
+ if (f.min !== void 0 && x < f.min) x = f.min;
266
+ if (f.max !== void 0 && x > f.max) x = f.max;
267
+ return x;
268
+ }
269
+ case "boolean":
270
+ if (typeof v === "boolean") return v;
271
+ if (v === "true" || v === "false") return v === "true";
272
+ return bad("expected true/false");
273
+ case "enum":
274
+ if (typeof v === "string" && f.values.includes(v)) return v;
275
+ return bad(`expected one of ${f.values.join(", ")}`);
276
+ case "list": {
277
+ if (!Array.isArray(v)) return bad("expected a list");
278
+ const items = v.map((item, i) => coerce(f.item, item, path ? `${path}.${i}` : String(i), issues));
279
+ return f.max !== void 0 ? items.slice(0, f.max) : items;
280
+ }
281
+ case "map": {
282
+ if (typeof v !== "object" || Array.isArray(v)) return bad("expected key/value pairs");
283
+ return Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === "string" || typeof x === "number").map(([k, x]) => [k, String(x)]));
284
+ }
285
+ case "object": {
286
+ if (typeof v !== "object" || Array.isArray(v)) return bad("expected an object");
287
+ const src = v;
288
+ const out = { ...src };
289
+ for (const [k, sub] of Object.entries(f.props)) out[k] = coerce(sub, src[k], path ? `${path}.${k}` : k, issues);
290
+ return out;
291
+ }
292
+ }
293
+ }
294
+ var SECRET_NOTE = 'Secret: leave it empty (or a placeholder such as "<token>"). Kiosko keeps the value it already has, or asks for it in the editor.';
295
+ function toJsonSchema(f) {
296
+ const ui = { label: f.label, help: f.help, advanced: f.advanced };
297
+ const secret = f.kind === "string" && !!f.secret;
298
+ const help = f.help === void 0 ? void 0 : localize(f.help, "en");
299
+ const description = secret ? [help, SECRET_NOTE].filter(Boolean).join(" ") : help;
300
+ const base2 = {
301
+ ...f.label === void 0 ? {} : { title: localize(f.label, "en") },
302
+ ...description ? { description } : {},
303
+ default: f.default,
304
+ "x-ui": ui,
305
+ ...secret ? { "x-secret": true } : {},
306
+ ...f.risk === void 0 ? {} : { "x-risk": typeof f.risk === "string" ? f.risk : [...f.risk] }
307
+ };
308
+ switch (f.kind) {
309
+ case "string":
310
+ return { ...base2, 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 } };
311
+ case "color":
312
+ return { ...base2, type: "string", "x-ui": { ...ui, widget: "color" } };
313
+ case "number":
314
+ return { ...base2, type: f.integer ? "integer" : "number", minimum: f.min, maximum: f.max, "x-ui": { ...ui, unit: f.unit, step: f.step, slider: f.slider } };
315
+ case "boolean":
316
+ return { ...base2, type: "boolean" };
317
+ case "enum":
318
+ return { ...base2, type: "string", enum: [...f.values], "x-ui": { ...ui, labels: f.labels } };
319
+ case "list":
320
+ return { ...base2, type: "array", items: toJsonSchema(f.item), maxItems: f.max, ...f.filter ? { "x-ui": { ...ui, widget: "filter", choices: f.item.kind === "string" ? f.item.choices : void 0 }, "x-filter": true } : {} };
321
+ case "map":
322
+ return { ...base2, type: "object", additionalProperties: { type: "string" } };
323
+ case "object":
324
+ return { ...base2, type: "object", properties: Object.fromEntries(Object.entries(f.props).map(([k, sub]) => [k, toJsonSchema(sub)])) };
325
+ }
326
+ }
327
+
328
+ // packages/sdk/src/theme.ts
329
+ var FONT_FAMILIES = {
330
+ sans: "KioskoSans",
331
+ sansBold: "KioskoSansBold",
332
+ mono: "KioskoMono",
333
+ monoBold: "KioskoMonoBold"
334
+ };
335
+ var base = { fonts: FONT_FAMILIES, radius: 12, titleSize: 30 };
336
+ var THEMES = [
337
+ {
338
+ id: "midnight",
339
+ name: "Midnight",
340
+ ...base,
341
+ colors: { bg: "#05080D", surface: "#0D131A", surfaceEdge: "#1C2631", ink: "#D3DFEA", inkDim: "#627180", inkFaint: "#384450", accent: "#4DA3FF", alert: "#F5453D", warn: "#FFB020", info: "#4DA3FF", ok: "#3FCB7E" }
342
+ },
343
+ {
344
+ id: "graphite",
345
+ name: "Graphite",
346
+ ...base,
347
+ radius: 6,
348
+ colors: { bg: "#111214", surface: "#1A1C1F", surfaceEdge: "#2A2D31", ink: "#ECEDEE", inkDim: "#8B9096", inkFaint: "#4A4F55", accent: "#E8E8E8", alert: "#FF5F57", warn: "#FEBC2E", info: "#64B5F6", ok: "#28C840" }
349
+ },
350
+ {
351
+ id: "aurora",
352
+ name: "Aurora",
353
+ ...base,
354
+ radius: 16,
355
+ colors: { bg: "#0B0A1A", surface: "#15132B", surfaceEdge: "#2A2550", ink: "#EDE9FF", inkDim: "#8D86B8", inkFaint: "#4A4475", accent: "#9F7AEA", alert: "#FF4D8D", warn: "#FFC857", info: "#4CC9F0", ok: "#43E5A0" }
356
+ },
357
+ {
358
+ id: "phosphor",
359
+ name: "Phosphor",
360
+ ...base,
361
+ radius: 2,
362
+ fonts: { ...FONT_FAMILIES, sans: FONT_FAMILIES.mono, sansBold: FONT_FAMILIES.monoBold },
363
+ colors: { bg: "#020602", surface: "#061006", surfaceEdge: "#0F2A0F", ink: "#7CFF7C", inkDim: "#2F9E3A", inkFaint: "#165C1E", accent: "#7CFF7C", alert: "#FF5A3C", warn: "#FFD23C", info: "#5CE1E6", ok: "#7CFF7C" }
364
+ },
365
+ {
366
+ id: "paper",
367
+ name: "Paper",
368
+ ...base,
369
+ radius: 10,
370
+ colors: { bg: "#F2EFE8", surface: "#FFFFFF", surfaceEdge: "#DDD8CC", ink: "#1F2328", inkDim: "#6B6F76", inkFaint: "#B4B0A6", accent: "#2F6FEB", alert: "#D92D20", warn: "#C27803", info: "#2F6FEB", ok: "#1E8E3E" }
371
+ }
372
+ ];
373
+ var DEFAULT_THEME = THEMES[0];
374
+ function themeById(id) {
375
+ return THEMES.find((t2) => t2.id === id) ?? DEFAULT_THEME;
376
+ }
377
+
378
+ // packages/sdk/src/languages.ts
379
+ var MAINLAND_CHINA = {
380
+ without: [],
381
+ first: ["llm", "gpu", "usage"],
382
+ instead: { "usage/rail": "usage/balance", "usage/blocks": "usage/agents" }
383
+ };
384
+ var LANGUAGES = [
385
+ { id: "en", name: "English", panel: "en", ogLocale: "en_US", hreflang: ["en", "x-default"], dir: "ltr" },
386
+ { id: "es", name: "Espa\xF1ol", panel: "es", ogLocale: "es_ES", hreflang: ["es"], dir: "ltr" },
387
+ { id: "de", name: "Deutsch", panel: "de", ogLocale: "de_DE", hreflang: ["de"], dir: "ltr" },
388
+ { id: "zh-Hant", name: "\u7E41\u9AD4\u4E2D\u6587", panel: "zh-TW", ogLocale: "zh_TW", hreflang: ["zh-Hant", "zh-TW", "zh-HK"], dir: "ltr" },
389
+ { id: "zh-Hans", name: "\u7B80\u4F53\u4E2D\u6587", panel: "zh-CN", ogLocale: "zh_CN", hreflang: ["zh-Hans", "zh-CN"], dir: "ltr", plugins: MAINLAND_CHINA }
390
+ ];
391
+ var LANGUAGE_IDS = LANGUAGES.map((l) => l.id);
392
+
393
+ // packages/sdk/src/format.ts
394
+ var latin = (wk, yr) => ({
395
+ s: (n) => `${n} s`,
396
+ min: (n) => `${n} min`,
397
+ h: (n) => `${n} h`,
398
+ d: (n) => `${n} d`,
399
+ wk: (n) => `${n} ${wk}`,
400
+ yr: (n) => `${n} ${yr(n)}`,
401
+ hm: (h, m) => `${h} h ${pad2(m)}`,
402
+ dh: (d, h) => `${d} d ${h} h`
403
+ });
404
+ var german = {
405
+ s: (n) => `${n} s`,
406
+ min: (n) => `${n} Min.`,
407
+ h: (n) => `${n} Std.`,
408
+ d: (n) => `${n} T.`,
409
+ wk: (n) => `${n} Wo.`,
410
+ yr: (n) => `${n} J.`,
411
+ hm: (h, m) => `${h}:${pad2(m)} h`,
412
+ dh: (d, h) => `${d} T. ${h} Std.`
413
+ };
414
+ var chinese = (u) => ({
415
+ s: (n) => `${n} \u79D2`,
416
+ min: (n) => `${n} ${u.min}`,
417
+ h: (n) => `${n} ${u.h}`,
418
+ d: (n) => `${n} \u5929`,
419
+ wk: (n) => `${n} ${u.wk}`,
420
+ yr: (n) => `${n} \u5E74`,
421
+ // No leading zero in Chinese: 1 小時 5 分.
422
+ hm: (h, m) => `${h} ${u.h} ${m} \u5206`,
423
+ dh: (d, h) => `${d} \u5929 ${h} ${u.h}`
424
+ });
425
+ var WORDS = {
426
+ en: { now: "now", justNow: "just now", ago: (v) => `${v} ago`, am: "AM", pm: "PM", ...latin("wk", () => "yr") },
427
+ es: { now: "ahora", justNow: "ahora mismo", ago: (v) => `hace ${v}`, am: "a. m.", pm: "p. m.", ...latin("sem", (n) => n === 1 ? "a\xF1o" : "a\xF1os") },
428
+ de: { now: "jetzt", justNow: "gerade eben", ago: (v) => `vor ${v}`, am: "AM", pm: "PM", ...german },
429
+ "zh-Hant": { now: "\u73FE\u5728", justNow: "\u525B\u525B", ago: (v) => `${v}\u524D`, am: "\u4E0A\u5348", pm: "\u4E0B\u5348", ampmFirst: true, ...chinese({ min: "\u5206\u9418", h: "\u5C0F\u6642", wk: "\u9031" }) },
430
+ "zh-Hans": { now: "\u73B0\u5728", justNow: "\u521A\u521A", ago: (v) => `${v}\u524D`, am: "\u4E0A\u5348", pm: "\u4E0B\u5348", ampmFirst: true, ...chinese({ min: "\u5206\u949F", h: "\u5C0F\u65F6", wk: "\u5468" }) }
431
+ };
432
+ var FORMAT_LANGUAGES = Object.keys(WORDS);
433
+ var LANGS = Object.keys(WORDS);
434
+ var wordsFor = (locale) => WORDS[pickLocale(LANGS, locale) ?? "en"] ?? WORDS.en;
435
+ var pad2 = (n) => String(n).padStart(2, "0");
436
+ var cycles = /* @__PURE__ */ new Map();
437
+ function usesHour12(locale, timeFormat = "auto") {
438
+ if (timeFormat !== "auto") return timeFormat === "12h";
439
+ let h12 = cycles.get(locale);
440
+ if (h12 === void 0) {
441
+ try {
442
+ const cycle = new Intl.DateTimeFormat(locale, { hour: "numeric" }).resolvedOptions().hourCycle;
443
+ h12 = cycle === "h11" || cycle === "h12";
444
+ } catch {
445
+ h12 = false;
446
+ }
447
+ cycles.set(locale, h12);
448
+ }
449
+ return h12;
450
+ }
451
+ function toMs(at) {
452
+ if (typeof at === "number") return at;
453
+ if (typeof at === "string") return Date.parse(at);
454
+ return at.getTime();
455
+ }
456
+ function createFormatters(o) {
457
+ const w = wordsFor(o.locale);
458
+ const hour12 = usesHour12(o.locale, o.timeFormat);
459
+ const fmt = {
460
+ hour12,
461
+ time(at, opts = {}) {
462
+ const d = new Date(toMs(at));
463
+ const h = d.getHours();
464
+ const rest = `:${pad2(d.getMinutes())}${opts.seconds ? `:${pad2(d.getSeconds())}` : ""}`;
465
+ if (!hour12) return `${pad2(h)}${rest}`;
466
+ const base2 = `${h % 12 || 12}${rest}`;
467
+ if (opts.ampm === false) return base2;
468
+ const mark = h < 12 ? w.am : w.pm;
469
+ return w.ampmFirst ? `${mark} ${base2}` : `${base2} ${mark}`;
470
+ },
471
+ range(from, to, opts = {}) {
472
+ const a = new Date(toMs(from));
473
+ const b = new Date(toMs(to));
474
+ if (!hour12 || a.getHours() < 12 !== b.getHours() < 12) return `${fmt.time(a, opts)}\u2013${fmt.time(b, opts)}`;
475
+ return w.ampmFirst ? `${fmt.time(a, opts)}\u2013${fmt.time(b, { ...opts, ampm: false })}` : `${fmt.time(a, { ...opts, ampm: false })}\u2013${fmt.time(b, opts)}`;
476
+ },
477
+ ago(at, opts = {}) {
478
+ const suffix = opts.suffix !== false;
479
+ const ms = (opts.now ?? o.now) - toMs(at);
480
+ const min = Math.floor(ms / 6e4);
481
+ if (!Number.isFinite(min) || min < 1) return suffix ? w.justNow : w.now;
482
+ const h = Math.floor(min / 60);
483
+ const d = Math.floor(h / 24);
484
+ 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)];
485
+ return suffix ? w.ago(v, n) : v;
486
+ },
487
+ duration(ms, opts = {}) {
488
+ const round2 = opts.round === "up" ? Math.ceil : opts.round === "nearest" ? Math.round : Math.floor;
489
+ const safe2 = Number.isFinite(ms) ? Math.max(0, ms) : 0;
490
+ if (opts.seconds && safe2 < 6e4) return w.s(round2(safe2 / 1e3));
491
+ const min = round2(safe2 / 6e4);
492
+ if (min < 60) return w.min(min);
493
+ const h = Math.floor(min / 60);
494
+ if (h < 24) return opts.compact && min % 60 === 0 ? w.h(h) : w.hm(h, min % 60);
495
+ return opts.compact && h % 24 === 0 ? w.d(h / 24) : w.dh(Math.floor(h / 24), h % 24);
496
+ }
497
+ };
498
+ return fmt;
499
+ }
500
+
501
+ // packages/sdk/src/list.ts
502
+ var LAYOUT_LABELS = {
503
+ auto: { en: "Automatic", es: "Autom\xE1tico", de: "Automatisch", "zh-Hant": "\u81EA\u52D5", "zh-Hans": "\u81EA\u52A8" },
504
+ "one-line": { en: "One line", es: "Una l\xEDnea", de: "Eine Zeile", "zh-Hant": "\u55AE\u884C", "zh-Hans": "\u5355\u884C" },
505
+ detailed: { en: "Detailed", es: "Detallado", de: "Ausf\xFChrlich", "zh-Hant": "\u8A73\u7D30", "zh-Hans": "\u8BE6\u7EC6" }
506
+ };
507
+ var rowsField = (def) => t.integer({
508
+ default: def,
509
+ min: 0,
510
+ max: 30,
511
+ label: { en: "Rows", es: "Filas", de: "Zeilen", "zh-Hant": "\u5217\u6578", "zh-Hans": "\u884C\u6570" },
512
+ help: {
513
+ en: '0 = as many as fit. A number shows that many, in rows of a readable size (fewer when the tile is too small for them); the rest are counted in "+N more".',
514
+ es: "0 = las que quepan. Con un n\xFAmero se ven esas, en filas de un tama\xF1o legible (menos si la tesela no da para ellas); el resto se cuenta en \xAB+N m\xE1s\xBB.",
515
+ de: "0 = so viele, wie passen. Eine Zahl zeigt so viele, in Zeilen lesbarer Gr\xF6\xDFe (weniger, wenn die Kachel daf\xFCr zu klein ist); der Rest wird als \u201E+N weitere\u201C gez\xE4hlt.",
516
+ "zh-Hant": "0 = \u76E1\u91CF\u653E\u6EFF\u3002\u586B\u6578\u5B57\u5247\u986F\u793A\u8A72\u6578\u91CF\uFF0C\u4E26\u4EE5\u6613\u8B80\u7684\u5927\u5C0F\u6392\u5217\uFF08\u65B9\u683C\u592A\u5C0F\u6642\u6703\u6E1B\u5C11\uFF09\uFF1B\u5176\u9918\u7684\u8A08\u5165\u300C\u9084\u6709 N \u500B\u300D\u3002",
517
+ "zh-Hans": "0 = \u5C3D\u91CF\u653E\u6EE1\u3002\u586B\u6570\u5B57\u5219\u663E\u793A\u8BE5\u6570\u91CF\uFF0C\u5E76\u4EE5\u6613\u8BFB\u7684\u5927\u5C0F\u6392\u5217\uFF08\u683C\u5B50\u592A\u5C0F\u65F6\u4F1A\u51CF\u5C11\uFF09\uFF1B\u5176\u4F59\u7684\u8BA1\u5165\u201C\u8FD8\u6709 N \u4E2A\u201D\u3002"
518
+ }
519
+ });
520
+ function listOptions(o = {}) {
521
+ const rows = rowsField(o.rows ?? 0);
522
+ if (!o.layouts || o.layouts.length < 2) return { rows };
523
+ const values = ["auto", ...o.layouts];
524
+ return {
525
+ rows,
526
+ layout: t.enum(values, {
527
+ default: o.layout ?? "auto",
528
+ label: { en: "Row layout", es: "Formato de fila", de: "Zeilenlayout", "zh-Hant": "\u5217\u7248\u9762", "zh-Hans": "\u884C\u5E03\u5C40" },
529
+ labels: Object.fromEntries(values.map((v) => [v, LAYOUT_LABELS[v]])),
530
+ help: { en: "Automatic: the widget picks by the tile's shape.", es: "Autom\xE1tico: el widget elige seg\xFAn la forma de la tesela.", de: "Automatisch: Das Widget w\xE4hlt nach der Form der Kachel.", "zh-Hant": "\u81EA\u52D5\uFF1A\u5C0F\u5DE5\u5177\u4F9D\u65B9\u683C\u5F62\u72C0\u9078\u64C7\u3002", "zh-Hans": "\u81EA\u52A8\uFF1A\u5C0F\u7EC4\u4EF6\u6839\u636E\u683C\u5B50\u5F62\u72B6\u9009\u62E9\u3002" }
531
+ })
532
+ };
533
+ }
534
+ var TOLERANCE = 0.1;
535
+ var MIN_MORE_H = 12;
536
+ var clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
537
+ function moreHeight(rowH) {
538
+ return Math.min(clamp(Math.round(rowH * 0.6), 18, 28), rowH);
539
+ }
540
+ function listLayout(box, count, options, spec) {
541
+ const declared = Object.keys(spec.sizes);
542
+ const n = Math.max(0, Math.floor(count));
543
+ const fixed = Math.max(0, Math.round(options.rows ?? 0));
544
+ const want = options.layout;
545
+ const layout = want && want !== "auto" && declared.includes(want) ? want : spec.auto?.(box, fixed > 0 ? Math.min(fixed, n) : n) ?? declared[0];
546
+ const size = spec.sizes[layout] ?? spec.sizes[declared[0]];
547
+ const min = Math.max(1, size.min);
548
+ const max = Math.max(min, size.max);
549
+ const h = Math.max(0, box.h);
550
+ const text2 = (rowH2) => {
551
+ const textSize = Math.round(rowH2 * (layout === "detailed" ? 0.42 : 0.6));
552
+ return { textSize, detailSize: Math.round(layout === "detailed" ? rowH2 * 0.3 : textSize * 0.8) };
553
+ };
554
+ if (h <= 0) return { layout, rowH: 0, rows: [], shown: 0, hidden: n, more: null, ...text2(0) };
555
+ const target = fixed > 0 ? Math.min(fixed, n) : n;
556
+ const divisor = fixed > 0 ? fixed : Math.max(n, spec.minRows ?? 1, 1);
557
+ const fits = (space, rowH2) => Math.floor(space / rowH2 + TOLERANCE);
558
+ let rowH = clamp(h / divisor, min, max);
559
+ let shown = Math.min(target, fits(h, rowH));
560
+ let more = null;
561
+ if (shown < n) {
562
+ let moreH = Math.min(spec.moreH ?? moreHeight(rowH), rowH);
563
+ rowH = clamp((h - moreH) / divisor, min, max);
564
+ shown = Math.min(target, fits(h - moreH, rowH));
565
+ if (shown < 1) {
566
+ shown = Math.min(1, n);
567
+ rowH = Math.min(h, min);
568
+ moreH = Math.min(moreH, h - rowH);
569
+ }
570
+ if (moreH >= MIN_MORE_H) more = { x: box.x, y: box.y + shown * rowH, w: box.w, h: moreH };
571
+ }
572
+ const rows = Array.from({ length: shown }, (_, i) => ({ x: box.x, y: box.y + i * rowH, w: box.w, h: rowH }));
573
+ return { layout, rowH, rows, shown, hidden: n - shown, more, ...text2(rowH) };
574
+ }
575
+ function moreLabel(n, tr) {
576
+ return tr({ en: `+${n} more`, es: `+${n} m\xE1s`, de: `+${n} weitere`, "zh-Hant": `\u9084\u6709 ${n} \u500B`, "zh-Hans": `\u8FD8\u6709 ${n} \u4E2A` });
577
+ }
578
+ function drawMore(g, ctx, plan, o = {}) {
579
+ const m = plan.more;
580
+ if (!m || plan.hidden <= 0) return;
581
+ const size = Math.max(8, Math.round(m.h * 0.62));
582
+ const indent = o.indent ?? 0;
583
+ const font = { size, family: ctx.theme.fonts.sans, color: ctx.theme.colors.inkDim };
584
+ const text2 = ctx.kit.truncate(g, moreLabel(plan.hidden, ctx.t), Math.max(1, m.w - indent), font);
585
+ const y = m.y + (m.h + size * 0.7) / 2;
586
+ if (o.align === "right") ctx.kit.drawTracked(g, text2, m.x + m.w, y, { ...font, align: "right" });
587
+ else ctx.kit.drawTracked(g, text2, m.x + indent, y, font);
588
+ }
589
+ function drawEmpty(g, ctx, message) {
590
+ const { box, kit, theme } = ctx;
591
+ const size = Math.max(10, Math.round(Math.min(32, box.h * 0.3)));
592
+ const font = { size, family: theme.fonts.sans, color: theme.colors.inkDim };
593
+ kit.drawTracked(g, kit.truncate(g, message, box.w, font), box.x, box.y + size * 1.1, font);
594
+ }
595
+
596
+ // packages/sdk/src/context.ts
597
+ function createBaseContext(o) {
598
+ const locale = o.locale ?? "en";
599
+ return {
600
+ now: o.now,
601
+ locale,
602
+ t: (text2) => localize(text2, locale),
603
+ plural: (n, forms) => plural(n, forms, locale),
604
+ pickLanguage: (available2) => pickLocale(available2, locale) ?? (available2.includes("en") ? "en" : available2[0] ?? "en"),
605
+ fmt: createFormatters({ locale, timeFormat: o.timeFormat ?? "auto", now: o.now }),
606
+ log: o.log ?? (() => void 0),
607
+ dataDir: o.dataDir ?? "",
608
+ cacheDir: o.cacheDir ?? o.dataDir ?? "",
609
+ ...o.location ? { location: o.location } : {},
610
+ workday: o.workday ?? DEFAULT_WORKDAY
611
+ };
612
+ }
613
+
614
+ // packages/sdk/src/system.ts
615
+ import { homedir } from "node:os";
616
+ import { join, win32 } from "node:path";
617
+ function expandPath(p, o = {}) {
618
+ const env = o.env ?? process.env;
619
+ let v = p.replace(/\$(?:\{(\w+)\}|(\w+))/g, (whole, a, b) => env[a ?? b ?? ""] ?? whole);
620
+ if ((o.os ?? process.platform) === "win32") v = v.replace(/%([^%\r\n]+)%/g, (whole, name) => env[name] ?? whole);
621
+ const home = o.home ?? homedir();
622
+ if (v === "~") return home;
623
+ return v.startsWith("~/") || v.startsWith("~\\") ? join(home, v.slice(2)) : v;
624
+ }
625
+
626
+ // packages/sdk/src/semver.ts
627
+ function parseVersion(s) {
628
+ const m = /^\s*v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?\s*$/.exec(s);
629
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ?? ""] : null;
630
+ }
631
+ function compareVersions(a, b) {
632
+ const x = parseVersion(a), y = parseVersion(b);
633
+ if (!x || !y) return 0;
634
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
635
+ if (x[3] === y[3]) return 0;
636
+ if (!x[3]) return 1;
637
+ if (!y[3]) return -1;
638
+ return x[3] < y[3] ? -1 : 1;
639
+ }
640
+ function partial(s) {
641
+ const m = /^\s*v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?\s*$/.exec(s);
642
+ if (!m) return null;
643
+ const n = (p) => p === void 0 || /^[xX*]$/.test(p) ? void 0 : Number(p);
644
+ return [n(m[1]), n(m[2]), n(m[3]), m[4] ?? ""];
645
+ }
646
+ var ver = (a, b, c, pre = "") => `${a}.${b}.${c}${pre ? `-${pre}` : ""}`;
647
+ function comparators(set) {
648
+ const out = [];
649
+ const tokens = set.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, "$1").split(/\s+/).filter(Boolean);
650
+ if (!tokens.length) return [{ op: ">=", v: "0.0.0" }];
651
+ for (const tk of tokens) {
652
+ const m = /^(>=|<=|>|<|=|\^|~)?(.*)$/.exec(tk);
653
+ const op = m[1] ?? "";
654
+ const p = partial(m[2]);
655
+ if (!p) return null;
656
+ const [ma, mi, pa, pre] = p;
657
+ if (ma === void 0) {
658
+ out.push({ op: ">=", v: "0.0.0" });
659
+ continue;
660
+ }
661
+ if (op === "^") {
662
+ const lo = ver(ma, mi ?? 0, pa ?? 0, pre);
663
+ const hi = ma > 0 || mi === void 0 ? ver(ma + 1, 0, 0) : mi > 0 || pa === void 0 ? ver(0, mi + 1, 0) : ver(0, 0, pa + 1);
664
+ out.push({ op: ">=", v: lo }, { op: "<", v: `${hi}-0` });
665
+ } else if (op === "~") {
666
+ const lo = ver(ma, mi ?? 0, pa ?? 0, pre);
667
+ const hi = mi === void 0 ? ver(ma + 1, 0, 0) : ver(ma, mi + 1, 0);
668
+ out.push({ op: ">=", v: lo }, { op: "<", v: `${hi}-0` });
669
+ } else if (op === "" || op === "=") {
670
+ if (mi === void 0) out.push({ op: ">=", v: ver(ma, 0, 0) }, { op: "<", v: `${ver(ma + 1, 0, 0)}-0` });
671
+ else if (pa === void 0) out.push({ op: ">=", v: ver(ma, mi, 0) }, { op: "<", v: `${ver(ma, mi + 1, 0)}-0` });
672
+ else out.push({ op: "=", v: ver(ma, mi, pa, pre) });
673
+ } else {
674
+ if (pa === void 0 && (op === ">" || op === "<=")) {
675
+ const next = mi === void 0 ? ver(ma + 1, 0, 0) : ver(ma, mi + 1, 0);
676
+ out.push(op === ">" ? { op: ">=", v: next } : { op: "<", v: `${next}-0` });
677
+ } else out.push({ op, v: ver(ma, mi ?? 0, pa ?? 0, pre) });
678
+ }
679
+ }
680
+ return out;
681
+ }
682
+ function satisfies(version, range) {
683
+ const v = parseVersion(version);
684
+ if (!v) return false;
685
+ return range.split("||").some((set) => {
686
+ const cs = comparators(set);
687
+ if (!cs) return false;
688
+ const ok = cs.every(({ op, v: w }) => {
689
+ const c = compareVersions(version, w);
690
+ return op === ">=" ? c >= 0 : op === ">" ? c > 0 : op === "<=" ? c <= 0 : op === "<" ? c < 0 : c === 0;
691
+ });
692
+ if (!ok || !v[3]) return ok;
693
+ return cs.some(({ v: w }) => {
694
+ const x = parseVersion(w);
695
+ return !!x && !!x[3] && x[3] !== "0" && x[0] === v[0] && x[1] === v[1] && x[2] === v[2];
696
+ });
697
+ });
698
+ }
699
+
700
+ // packages/core/src/paths.ts
701
+ import { join as join2 } from "node:path";
702
+ function kioskoHome() {
703
+ if (process.env.KIOSKO_HOME) return process.env.KIOSKO_HOME;
704
+ const home = homedir2();
705
+ switch (platform()) {
706
+ case "darwin":
707
+ return join2(home, "Library", "Application Support", "Kiosko");
708
+ case "win32":
709
+ return join2(process.env.APPDATA ?? join2(home, "AppData", "Roaming"), "Kiosko");
710
+ default:
711
+ return join2(process.env.XDG_CONFIG_HOME ?? join2(home, ".config"), "kiosko");
712
+ }
713
+ }
714
+ var paths = {
715
+ get home() {
716
+ return kioskoHome();
717
+ },
718
+ get config() {
719
+ return join2(kioskoHome(), "config.json");
720
+ },
721
+ /** External plugins: one folder (or npm package) per plugin. */
722
+ get plugins() {
723
+ return join2(kioskoHome(), "plugins");
724
+ },
725
+ /**
726
+ * Per-plugin re-fetchable caches, in RAM: `$XDG_RUNTIME_DIR/kiosko-cache/<plugin>`
727
+ * (or `/dev/shm/kiosko-cache-<uid>/<plugin>`). Null where there is no tmpfs.
728
+ * On Windows there is none, but the cache belongs in the machine-local
729
+ * profile (`%LOCALAPPDATA%\\Kiosko\\cache`), not in the roaming one `data/` uses.
730
+ */
731
+ cache(plugin) {
732
+ if (platform() === "win32") return join2(process.env.LOCALAPPDATA ?? join2(homedir2(), "AppData", "Local"), "Kiosko", "cache", plugin.replace(/[^a-z0-9._-]/gi, "_"));
733
+ const base2 = process.env.XDG_RUNTIME_DIR && existsSync(process.env.XDG_RUNTIME_DIR) ? join2(process.env.XDG_RUNTIME_DIR, "kiosko-cache") : existsSync("/dev/shm") ? `/dev/shm/kiosko-cache-${process.getuid?.() ?? "u"}` : null;
734
+ return base2 && join2(base2, plugin.replace(/[^a-z0-9._-]/gi, "_"));
735
+ },
736
+ /** Per-plugin data that must persist: `data/<plugin>`. */
737
+ data(plugin) {
738
+ return join2(kioskoHome(), "data", plugin.replace(/[^a-z0-9._-]/gi, "_"));
739
+ }
740
+ };
741
+
742
+ // packages/core/src/config/sources.ts
743
+ var DEFAULT_SOURCE_MS = 3e4;
744
+ var DEFAULT_MIN_SOURCE_MS = 5e3;
745
+ var DEFAULT_TIMEOUT_MS = 2 * 6e4;
746
+ var MAX_INTERVAL_MS = 24 * 36e5;
747
+ var MIN_TIMEOUT_MS = 1e3;
748
+ var MAX_TIMEOUT_MS = 10 * 6e4;
749
+ var canRunInBackground = (def) => def.background === true && typeof def.alerts === "function" && !("background" in (def.options?.props ?? {}));
750
+ function human(ms) {
751
+ if (ms % 36e5 === 0) return `${ms / 36e5} h`;
752
+ if (ms % 6e4 === 0) return `${ms / 6e4} min`;
753
+ return `${+(ms / 1e3).toFixed(1)} s`;
754
+ }
755
+ function sourceTiming(def) {
756
+ const intervalMs = Math.max(1, def.intervalMs ?? DEFAULT_SOURCE_MS);
757
+ const minIntervalMs = Math.max(1, def.minIntervalMs ?? Math.min(DEFAULT_MIN_SOURCE_MS, intervalMs));
758
+ return { intervalMs: Math.max(intervalMs, minIntervalMs), minIntervalMs, timeoutMs: def.timeoutMs ?? DEFAULT_TIMEOUT_MS };
759
+ }
760
+ function sourceCommonFields(def) {
761
+ const fields = {};
762
+ if (canRunInBackground(def)) {
763
+ fields.background = t.boolean({
764
+ default: false,
765
+ label: { en: "Watch for alerts without a widget", es: "Vigilar avisos sin widget", de: "Ohne Widget auf Alarme achten", "zh-Hant": "\u7121\u9700\u5C0F\u5DE5\u5177\u4E5F\u76E3\u770B\u8B66\u5831", "zh-Hans": "\u65E0\u9700\u5C0F\u7EC4\u4EF6\u4E5F\u76D1\u770B\u8B66\u62A5" },
766
+ help: {
767
+ en: "Kiosko reads it even when no tile uses it, and its alerts take the panel over like any other. Off: it runs only while a widget uses it.",
768
+ es: "Kiosko la lee aunque ninguna tesela la use, y sus avisos ocupan el panel como cualquier otro. Apagado: solo corre mientras alg\xFAn widget la usa.",
769
+ de: "Kiosko liest sie, auch wenn keine Kachel sie verwendet, und ihre Alarme \xFCbernehmen das Panel wie jeder andere. Aus: Sie l\xE4uft nur, solange ein Widget sie verwendet.",
770
+ "zh-Hant": "\u5373\u4F7F\u6C92\u6709\u5716\u584A\u4F7F\u7528\uFF0CKiosko \u4E5F\u6703\u8B80\u53D6\u5B83\uFF0C\u5176\u8B66\u5831\u6703\u50CF\u5176\u4ED6\u8B66\u5831\u4E00\u6A23\u4F54\u6EFF\u9762\u677F\u3002\u95DC\u9589\u6642\uFF1A\u53EA\u5728\u6709\u5C0F\u5DE5\u5177\u4F7F\u7528\u6642\u624D\u57F7\u884C\u3002",
771
+ "zh-Hans": "\u5373\u4F7F\u6CA1\u6709\u56FE\u5757\u4F7F\u7528\uFF0CKiosko \u4E5F\u4F1A\u8BFB\u53D6\u5B83\uFF0C\u5176\u8B66\u62A5\u4F1A\u50CF\u5176\u4ED6\u8B66\u62A5\u4E00\u6837\u5360\u6EE1\u526F\u5C4F\u3002\u5173\u95ED\u65F6\uFF1A\u53EA\u5728\u6709\u5C0F\u7EC4\u4EF6\u4F7F\u7528\u65F6\u624D\u8FD0\u884C\u3002"
772
+ }
773
+ });
774
+ }
775
+ if (!def.read) return fields;
776
+ const { intervalMs, minIntervalMs, timeoutMs } = sourceTiming(def);
777
+ Object.assign(fields, {
778
+ intervalMs: t.duration({
779
+ default: intervalMs,
780
+ min: minIntervalMs,
781
+ max: Math.max(MAX_INTERVAL_MS, intervalMs),
782
+ label: { en: "Read every", es: "Leer cada", de: "Lesen alle", "zh-Hant": "\u8B80\u53D6\u9593\u9694", "zh-Hans": "\u8BFB\u53D6\u95F4\u9694" },
783
+ help: fields.background ? { en: `How often Kiosko reads it while it runs. At least ${human(minIntervalMs)}.`, es: `Cada cu\xE1nto lo lee Kiosko mientras corre. Como m\xEDnimo, ${human(minIntervalMs)}.`, de: `Wie oft Kiosko sie liest, solange sie l\xE4uft. Mindestens ${human(minIntervalMs)}.`, "zh-Hant": `\u57F7\u884C\u6642 Kiosko \u8B80\u53D6\u5B83\u7684\u983B\u7387\u3002\u6700\u5C11 ${human(minIntervalMs)}\u3002`, "zh-Hans": `\u8FD0\u884C\u65F6 Kiosko \u8BFB\u53D6\u5B83\u7684\u9891\u7387\u3002\u6700\u5C11 ${human(minIntervalMs)}\u3002` } : { en: `How often Kiosko reads it while a widget uses it. At least ${human(minIntervalMs)}.`, es: `Cada cu\xE1nto lo lee Kiosko mientras alg\xFAn widget lo usa. Como m\xEDnimo, ${human(minIntervalMs)}.`, de: `Wie oft Kiosko sie liest, solange ein Widget sie verwendet. Mindestens ${human(minIntervalMs)}.`, "zh-Hant": `\u5C0F\u5DE5\u5177\u4F7F\u7528\u6642\uFF0CKiosko \u8B80\u53D6\u5B83\u7684\u983B\u7387\u3002\u6700\u5C11 ${human(minIntervalMs)}\u3002`, "zh-Hans": `\u6709\u5C0F\u7EC4\u4EF6\u4F7F\u7528\u65F6 Kiosko \u8BFB\u53D6\u5B83\u7684\u9891\u7387\u3002\u6700\u5C11 ${human(minIntervalMs)}\u3002` }
784
+ }),
785
+ timeoutMs: t.duration({
786
+ default: timeoutMs,
787
+ min: MIN_TIMEOUT_MS,
788
+ max: Math.max(MAX_TIMEOUT_MS, timeoutMs),
789
+ advanced: true,
790
+ label: { en: "Give up a reading after", es: "Abandonar una lectura tras", de: "Lesen abbrechen nach", "zh-Hant": "\u8B80\u53D6\u903E\u6642", "zh-Hans": "\u8BFB\u53D6\u8D85\u65F6" },
791
+ help: { en: "A reading that takes longer is cancelled and counts as failed; the next try comes sooner.", es: "Una lectura que tarde m\xE1s se cancela y cuenta como fallida; el siguiente intento llega antes.", de: "Ein Lesevorgang, der l\xE4nger dauert, wird abgebrochen und z\xE4hlt als fehlgeschlagen; der n\xE4chste Versuch kommt fr\xFCher.", "zh-Hant": "\u8D85\u904E\u6B64\u6642\u9593\u7684\u8B80\u53D6\u6703\u88AB\u53D6\u6D88\u4E26\u8996\u70BA\u5931\u6557\uFF1B\u4E0B\u6B21\u6703\u63D0\u65E9\u91CD\u8A66\u3002", "zh-Hans": "\u8D85\u8FC7\u6B64\u65F6\u95F4\u7684\u8BFB\u53D6\u4F1A\u88AB\u53D6\u6D88\u5E76\u89C6\u4E3A\u5931\u8D25\uFF1B\u4E0B\u6B21\u4F1A\u63D0\u524D\u91CD\u8BD5\u3002" }
792
+ })
793
+ });
794
+ const own = def.options?.props ?? {};
795
+ return Object.fromEntries(Object.entries(fields).filter(([k]) => !(k in own)));
796
+ }
797
+ var merged = /* @__PURE__ */ new WeakMap();
798
+ function sourceOptionsField(def) {
799
+ if (!merged.has(def)) {
800
+ const own = def.options?.props ?? {};
801
+ const props = { ...own, ...sourceCommonFields(def) };
802
+ const o = def.options;
803
+ merged.set(def, Object.keys(props).length ? t.object(props, { ...o?.label ? { label: o.label } : {}, ...o?.help ? { help: o.help } : {} }) : null);
804
+ }
805
+ return merged.get(def) ?? void 0;
806
+ }
807
+
808
+ // packages/core/src/layout/stack.ts
809
+ function pickInStack(entries, now, rotateMs) {
810
+ const urgent = entries.find((e) => e.visible && e.urgent);
811
+ if (urgent) return urgent.id;
812
+ const shown = entries.filter((e) => e.visible);
813
+ if (!shown.length) return null;
814
+ if (shown.length === 1 || rotateMs <= 0) return shown[0].id;
815
+ const turn = Math.floor(now / Math.max(1e3, rotateMs));
816
+ return shown[turn % shown.length].id;
817
+ }
818
+ function nextTurnAt(now, rotateMs) {
819
+ const p = Math.max(1e3, rotateMs);
820
+ return (Math.floor(now / p) + 1) * p;
821
+ }
822
+ function pickPage(pages, now, pinned) {
823
+ const on = pages.filter((p) => p.enabled !== false);
824
+ if (!on.length) return null;
825
+ if (pinned) {
826
+ const p = on.find((x) => x.id === pinned);
827
+ if (p) return p;
828
+ }
829
+ if (on.length === 1) return on[0];
830
+ const lens = on.map((p) => Math.max(1e4, p.durationMs ?? 10 * 6e4));
831
+ const cycle = lens.reduce((a, b) => a + b, 0);
832
+ let t2 = now % cycle;
833
+ for (let i = 0; i < on.length; i++) {
834
+ if (t2 < lens[i]) return on[i];
835
+ t2 -= lens[i];
836
+ }
837
+ return on[0];
838
+ }
839
+
840
+ // packages/core/src/compositor.ts
841
+ import { createCanvas as createCanvas5, loadImage as loadImage3 } from "@napi-rs/canvas";
842
+
843
+ // packages/lcd-canvas-kit/src/index.ts
844
+ var src_exports = {};
845
+ __export(src_exports, {
846
+ FileSink: () => FileSink,
847
+ TAU: () => TAU,
848
+ bezierPts: () => bezierPts,
849
+ clamp: () => clamp2,
850
+ clearTextCache: () => clearTextCache,
851
+ css: () => css,
852
+ drawClipped: () => drawClipped,
853
+ drawMoonPhase: () => drawMoonPhase,
854
+ drawTracked: () => drawTracked,
855
+ drawWeatherIcon: () => drawWeatherIcon,
856
+ ellipse: () => ellipse,
857
+ fitSize: () => fitSize,
858
+ hasCjk: () => hasCjk,
859
+ hashString: () => hashString,
860
+ hex: () => hex,
861
+ linear: () => linear,
862
+ measureTracked: () => measureTracked,
863
+ mix: () => mix,
864
+ pixelShift: () => pixelShift,
865
+ radial: () => radial,
866
+ registerFontFiles: () => registerFontFiles,
867
+ rng: () => rng,
868
+ setDefaultFamily: () => setDefaultFamily,
869
+ setMinCjkPx: () => setMinCjkPx,
870
+ smooth: () => smooth,
871
+ sparkBars: () => sparkBars,
872
+ takeCjkEnlarged: () => takeCjkEnlarged,
873
+ truncate: () => truncate,
874
+ wrapLines: () => wrapLines
875
+ });
876
+
877
+ // packages/lcd-canvas-kit/src/text.ts
878
+ import { GlobalFonts } from "@napi-rs/canvas";
879
+ var defaultFamily = "sans-serif";
880
+ function setDefaultFamily(family) {
881
+ defaultFamily = family;
882
+ }
883
+ function registerFontFiles(fonts) {
884
+ widths.clear();
885
+ return Object.entries(fonts).filter(([family, path]) => !GlobalFonts.registerFromPath(path, family)).map(([, path]) => path);
886
+ }
887
+ var widths = /* @__PURE__ */ new Map();
888
+ var MAX_FONTS = 400;
889
+ function widthOf(ctx, font, ch) {
890
+ let byChar = widths.get(font);
891
+ if (!byChar) {
892
+ if (widths.size >= MAX_FONTS) widths.clear();
893
+ byChar = /* @__PURE__ */ new Map();
894
+ widths.set(font, byChar);
895
+ }
896
+ let w = byChar.get(ch);
897
+ if (w === void 0) {
898
+ if (ctx.font !== font) ctx.font = font;
899
+ w = ctx.measureText(ch).width;
900
+ byChar.set(ch, w);
901
+ }
902
+ return w;
903
+ }
904
+ function clearTextCache() {
905
+ widths.clear();
906
+ }
907
+ var CJK = /[\u1100-\u11ff\u2e80-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/;
908
+ function hasCjk(text2) {
909
+ return CJK.test(text2);
910
+ }
911
+ function trackingOf(text2, o) {
912
+ return o.tracking && hasCjk(text2) ? 0 : o.tracking ?? 0;
913
+ }
914
+ var minCjkPx = 0;
915
+ var enlarged = Infinity;
916
+ function setMinCjkPx(px) {
917
+ if (px !== minCjkPx) widths.clear();
918
+ minCjkPx = Math.max(0, px);
919
+ }
920
+ function takeCjkEnlarged() {
921
+ const v = enlarged;
922
+ enlarged = Infinity;
923
+ return Number.isFinite(v) ? Math.round(v) : null;
924
+ }
925
+ function scaleOf(ctx) {
926
+ const t2 = ctx.getTransform?.();
927
+ return t2 ? Math.hypot(t2.a, t2.b) || 1 : 1;
928
+ }
929
+ function glyphs(ctx, text2, o) {
930
+ const family = o.family ?? defaultFamily;
931
+ const cjk = hasCjk(text2);
932
+ const small = o.smallCaps === true && !cjk;
933
+ const capSize = o.size * (o.capRatio ?? 0.76);
934
+ const out = [];
935
+ const font = `${o.size}px "${family}"`;
936
+ const capFont = `${capSize}px "${family}"`;
937
+ let cjkSize = o.size;
938
+ if (cjk && minCjkPx > 0) {
939
+ const scale = scaleOf(ctx);
940
+ if (o.size * scale < minCjkPx - 0.5) {
941
+ cjkSize = minCjkPx / scale;
942
+ enlarged = Math.min(enlarged, o.size * scale);
943
+ }
944
+ }
945
+ const cjkFont = `${cjkSize}px "${family}"`;
946
+ for (const ch of text2) {
947
+ if (cjkSize !== o.size && CJK.test(ch)) {
948
+ out.push({ ch, size: cjkSize, width: widthOf(ctx, cjkFont, ch) });
949
+ continue;
950
+ }
951
+ const isLower = small && ch !== ch.toUpperCase() && ch === ch.toLowerCase();
952
+ const size = isLower ? capSize : o.size;
953
+ const draw = small ? ch.toUpperCase() : ch;
954
+ out.push({ ch: draw, size, width: widthOf(ctx, isLower ? capFont : font, draw) });
955
+ }
956
+ return out;
957
+ }
958
+ function advance(gs, tracking) {
959
+ if (!gs.length) return 0;
960
+ return gs.reduce((a, g) => a + g.width, 0) + tracking * (gs.length - 1);
961
+ }
962
+ function measureTracked(ctx, text2, o) {
963
+ return advance(glyphs(ctx, text2, o), trackingOf(text2, o));
964
+ }
965
+ function drawTracked(ctx, text2, x, y, o) {
966
+ const family = o.family ?? defaultFamily;
967
+ const tracking = trackingOf(text2, o);
968
+ const gs = glyphs(ctx, text2, o);
969
+ const total = advance(gs, tracking);
970
+ let cursor = o.align === "right" ? x - total : o.align === "center" ? x - total / 2 : x;
971
+ if (o.color) ctx.fillStyle = o.color;
972
+ ctx.textBaseline = "alphabetic";
973
+ let size = -1;
974
+ for (const g of gs) {
975
+ if (g.size !== size) {
976
+ ctx.font = `${g.size}px "${family}"`;
977
+ size = g.size;
978
+ }
979
+ ctx.fillText(g.ch, cursor, y);
980
+ cursor += g.width + tracking;
981
+ }
982
+ return total;
983
+ }
984
+ function truncate(ctx, text2, maxWidth, o) {
985
+ if (measureTracked(ctx, text2, o) <= maxWidth) return text2;
986
+ const chars = [...text2];
987
+ const candidate = (n) => `${chars.slice(0, n).join("").trimEnd()}\u2026`;
988
+ let lo = 0;
989
+ let hi = chars.length;
990
+ while (lo < hi) {
991
+ const mid = Math.ceil((lo + hi) / 2);
992
+ if (measureTracked(ctx, candidate(mid), o) <= maxWidth) lo = mid;
993
+ else hi = mid - 1;
994
+ }
995
+ return lo > 0 ? candidate(lo) : "\u2026";
996
+ }
997
+ function fitSize(ctx, text2, maxWidth, o, minSize) {
998
+ let size = o.size;
999
+ while (size > minSize && measureTracked(ctx, text2, { ...o, size }) > maxWidth) size -= 1;
1000
+ return size;
1001
+ }
1002
+ function drawClipped(ctx, text2, x, y, maxWidth, o) {
1003
+ return drawTracked(ctx, truncate(ctx, text2, maxWidth, o), x, y, o);
1004
+ }
1005
+ var NO_START = /* @__PURE__ */ new Set([..."\u3001\u3002\uFF0C\uFF0E\uFF1A\uFF1B\uFF1F\uFF01\uFF09\u300D\u300F\u3011\u300B\u3009\u3015\uFF5D\u3017\u3019\u301B\u2019\u201D\u2026\u2025\u30FC\u3005\u309D\u309E\u30FD\u30FE\u3041\u3043\u3045\u3047\u3049\u3063\u3083\u3085\u3087\u308E\u30A1\u30A3\u30A5\u30A7\u30A9\u30C3\u30E3\u30E5\u30E7\u30EE\u30F5\u30F6,.;:?!)]}%"]);
1006
+ var NO_END = /* @__PURE__ */ new Set([..."\uFF08\u300C\u300E\u3010\u300A\u3008\u3014\uFF5B\u3016\u3018\u301A\u2018\u201C([{$"]);
1007
+ var isSpace = (c) => /\s/.test(c);
1008
+ function fitPrefix(ctx, text2, maxWidth, o) {
1009
+ if (measureTracked(ctx, text2, o) <= maxWidth) return text2.length;
1010
+ const chars = [...text2];
1011
+ let lo = 1;
1012
+ let hi = chars.length;
1013
+ while (lo < hi) {
1014
+ const mid = Math.ceil((lo + hi) / 2);
1015
+ if (measureTracked(ctx, chars.slice(0, mid).join(""), o) <= maxWidth) lo = mid;
1016
+ else hi = mid - 1;
1017
+ }
1018
+ const cjk = hasCjk(text2);
1019
+ const fits = (i) => !NO_START.has(chars[i]) && !NO_END.has(chars[i - 1]);
1020
+ let cut = 0;
1021
+ for (let i = lo; i >= 1; i--) {
1022
+ const before = chars[i - 1];
1023
+ const after = chars[i];
1024
+ if ((isSpace(before) || isSpace(after) || CJK.test(before) || CJK.test(after)) && fits(i)) {
1025
+ cut = i;
1026
+ break;
1027
+ }
1028
+ }
1029
+ if (!cut || cjk && cut < lo * 0.6) {
1030
+ cut = lo;
1031
+ while (cut > 1 && !fits(cut)) cut--;
1032
+ }
1033
+ return chars.slice(0, cut).join("").length;
1034
+ }
1035
+ function wrapLines(ctx, text2, maxWidth, maxLines, o) {
1036
+ const clean = text2.replace(/\s+/g, " ").trim();
1037
+ if (!clean || maxLines < 1 || maxWidth <= 0) return [];
1038
+ const lines = [];
1039
+ let rest = clean;
1040
+ while (rest && lines.length < maxLines) {
1041
+ if (lines.length === maxLines - 1) {
1042
+ lines.push(truncate(ctx, rest, maxWidth, o));
1043
+ break;
1044
+ }
1045
+ const cut = fitPrefix(ctx, rest, maxWidth, o);
1046
+ lines.push(rest.slice(0, cut).trimEnd());
1047
+ rest = rest.slice(cut).trimStart();
1048
+ }
1049
+ return lines;
1050
+ }
1051
+
1052
+ // packages/lcd-canvas-kit/src/paint.ts
1053
+ var TAU = Math.PI * 2;
1054
+ var hex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
1055
+ var mix = (a, b, t2) => [0, 1, 2].map((i) => a[i] + (b[i] - a[i]) * t2);
1056
+ var css = (c, a = 1) => `rgba(${c.map(Math.round).join(",")},${a})`;
1057
+ var clamp2 = (v, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, v));
1058
+ var smooth = (e0, e1, v) => {
1059
+ const t2 = clamp2((v - e0) / (e1 - e0));
1060
+ return t2 * t2 * (3 - 2 * t2);
1061
+ };
1062
+ function rng(seed) {
1063
+ let s = seed | 0;
1064
+ return () => {
1065
+ s = s + 1831565813 | 0;
1066
+ let t2 = Math.imul(s ^ s >>> 15, 1 | s);
1067
+ t2 = t2 + Math.imul(t2 ^ t2 >>> 7, 61 | t2) ^ t2;
1068
+ return ((t2 ^ t2 >>> 14) >>> 0) / 4294967296;
1069
+ };
1070
+ }
1071
+ function hashString(s) {
1072
+ let h = 2166136261;
1073
+ for (let i = 0; i < s.length; i++) {
1074
+ h ^= s.charCodeAt(i);
1075
+ h = Math.imul(h, 16777619);
1076
+ }
1077
+ return h >>> 0;
1078
+ }
1079
+ function ellipse(c, x, y, rx, ry, rot = 0) {
1080
+ c.beginPath();
1081
+ c.ellipse(x, y, Math.max(0.01, rx), Math.max(0.01, ry), rot, 0, TAU);
1082
+ }
1083
+ function radial(c, x, y, r0, r1, stops, fx = x, fy = y) {
1084
+ const g = c.createRadialGradient(fx, fy, r0, x, y, r1);
1085
+ for (const [o, col] of stops) g.addColorStop(o, col);
1086
+ return g;
1087
+ }
1088
+ function linear(c, x0, y0, x1, y1, stops) {
1089
+ const g = c.createLinearGradient(x0, y0, x1, y1);
1090
+ for (const [o, col] of stops) g.addColorStop(o, col);
1091
+ return g;
1092
+ }
1093
+ function bezierPts(p, steps = 40) {
1094
+ const out = [];
1095
+ for (let i = 0; i <= steps; i++) {
1096
+ const t2 = i / steps, u = 1 - t2;
1097
+ out.push([0, 1].map((k) => u * u * u * p[0][k] + 3 * u * u * t2 * p[1][k] + 3 * u * t2 * t2 * p[2][k] + t2 * t2 * t2 * p[3][k]));
1098
+ }
1099
+ return out;
1100
+ }
1101
+
1102
+ // packages/lcd-canvas-kit/src/sparkline.ts
1103
+ function sparkBars(values, w, h, opts = {}) {
1104
+ const n = values.length;
1105
+ if (n === 0 || w <= 0 || h <= 0) return [];
1106
+ const gap = opts.gap ?? 2;
1107
+ const minHeight = opts.minHeight ?? 1;
1108
+ const effGap = n > 1 && (w - gap * (n - 1)) / n < 1 ? 0 : gap;
1109
+ const barW = Math.max(1, (w - effGap * (n - 1)) / n);
1110
+ const max = opts.max ?? Math.max(...values);
1111
+ return values.map((value, index) => {
1112
+ const ratio = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0;
1113
+ const barH = Math.max(minHeight, Math.round(h * ratio));
1114
+ return {
1115
+ x: Math.round(index * (barW + effGap)),
1116
+ y: Math.round(h - barH),
1117
+ w: Math.max(1, Math.round(barW)),
1118
+ h: barH,
1119
+ index,
1120
+ value
1121
+ };
1122
+ });
1123
+ }
1124
+
1125
+ // packages/lcd-canvas-kit/src/pixelshift.ts
1126
+ var CYCLE = [
1127
+ [0, 0],
1128
+ [1, 0],
1129
+ [1, 0.5],
1130
+ [1, 1],
1131
+ [0.5, 1],
1132
+ [0, 1]
1133
+ ];
1134
+ function pixelShift(now, o) {
1135
+ if (!o.enabled) return { x: 0, y: 0 };
1136
+ const step = CYCLE[Math.floor(now / o.periodMs) % CYCLE.length];
1137
+ return { x: Math.round(step[0] * o.amplitude), y: Math.round(step[1] * o.amplitude) };
1138
+ }
1139
+
1140
+ // packages/lcd-canvas-kit/src/weathericons.ts
1141
+ import { createCanvas } from "@napi-rs/canvas";
1142
+ function cloud(ctx, cx, cy, s) {
1143
+ const r = s * 0.22;
1144
+ ctx.beginPath();
1145
+ ctx.arc(cx - s * 0.22, cy + s * 0.04, r, Math.PI * 0.5, Math.PI * 1.5);
1146
+ ctx.arc(cx - s * 0.06, cy - s * 0.14, r * 1.25, Math.PI, Math.PI * 1.85);
1147
+ ctx.arc(cx + s * 0.22, cy + s * 0.02, r * 0.95, Math.PI * 1.4, Math.PI * 0.5);
1148
+ ctx.closePath();
1149
+ ctx.fill();
1150
+ }
1151
+ function sun(ctx, cx, cy, s, rays = true) {
1152
+ const r = s * 0.19;
1153
+ ctx.beginPath();
1154
+ ctx.arc(cx, cy, r, 0, Math.PI * 2);
1155
+ ctx.fill();
1156
+ if (!rays) return;
1157
+ ctx.lineWidth = Math.max(1.5, s * 0.045);
1158
+ ctx.lineCap = "round";
1159
+ for (let i = 0; i < 8; i += 1) {
1160
+ const a = i * Math.PI / 4;
1161
+ ctx.beginPath();
1162
+ ctx.moveTo(cx + Math.cos(a) * r * 1.45, cy + Math.sin(a) * r * 1.45);
1163
+ ctx.lineTo(cx + Math.cos(a) * r * 1.95, cy + Math.sin(a) * r * 1.95);
1164
+ ctx.stroke();
1165
+ }
1166
+ }
1167
+ function moon(ctx, cx, cy, s) {
1168
+ const r = s * 0.24;
1169
+ const pad = 2;
1170
+ const side = Math.ceil(r * 2 + pad * 2);
1171
+ const off = createCanvas(side, side);
1172
+ const o = off.getContext("2d");
1173
+ const c = side / 2;
1174
+ o.fillStyle = ctx.fillStyle;
1175
+ o.beginPath();
1176
+ o.arc(c, c, r, 0, Math.PI * 2);
1177
+ o.fill();
1178
+ o.globalCompositeOperation = "destination-out";
1179
+ o.beginPath();
1180
+ o.arc(c + r * 0.55, c - r * 0.42, r * 0.92, 0, Math.PI * 2);
1181
+ o.fill();
1182
+ ctx.drawImage(off, cx - c, cy - c);
1183
+ }
1184
+ function drops(ctx, cx, cy, s, len) {
1185
+ ctx.lineWidth = Math.max(1.5, s * 0.05);
1186
+ ctx.lineCap = "round";
1187
+ for (const dx of [-0.2, 0, 0.2]) {
1188
+ ctx.beginPath();
1189
+ ctx.moveTo(cx + s * dx + s * 0.05, cy + s * 0.22);
1190
+ ctx.lineTo(cx + s * dx - s * 0.02, cy + s * (0.22 + len));
1191
+ ctx.stroke();
1192
+ }
1193
+ }
1194
+ function snowflakes(ctx, cx, cy, s) {
1195
+ ctx.lineWidth = Math.max(1.2, s * 0.035);
1196
+ ctx.lineCap = "round";
1197
+ for (const dx of [-0.2, 0.05]) {
1198
+ const x = cx + s * dx;
1199
+ const y = cy + s * 0.3;
1200
+ for (let i = 0; i < 3; i += 1) {
1201
+ const a = i * Math.PI / 3;
1202
+ ctx.beginPath();
1203
+ ctx.moveTo(x - Math.cos(a) * s * 0.07, y - Math.sin(a) * s * 0.07);
1204
+ ctx.lineTo(x + Math.cos(a) * s * 0.07, y + Math.sin(a) * s * 0.07);
1205
+ ctx.stroke();
1206
+ }
1207
+ }
1208
+ }
1209
+ function bolt(ctx, cx, cy, s) {
1210
+ ctx.beginPath();
1211
+ ctx.moveTo(cx + s * 0.06, cy + s * 0.16);
1212
+ ctx.lineTo(cx - s * 0.1, cy + s * 0.34);
1213
+ ctx.lineTo(cx + s * 0.01, cy + s * 0.34);
1214
+ ctx.lineTo(cx - s * 0.06, cy + s * 0.5);
1215
+ ctx.lineTo(cx + s * 0.14, cy + s * 0.28);
1216
+ ctx.lineTo(cx + s * 0.03, cy + s * 0.28);
1217
+ ctx.closePath();
1218
+ ctx.fill();
1219
+ }
1220
+ function fogLines(ctx, cx, cy, s) {
1221
+ ctx.lineWidth = Math.max(1.5, s * 0.055);
1222
+ ctx.lineCap = "round";
1223
+ for (const [i, w] of [0.34, 0.4, 0.28].entries()) {
1224
+ const y = cy + s * (0.2 + i * 0.13);
1225
+ ctx.beginPath();
1226
+ ctx.moveTo(cx - s * w, y);
1227
+ ctx.lineTo(cx + s * w, y);
1228
+ ctx.stroke();
1229
+ }
1230
+ }
1231
+ function drawWeatherIcon(ctx, kind, cx, cy, size, color) {
1232
+ ctx.save();
1233
+ ctx.fillStyle = color;
1234
+ ctx.strokeStyle = color;
1235
+ switch (kind) {
1236
+ case "sun":
1237
+ sun(ctx, cx, cy, size);
1238
+ break;
1239
+ case "moon":
1240
+ moon(ctx, cx, cy, size);
1241
+ break;
1242
+ case "sun-cloud":
1243
+ sun(ctx, cx - size * 0.16, cy - size * 0.18, size * 0.72);
1244
+ cloud(ctx, cx + size * 0.06, cy + size * 0.1, size);
1245
+ break;
1246
+ case "moon-cloud":
1247
+ moon(ctx, cx - size * 0.16, cy - size * 0.2, size * 0.72);
1248
+ cloud(ctx, cx + size * 0.06, cy + size * 0.1, size);
1249
+ break;
1250
+ case "cloud":
1251
+ cloud(ctx, cx, cy, size);
1252
+ break;
1253
+ case "fog":
1254
+ cloud(ctx, cx, cy - size * 0.12, size * 0.9);
1255
+ fogLines(ctx, cx, cy, size);
1256
+ break;
1257
+ case "drizzle":
1258
+ cloud(ctx, cx, cy - size * 0.1, size);
1259
+ drops(ctx, cx, cy - size * 0.1, size, 0.14);
1260
+ break;
1261
+ case "rain":
1262
+ cloud(ctx, cx, cy - size * 0.12, size);
1263
+ drops(ctx, cx, cy - size * 0.12, size, 0.26);
1264
+ break;
1265
+ case "snow":
1266
+ cloud(ctx, cx, cy - size * 0.14, size);
1267
+ snowflakes(ctx, cx, cy - size * 0.14, size);
1268
+ break;
1269
+ case "storm":
1270
+ cloud(ctx, cx, cy - size * 0.14, size);
1271
+ bolt(ctx, cx, cy - size * 0.14, size);
1272
+ break;
1273
+ }
1274
+ ctx.restore();
1275
+ }
1276
+ function drawMoonPhase(ctx, moon2, cx, cy, size, color) {
1277
+ const r = size / 2;
1278
+ const pad = 2;
1279
+ const side = Math.ceil(size + pad * 2);
1280
+ const off = createCanvas(side, side);
1281
+ const o = off.getContext("2d");
1282
+ const c = side / 2;
1283
+ o.fillStyle = color;
1284
+ o.beginPath();
1285
+ o.arc(c, c, r, 0, Math.PI * 2);
1286
+ o.fill();
1287
+ const f = 1 - 2 * moon2.illumination;
1288
+ const dark = moon2.waxing ? -1 : 1;
1289
+ const STEPS = 48;
1290
+ o.globalCompositeOperation = "destination-out";
1291
+ o.beginPath();
1292
+ for (let i = 0; i <= STEPS; i += 1) {
1293
+ const u = i / STEPS * Math.PI;
1294
+ o.lineTo(c + dark * r * Math.sin(u), c - r * Math.cos(u));
1295
+ }
1296
+ for (let i = STEPS; i >= 0; i -= 1) {
1297
+ const u = i / STEPS * Math.PI;
1298
+ o.lineTo(c - dark * r * f * Math.sin(u), c - r * Math.cos(u));
1299
+ }
1300
+ o.closePath();
1301
+ o.fill();
1302
+ ctx.save();
1303
+ ctx.drawImage(off, cx - c, cy - c);
1304
+ ctx.strokeStyle = "rgba(255,255,255,0.22)";
1305
+ ctx.lineWidth = Math.max(1, size * 0.02);
1306
+ ctx.beginPath();
1307
+ ctx.arc(cx, cy, r, 0, Math.PI * 2);
1308
+ ctx.stroke();
1309
+ ctx.restore();
1310
+ }
1311
+
1312
+ // packages/lcd-canvas-kit/src/sink.ts
1313
+ import { renameSync, writeFileSync } from "node:fs";
1314
+ var FileSink = class {
1315
+ path;
1316
+ constructor(path) {
1317
+ this.path = path;
1318
+ }
1319
+ async send(frame) {
1320
+ const tmp = `${this.path}.tmp`;
1321
+ writeFileSync(tmp, frame);
1322
+ renameSync(tmp, this.path);
1323
+ }
1324
+ };
1325
+
1326
+ // packages/core/src/env.ts
1327
+ import { mkdirSync } from "node:fs";
1328
+ import { createCanvas as createCanvas3, loadImage as loadImage2 } from "@napi-rs/canvas";
1329
+
1330
+ // packages/core/src/scaled-images.ts
1331
+ import { createRequire } from "node:module";
1332
+ import { Worker } from "node:worker_threads";
1333
+ import { createCanvas as createCanvas2, loadImage } from "@napi-rs/canvas";
1334
+ function scaledSize(w, h, size) {
1335
+ const sx = size.width / w, sy = size.height / h;
1336
+ const s = Math.min(1, (size.fit ?? "cover") === "cover" ? Math.max(sx, sy) : Math.min(sx, sy));
1337
+ return { width: Math.max(1, Math.round(w * s)), height: Math.max(1, Math.round(h * s)) };
1338
+ }
1339
+ var WORKER = `
1340
+ const { parentPort, workerData } = require('node:worker_threads');
1341
+ const { readFile } = require('node:fs/promises');
1342
+ const { createCanvas, loadImage } = require(workerData.canvas);
1343
+ const scaledSize = ${scaledSize.toString()};
1344
+ parentPort.on('message', async (job) => {
1345
+ try {
1346
+ const src = typeof job.src === 'string' ? await readFile(job.src) : Buffer.from(job.src);
1347
+ const img = await loadImage(src);
1348
+ const to = scaledSize(img.width, img.height, job.size);
1349
+ if (to.width >= img.width && to.height >= img.height) {
1350
+ // Already small enough: the bytes as they are.
1351
+ parentPort.postMessage({ id: job.id, ok: true, same: true });
1352
+ return;
1353
+ }
1354
+ const c = createCanvas(to.width, to.height);
1355
+ const g = c.getContext('2d');
1356
+ g.imageSmoothingQuality = 'high';
1357
+ g.drawImage(img, 0, 0, to.width, to.height);
1358
+ const png = src[0] === 0x89 && src[1] === 0x50;
1359
+ const out = png ? await c.encode('png') : await c.encode('jpeg', 90);
1360
+ const ab = out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength);
1361
+ parentPort.postMessage({ id: job.id, ok: true, bytes: ab }, [ab]);
1362
+ } catch (err) {
1363
+ parentPort.postMessage({ id: job.id, ok: false, error: err && err.message ? err.message : String(err) });
1364
+ }
1365
+ });
1366
+ `;
1367
+ var worker = null;
1368
+ var broken = false;
1369
+ var nextId = 1;
1370
+ var pending = /* @__PURE__ */ new Map();
1371
+ function startWorker() {
1372
+ if (worker) return worker;
1373
+ if (broken) return null;
1374
+ try {
1375
+ const canvas = createRequire(import.meta.url).resolve("@napi-rs/canvas");
1376
+ const w = new Worker(WORKER, { eval: true, workerData: { canvas } });
1377
+ w.on("message", (m) => {
1378
+ const p = pending.get(m.id);
1379
+ if (!p) return;
1380
+ pending.delete(m.id);
1381
+ if (!pending.size) w.unref();
1382
+ if (m.ok) p.resolve(m);
1383
+ else p.reject(new Error(m.error ?? "could not scale the image"));
1384
+ });
1385
+ const gone = (err) => {
1386
+ if (worker === w) worker = null;
1387
+ for (const [id, p] of pending) {
1388
+ pending.delete(id);
1389
+ p.reject(err ?? new Error("the image thread stopped"));
1390
+ }
1391
+ };
1392
+ w.on("error", gone);
1393
+ w.on("exit", () => gone());
1394
+ w.unref();
1395
+ worker = w;
1396
+ return w;
1397
+ } catch {
1398
+ broken = true;
1399
+ return null;
1400
+ }
1401
+ }
1402
+ function warm(img) {
1403
+ const w = Math.max(1, Math.round(img.width / 3)), h = Math.max(1, Math.round(img.height / 3));
1404
+ createCanvas2(w, h).getContext("2d").drawImage(img, 0, 0, w, h);
1405
+ return img;
1406
+ }
1407
+ async function loadImageScaled(src, size) {
1408
+ if (!(size.width > 0) || !(size.height > 0)) throw new Error("loadImageScaled: width and height must be over 0");
1409
+ const w = startWorker();
1410
+ if (!w) return warm(await loadImage(src));
1411
+ const id = nextId++;
1412
+ const job = typeof src === "string" ? src : src.buffer.slice(src.byteOffset, src.byteOffset + src.byteLength);
1413
+ const r = await new Promise((resolve2, reject) => {
1414
+ pending.set(id, { resolve: resolve2, reject });
1415
+ w.ref();
1416
+ w.postMessage({ id, src: job, size });
1417
+ });
1418
+ return warm(await loadImage(r.same || !r.bytes ? src : Buffer.from(r.bytes)));
1419
+ }
1420
+
1421
+ // packages/core/src/env.ts
1422
+ var CANVAS = { createCanvas: createCanvas3, loadImage: loadImage2, loadImageScaled };
1423
+ function systemLocale() {
1424
+ try {
1425
+ return Intl.DateTimeFormat().resolvedOptions().locale || "en";
1426
+ } catch {
1427
+ return "en";
1428
+ }
1429
+ }
1430
+ function resolveLocale(cfg) {
1431
+ return !cfg.locale || cfg.locale === "auto" ? systemLocale() : cfg.locale;
1432
+ }
1433
+ function baseContext(cfg, plugin, log, now) {
1434
+ let made = false;
1435
+ const dir = paths.data(plugin);
1436
+ const cache = paths.cache(plugin);
1437
+ let cacheMade = false;
1438
+ const base2 = createBaseContext({ now, locale: resolveLocale(cfg), timeFormat: cfg.timeFormat, workday: cfg.workday, ...cfg.location ? { location: cfg.location } : {}, log: (msg) => log(plugin, msg) });
1439
+ return {
1440
+ ...base2,
1441
+ get cacheDir() {
1442
+ if (!cache) return this.dataDir;
1443
+ if (!cacheMade) {
1444
+ try {
1445
+ mkdirSync(cache, { recursive: true });
1446
+ } catch {
1447
+ return this.dataDir;
1448
+ }
1449
+ cacheMade = true;
1450
+ }
1451
+ return cache;
1452
+ },
1453
+ get dataDir() {
1454
+ if (!made) {
1455
+ try {
1456
+ mkdirSync(dir, { recursive: true });
1457
+ } catch {
1458
+ }
1459
+ made = true;
1460
+ }
1461
+ return dir;
1462
+ }
1463
+ };
1464
+ }
1465
+
1466
+ // packages/core/src/fonts.ts
1467
+ import { existsSync as existsSync2, readdirSync } from "node:fs";
1468
+ import { createRequire as createRequire2 } from "node:module";
1469
+ import { dirname, join as join3 } from "node:path";
1470
+ import { createCanvas as createCanvas4, GlobalFonts as GlobalFonts2 } from "@napi-rs/canvas";
1471
+
1472
+ // packages/core/src/font-fallback.ts
1473
+ var CJK_FAMILIES = {
1474
+ Hant: ["Noto Sans CJK TC", "Noto Sans TC", "Source Han Sans TC", "Source Han Sans TW", "Microsoft JhengHei", "Microsoft JhengHei UI", "PingFang TC", "Heiti TC", "Sarasa Gothic TC", "AR PL UMing TW", "AR PL UKai TW", "PMingLiU", "MingLiU"],
1475
+ "Hant-HK": ["Noto Sans CJK HK", "Noto Sans HK", "Source Han Sans HK", "Microsoft JhengHei", "PingFang HK", "Sarasa Gothic HC", "AR PL UMing HK", "Noto Sans CJK TC", "Noto Sans TC", "PingFang TC", "MingLiU_HKSCS"],
1476
+ Hans: ["Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "Source Han Sans CN", "Microsoft YaHei", "Microsoft YaHei UI", "PingFang SC", "Heiti SC", "Hiragino Sans GB", "STHeiti", "HarmonyOS Sans SC", "Sarasa Gothic SC", "WenQuanYi Zen Hei", "WenQuanYi Micro Hei", "AR PL UMing CN", "SimHei", "SimSun", "Droid Sans Fallback"],
1477
+ Jpan: ["Noto Sans CJK JP", "Noto Sans JP", "Source Han Sans JP", "Source Han Sans", "Yu Gothic", "Meiryo", "Hiragino Sans", "Hiragino Kaku Gothic ProN", "IPAexGothic", "IPAGothic", "TakaoGothic", "VL Gothic"],
1478
+ Kore: ["Noto Sans CJK KR", "Noto Sans KR", "Source Han Sans KR", "Source Han Sans K", "Malgun Gothic", "Apple SD Gothic Neo", "NanumGothic", "UnDotum"]
1479
+ };
1480
+ var OTHER_SCRIPTS = [
1481
+ { script: "Thai", probe: "\u0E01", families: ["Noto Sans Thai", "Noto Sans Thai UI", "Leelawadee UI", "Leelawadee", "Thonburi", "Tlwg Typo", "Garuda"] },
1482
+ { script: "Deva", probe: "\u0915", families: ["Noto Sans Devanagari", "Nirmala UI", "Kohinoor Devanagari", "Lohit Devanagari", "Mangal"] },
1483
+ { script: "Beng", probe: "\u0995", families: ["Noto Sans Bengali", "Nirmala UI", "Kohinoor Bangla", "Lohit Bengali"] },
1484
+ { script: "Taml", probe: "\u0B95", families: ["Noto Sans Tamil", "Nirmala UI", "Tamil Sangam MN", "Lohit Tamil"] },
1485
+ { script: "Arab", probe: "\u0639", families: ["Noto Sans Arabic", "Noto Naskh Arabic", "Segoe UI", "Geeza Pro", "DejaVu Sans"] },
1486
+ { script: "Hebr", probe: "\u05D0", families: ["Noto Sans Hebrew", "Segoe UI", "Arial Hebrew", "DejaVu Sans"] },
1487
+ { script: "Geor", probe: "\u10D0", families: ["Noto Sans Georgian", "Sylfaen", "DejaVu Sans"] },
1488
+ { script: "Armn", probe: "\u0531", families: ["Noto Sans Armenian", "Sylfaen", "DejaVu Sans"] },
1489
+ { script: "Ethi", probe: "\u12A0", families: ["Noto Sans Ethiopic", "Ebrima", "Kefa"] }
1490
+ ];
1491
+ function scriptOrder(own) {
1492
+ const rest = ["Hans", "Hant", "Jpan", "Kore"];
1493
+ if (!own) return rest;
1494
+ const first = own === "Hant-HK" ? ["Hant-HK", "Hant"] : [own];
1495
+ return [...first, ...rest.filter((s) => !first.includes(s))];
1496
+ }
1497
+ function cjkFamiliesFor(locale, available2, own = []) {
1498
+ const out = [...own];
1499
+ for (const s of scriptOrder(hanScript(locale))) {
1500
+ const found = CJK_FAMILIES[s].find((f) => !out.includes(f) && available2(f));
1501
+ if (found) out.push(found);
1502
+ }
1503
+ return [...new Set(out)];
1504
+ }
1505
+ var BOLD_FAMILIES = [FONT_FAMILIES.sansBold, FONT_FAMILIES.monoBold];
1506
+ var FontFallback = class {
1507
+ tail = "";
1508
+ memo = /* @__PURE__ */ new Map();
1509
+ /** Sets the families; true if they changed (callers then forget measured widths). */
1510
+ setFamilies(families) {
1511
+ const tail = families.map((f) => `, "${f.replace(/"/g, "")}"`).join("");
1512
+ if (tail === this.tail) return false;
1513
+ this.tail = tail;
1514
+ this.memo.clear();
1515
+ return true;
1516
+ }
1517
+ /**
1518
+ * `font` with the families behind it. Kiosko's bold families are DejaVu
1519
+ * Bold files under their own name, so the string asks for no weight and
1520
+ * the CJK font would come out regular: ask for bold too, which the DejaVu
1521
+ * Bold face already is.
1522
+ */
1523
+ apply(font) {
1524
+ if (!this.tail) return font;
1525
+ let out = this.memo.get(font);
1526
+ if (out === void 0) {
1527
+ out = font;
1528
+ if (!font.endsWith(this.tail)) {
1529
+ out = font + this.tail;
1530
+ const size = /\d*\.?\d+(px|pt|em|rem)\b/.exec(font);
1531
+ const before = size ? font.slice(0, size.index) : "";
1532
+ const after = size ? font.slice(size.index) : font;
1533
+ if (BOLD_FAMILIES.some((f) => after.includes(f)) && !/\b(bold|bolder|[1-9]00)\b/.test(before)) out = `bold ${out}`;
1534
+ }
1535
+ if (this.memo.size > 2e3) this.memo.clear();
1536
+ this.memo.set(font, out);
1537
+ }
1538
+ return out;
1539
+ }
1540
+ };
1541
+ var SET = Symbol("kiosko.fontSet");
1542
+ var GOT = Symbol("kiosko.fontGot");
1543
+ function hookFont(proto, apply) {
1544
+ const desc = Object.getOwnPropertyDescriptor(proto, "font");
1545
+ if (!desc?.set || !desc.get || !desc.configurable) return null;
1546
+ const { get, set } = desc;
1547
+ Object.defineProperty(proto, "font", {
1548
+ configurable: true,
1549
+ enumerable: desc.enumerable ?? false,
1550
+ get() {
1551
+ const now = get.call(this);
1552
+ return now === this[GOT] ? this[SET] : now;
1553
+ },
1554
+ set(value) {
1555
+ const before = get.call(this);
1556
+ set.call(this, apply(String(value)));
1557
+ const after = get.call(this);
1558
+ if (after !== before || this[GOT] === void 0 || this[SET] === String(value)) {
1559
+ this[SET] = String(value);
1560
+ this[GOT] = after;
1561
+ }
1562
+ }
1563
+ });
1564
+ return desc;
1565
+ }
1566
+
1567
+ // packages/core/src/fonts.ts
1568
+ var require2 = createRequire2(import.meta.url);
1569
+ var done = false;
1570
+ function ttfDir() {
1571
+ try {
1572
+ return join3(dirname(require2.resolve("dejavu-fonts-ttf/package.json")), "ttf");
1573
+ } catch {
1574
+ return null;
1575
+ }
1576
+ }
1577
+ var FILES = [
1578
+ [FONT_FAMILIES.sans, "DejaVuSansCondensed.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansCondensed.ttf"],
1579
+ [FONT_FAMILIES.sansBold, "DejaVuSansCondensed-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansCondensed-Bold.ttf"],
1580
+ [FONT_FAMILIES.mono, "DejaVuSansMono.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"],
1581
+ [FONT_FAMILIES.monoBold, "DejaVuSansMono-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"]
1582
+ ];
1583
+ function registerFonts(extra = []) {
1584
+ if (done && !extra.length) return;
1585
+ if (!done) {
1586
+ const dir = ttfDir();
1587
+ for (const [family, file, fallback2] of FILES) {
1588
+ const p = dir && existsSync2(join3(dir, file)) ? join3(dir, file) : fallback2;
1589
+ if (existsSync2(p)) GlobalFonts2.registerFromPath(p, family);
1590
+ }
1591
+ installFallbackHook();
1592
+ }
1593
+ for (const f of extra) if (existsSync2(f.path)) GlobalFonts2.registerFromPath(f.path, f.family);
1594
+ done = true;
1595
+ }
1596
+ var PROBE = "\u9AD4";
1597
+ var missingPixels = /* @__PURE__ */ new Map();
1598
+ var available = /* @__PURE__ */ new Map();
1599
+ var probeCanvas = null;
1600
+ function pixelsOf(font, probe = PROBE) {
1601
+ probeCanvas ??= createCanvas4(40, 40);
1602
+ const g = probeCanvas.getContext("2d");
1603
+ g.clearRect(0, 0, 40, 40);
1604
+ if (nativeFont?.set) nativeFont.set.call(g, font);
1605
+ else g.font = font;
1606
+ g.fillStyle = "#000";
1607
+ g.textBaseline = "top";
1608
+ g.fillText(probe, 4, 4);
1609
+ return Buffer.from(g.getImageData(0, 0, 40, 40).data.buffer).toString("base64");
1610
+ }
1611
+ function hasFontFamily(family, probe = PROBE) {
1612
+ const key = `${family}\0${probe}`;
1613
+ let yes = available.get(key);
1614
+ if (yes === void 0) {
1615
+ let missing = missingPixels.get(probe);
1616
+ if (missing === void 0) missingPixels.set(probe, missing = pixelsOf('28px "Kiosko Missing Font"', probe));
1617
+ yes = pixelsOf(`28px "${family.replace(/"/g, "")}"`, probe) !== missing;
1618
+ available.set(key, yes);
1619
+ }
1620
+ return yes;
1621
+ }
1622
+ var userFamilies = null;
1623
+ function loadUserFonts() {
1624
+ if (userFamilies) return userFamilies;
1625
+ userFamilies = [];
1626
+ const dir = join3(paths.home, "fonts");
1627
+ if (!existsSync2(dir)) return userFamilies;
1628
+ const before = new Set(GlobalFonts2.families.map((f) => f.family));
1629
+ let files = [];
1630
+ try {
1631
+ files = readdirSync(dir).filter((f) => /\.(otf|ttf|ttc|woff2?)$/i.test(f));
1632
+ } catch {
1633
+ return userFamilies;
1634
+ }
1635
+ for (const f of files.sort()) GlobalFonts2.registerFromPath(join3(dir, f));
1636
+ userFamilies = GlobalFonts2.families.map((f) => f.family).filter((f) => !before.has(f));
1637
+ return userFamilies;
1638
+ }
1639
+ var chosen = /* @__PURE__ */ new Map();
1640
+ function cjkFonts(locale) {
1641
+ const script = hanScript(locale);
1642
+ const key = script ?? "-";
1643
+ let out = chosen.get(key);
1644
+ if (!out) {
1645
+ const fromUser = loadUserFonts().filter((f) => hasFontFamily(f));
1646
+ const families = cjkFamiliesFor(locale, hasFontFamily, fromUser);
1647
+ out = { script, families, fromUser };
1648
+ chosen.set(key, out);
1649
+ }
1650
+ return out;
1651
+ }
1652
+ var fallback = new FontFallback();
1653
+ function setFontLocale(locale) {
1654
+ if (fallback.setFamilies([.../* @__PURE__ */ new Set([...cjkFonts(locale).families, ...otherScriptFonts().map((f) => f.family)])])) clearTextCache();
1655
+ }
1656
+ var others = null;
1657
+ function otherScriptFonts() {
1658
+ if (!others) {
1659
+ registerFonts();
1660
+ others = [];
1661
+ for (const o of OTHER_SCRIPTS) {
1662
+ const family = o.families.find((f) => hasFontFamily(f, o.probe));
1663
+ if (family) others.push({ script: o.script, family });
1664
+ }
1665
+ }
1666
+ return others;
1667
+ }
1668
+ function withFallback(font) {
1669
+ return fallback.apply(font);
1670
+ }
1671
+ var nativeFont = null;
1672
+ function installFallbackHook() {
1673
+ if (nativeFont) return;
1674
+ nativeFont = hookFont(Object.getPrototypeOf(createCanvas4(1, 1).getContext("2d")), withFallback);
1675
+ }
1676
+
1677
+ // packages/core/src/compositor.ts
1678
+ var images = /* @__PURE__ */ new Map();
1679
+ function backgroundImage(path) {
1680
+ if (!images.has(path)) {
1681
+ images.set(path, null);
1682
+ loadImage3(path).then((img) => images.set(path, img)).catch(() => void 0);
1683
+ }
1684
+ return images.get(path) ?? null;
1685
+ }
1686
+ function resolve(input, inst) {
1687
+ const def = input.registry.widget(inst.type);
1688
+ if (!def) return null;
1689
+ let options = def.options ? validate(def.options, inst.options).value : {};
1690
+ let data = input.dataOf(inst);
1691
+ let sources = input.sourcesOf(def.sources);
1692
+ if (input.demo && def.demo) {
1693
+ const needData = data === void 0;
1694
+ const needSources = (def.sources ?? []).some((s) => sources[s] === void 0);
1695
+ if (needData || needSources || input.demoOptions) {
1696
+ try {
1697
+ const d = def.demo({ options, now: input.now, locale: resolveLocale(input.cfg) });
1698
+ if (input.demoOptions && d.options && def.options) options = validate(def.options, { ...d.options, ...inst.options }).value;
1699
+ if (needData) data = d.data;
1700
+ if (needSources) sources = { ...d.sources ?? {}, ...Object.fromEntries(Object.entries(sources).filter(([, v]) => v !== void 0)) };
1701
+ } catch {
1702
+ }
1703
+ }
1704
+ }
1705
+ return { inst, def, options, data, sources };
1706
+ }
1707
+ function stateCtx(r, now, working, cfg) {
1708
+ return { options: r.options, data: r.data, sources: r.sources, now, working, workday: cfg.workday, ...cfg.location ? { location: cfg.location } : {} };
1709
+ }
1710
+ function tileState(def, inst, state) {
1711
+ const takeOver = inst.takeOver ?? def.takeOver ?? true;
1712
+ const hideEmpty = inst.hideWhenEmpty ?? def.hideWhenEmpty ?? false;
1713
+ const visible = safe(() => def.visible?.(state) ?? true, true) && !(hideEmpty && def.empty && safe(() => def.empty(state), false));
1714
+ const urgent = takeOver && safe(() => def.urgent?.(state) ?? false, false);
1715
+ return { visible, urgent };
1716
+ }
1717
+ function safe(fn, fallback2) {
1718
+ if (!fn) return fallback2;
1719
+ try {
1720
+ return fn();
1721
+ } catch {
1722
+ return fallback2;
1723
+ }
1724
+ }
1725
+ function redrawStep(def, state) {
1726
+ const r = (typeof def.redraw === "function" ? safe(() => def.redraw(state), "never") : def.redraw) ?? "never";
1727
+ if (r === "never") return 0;
1728
+ return r === "second" ? 1e3 : r === "minute" ? 6e4 : Math.max(250, r.everyMs);
1729
+ }
1730
+ function fitText(g, text2, maxW) {
1731
+ if (g.measureText(text2).width <= maxW) return text2;
1732
+ const chars = [...text2];
1733
+ let lo = 0;
1734
+ let hi = chars.length;
1735
+ while (lo < hi) {
1736
+ const mid = Math.ceil((lo + hi) / 2);
1737
+ if (g.measureText(`${chars.slice(0, mid).join("").trimEnd()}\u2026`).width <= maxW) lo = mid;
1738
+ else hi = mid - 1;
1739
+ }
1740
+ return lo > 0 ? `${chars.slice(0, lo).join("").trimEnd()}\u2026` : "\u2026";
1741
+ }
1742
+ function roundRect(g, x, y, w, h, r) {
1743
+ g.beginPath();
1744
+ g.roundRect(x, y, w, h, Math.max(0, Math.min(r, w / 2, h / 2)));
1745
+ }
1746
+ function chromeMetrics(theme, screenH, rect) {
1747
+ const scale = Math.max(0.45, Math.min(1, screenH / 462, rect.h / 180));
1748
+ const pad = Math.round(16 * scale);
1749
+ const title = Math.round(theme.titleSize * scale);
1750
+ return { pad, title, titleBar: Math.round(title * 1.55) };
1751
+ }
1752
+ function drawCard(g, rect, theme) {
1753
+ roundRect(g, rect.x, rect.y, rect.w, rect.h, theme.radius);
1754
+ g.fillStyle = theme.colors.surface;
1755
+ g.fill();
1756
+ g.strokeStyle = theme.colors.surfaceEdge;
1757
+ g.lineWidth = 1;
1758
+ roundRect(g, rect.x + 0.5, rect.y + 0.5, rect.w - 1, rect.h - 1, theme.radius);
1759
+ g.stroke();
1760
+ }
1761
+ function paintTile(g, input, tile, rect, out, nextAt, idles, animatable) {
1762
+ const { theme, now, working } = input;
1763
+ const candidates = tile.widgets.filter((w) => !w.disabled && whenMatches(w.when, working)).map((w) => resolve(input, w)).filter((r2) => !!r2);
1764
+ const entries = candidates.map((r2) => ({ id: r2.inst.id, ...tileState(r2.def, r2.inst, stateCtx(r2, now, working, input.cfg)) }));
1765
+ const forced = input.forceShown?.[tile.id];
1766
+ const shownId = forced && candidates.some((c) => c.inst.id === forced) ? forced : pickInStack(entries, now, tile.rotateMs);
1767
+ if (entries.filter((e) => e.visible).length > 1 && !forced) nextAt.v = Math.min(nextAt.v, nextTurnAt(now, tile.rotateMs));
1768
+ out.shown = shownId;
1769
+ const r = candidates.find((c) => c.inst.id === shownId);
1770
+ const chrome = tile.chrome === "auto" ? r?.def.chrome ?? "card" : tile.chrome;
1771
+ if (!r) {
1772
+ if (chrome === "card") drawCard(g, rect, theme);
1773
+ if (input.preview && !tile.widgets.length) {
1774
+ g.setLineDash([6, 6]);
1775
+ g.strokeStyle = theme.colors.inkFaint;
1776
+ roundRect(g, rect.x + 1, rect.y + 1, rect.w - 2, rect.h - 2, theme.radius);
1777
+ g.stroke();
1778
+ g.setLineDash([]);
1779
+ }
1780
+ return;
1781
+ }
1782
+ const state = stateCtx(r, now, working, input.cfg);
1783
+ idles.push(safe(() => r.def.idle?.(state) ?? false, false));
1784
+ const step = redrawStep(r.def, state);
1785
+ if (step) nextAt.v = Math.min(nextAt.v, (Math.floor(now / step) + 1) * step);
1786
+ const animation = r.def.animation;
1787
+ if (animation && !input.preview) {
1788
+ animatable.push({
1789
+ tileId: tile.id,
1790
+ instanceId: r.inst.id,
1791
+ type: r.inst.type,
1792
+ def: r.def,
1793
+ data: r.data,
1794
+ sources: r.sources,
1795
+ ended: (plan, completed) => {
1796
+ const [plugin] = r.inst.type.split("/");
1797
+ safe(() => r.def.animationEnded?.({ ...baseContext(input.cfg, plugin, input.log ?? (() => void 0), input.now), options: r.options, plan, completed, data: r.data }), void 0);
1798
+ },
1799
+ ask: (trigger, rnd, prev) => safe(() => animation({ ...state, box: tileBoxes(theme, input.screen.height, r.inst, rect, chrome, input.screen.textScale).box, trigger, rnd, ...prev !== void 0 ? { prev } : {} }), null)
1800
+ });
1801
+ }
1802
+ const frame = input.animate?.find((a) => a.tileId === tile.id && a.instanceId === r.inst.id)?.frame;
1803
+ const draw = (tg2) => drawTileContent(tg2, input, r, rect, chrome, out, frame);
1804
+ if (frame || !input.cache) {
1805
+ draw(g);
1806
+ return;
1807
+ }
1808
+ const cfg = input.cfg;
1809
+ const key = JSON.stringify([r.inst.id, r.inst.type, r.inst.options, r.inst.title ?? "", zoomOf(r.inst), input.screen.textScale ?? 1, legibleCjkPx(input.screen), chrome, rect, theme.id, step ? Math.floor(now / step) : 0, cfg.locale, cfg.timeFormat, cfg.workday, cfg.location ?? null, working]);
1810
+ const refs = [r.data, ...(r.def.sources ?? []).map((s) => r.sources[s])];
1811
+ const hit = input.cache.get(tile.id);
1812
+ if (hit && hit.key === key && hit.refs.length === refs.length && hit.refs.every((x, i) => x === refs[i])) {
1813
+ g.drawImage(hit.canvas, rect.x, rect.y);
1814
+ if (hit.error) out.error = hit.error;
1815
+ return;
1816
+ }
1817
+ const canvas = createCanvas5(rect.w, rect.h);
1818
+ const tg = canvas.getContext("2d");
1819
+ tg.translate(-rect.x, -rect.y);
1820
+ draw(tg);
1821
+ g.drawImage(canvas, rect.x, rect.y);
1822
+ input.cache.set(tile.id, { key, refs, canvas, ...out.error ? { error: out.error } : {} });
1823
+ }
1824
+ function tileBoxes(theme, screenH, inst, rect, chrome, textScale = 1) {
1825
+ const m = chromeMetrics(theme, screenH, rect);
1826
+ const pad = chrome === "card" ? m.pad : 0;
1827
+ const top = rect.y + pad + (inst.title?.trim() && chrome === "card" ? m.titleBar : 0);
1828
+ const outer = { x: rect.x + pad, y: top, w: Math.max(1, rect.w - 2 * pad), h: Math.max(1, rect.y + rect.h - pad - top) };
1829
+ const zoom = Math.round(zoomOf(inst) * textScale * 100) / 100;
1830
+ const box = zoom === 1 ? outer : { x: outer.x, y: outer.y, w: Math.max(1, outer.w / zoom), h: Math.max(1, outer.h / zoom) };
1831
+ return { outer, box, zoom };
1832
+ }
1833
+ function drawTileContent(g, input, r, rect, chrome, out, anim) {
1834
+ const { theme, now, working } = input;
1835
+ const m = chromeMetrics(theme, input.screen.height, rect);
1836
+ if (chrome === "card") drawCard(g, rect, theme);
1837
+ const pad = chrome === "card" ? m.pad : 0;
1838
+ const title = r.inst.title?.trim();
1839
+ if (title && chrome === "card") {
1840
+ g.font = `${m.title}px "${theme.fonts.sans}"`;
1841
+ g.fillStyle = theme.colors.inkDim;
1842
+ g.textBaseline = "alphabetic";
1843
+ g.fillText(fitText(g, title, rect.w - 2 * pad), rect.x + pad, rect.y + pad + m.title * 0.8);
1844
+ }
1845
+ const { outer, box, zoom } = tileBoxes(theme, input.screen.height, r.inst, rect, chrome, input.screen.textScale);
1846
+ const [plugin] = r.inst.type.split("/");
1847
+ const ctx = {
1848
+ ...baseContext(input.cfg, plugin, input.log ?? (() => void 0), now),
1849
+ ...stateCtx(r, now, working, input.cfg),
1850
+ box,
1851
+ theme,
1852
+ fonts: theme.fonts,
1853
+ kit: src_exports,
1854
+ canvas: CANVAS,
1855
+ preview: !!input.preview,
1856
+ ...anim ? { anim, frame: anim.i } : {}
1857
+ };
1858
+ g.save();
1859
+ roundRect(g, rect.x, rect.y, rect.w, rect.h, chrome === "card" ? theme.radius : 0);
1860
+ g.clip();
1861
+ if (zoom !== 1) {
1862
+ g.translate(outer.x * (1 - zoom), outer.y * (1 - zoom));
1863
+ g.scale(zoom, zoom);
1864
+ }
1865
+ const t0 = performance.now();
1866
+ try {
1867
+ src_exports.takeCjkEnlarged();
1868
+ r.def.render(g, ctx);
1869
+ out.renderMs = performance.now() - t0;
1870
+ const small = src_exports.takeCjkEnlarged();
1871
+ if (small !== null) out.cjkEnlarged = small;
1872
+ } catch (err) {
1873
+ out.error = errorMessage(err, ctx.locale);
1874
+ input.log?.(r.inst.type, `render failed: ${out.error}`);
1875
+ const size = Math.max(12, Math.min(20, box.h / 4));
1876
+ src_exports.drawTracked(g, src_exports.truncate(g, `\u26A0 ${localize(r.def.name, ctx.locale)}: ${out.error}`, box.w, { size, family: theme.fonts.mono }), box.x, box.y + size * 1.2, { size, family: theme.fonts.mono, color: theme.colors.alert });
1877
+ }
1878
+ g.restore();
1879
+ }
1880
+ function composePage(input) {
1881
+ registerFonts();
1882
+ setFontLocale(resolveLocale(input.cfg));
1883
+ src_exports.setMinCjkPx(legibleCjkPx(input.screen));
1884
+ const { screen, page, theme, now } = input;
1885
+ const rotate = ((input.rotate ?? 0) % 360 + 360) % 360;
1886
+ const swap = rotate === 90 || rotate === 270;
1887
+ const canvas = createCanvas5(swap ? screen.height : screen.width, swap ? screen.width : screen.height);
1888
+ const g = canvas.getContext("2d");
1889
+ if (rotate) {
1890
+ g.translate(canvas.width / 2, canvas.height / 2);
1891
+ g.rotate(rotate * Math.PI / 180);
1892
+ g.translate(-screen.width / 2, -screen.height / 2);
1893
+ }
1894
+ g.fillStyle = page.background.color || theme.colors.bg;
1895
+ g.fillRect(0, 0, screen.width, screen.height);
1896
+ if (page.background.image) {
1897
+ const img = backgroundImage(page.background.image);
1898
+ if (img) {
1899
+ const s = Math.max(screen.width / img.width, screen.height / img.height);
1900
+ g.drawImage(img, (screen.width - img.width * s) / 2, (screen.height - img.height * s) / 2, img.width * s, img.height * s);
1901
+ }
1902
+ }
1903
+ const shift = input.noShift || input.preview ? { x: 0, y: 0 } : pixelShift(now, screen.pixelShift);
1904
+ g.save();
1905
+ g.translate(shift.x, shift.y);
1906
+ const nextAt = { v: Infinity };
1907
+ const idles = [];
1908
+ const tiles = [];
1909
+ const animatable = [];
1910
+ for (const tile of page.tiles) {
1911
+ const rect = toPx(tile, page.grid, screen.width, screen.height);
1912
+ const out = { id: tile.id, rect, shown: null };
1913
+ tiles.push(out);
1914
+ paintTile(g, input, tile, rect, out, nextAt, idles, animatable);
1915
+ }
1916
+ if (input.cache) {
1917
+ for (const id of input.cache.keys()) if (!page.tiles.some((t2) => t2.id === id)) input.cache.delete(id);
1918
+ }
1919
+ g.restore();
1920
+ if (screen.pixelShift.enabled && !input.preview) nextAt.v = Math.min(nextAt.v, (Math.floor(now / screen.pixelShift.periodMs) + 1) * screen.pixelShift.periodMs);
1921
+ return { canvas, tiles, idle: idles.length > 0 && idles.every(Boolean), nextAt: nextAt.v, animatable };
1922
+ }
1923
+ function rotateCanvas(src, rotate) {
1924
+ if (!rotate) return src;
1925
+ const swap = rotate === 90 || rotate === 270;
1926
+ const out = createCanvas5(swap ? src.height : src.width, swap ? src.width : src.height);
1927
+ const g = out.getContext("2d");
1928
+ g.translate(out.width / 2, out.height / 2);
1929
+ g.rotate(rotate * Math.PI / 180);
1930
+ g.drawImage(src, -src.width / 2, -src.height / 2);
1931
+ return out;
1932
+ }
1933
+
1934
+ // packages/core/src/animation.ts
1935
+ var MAX_FRAMES = 600;
1936
+ var MAX_CONCURRENT = 1;
1937
+ var DEFAULT_GAP = { minMs: 2e4, maxMs: 6e4 };
1938
+ function checkPlan(plan, maxFps) {
1939
+ const p = plan;
1940
+ if (!p || typeof p !== "object") return "not an object";
1941
+ if (typeof p.id !== "string" || !p.id) return "no id";
1942
+ if (!Number.isInteger(p.frames) || p.frames < 3) return `frames must be an integer of at least 3 (got ${String(p.frames)})`;
1943
+ if (p.frames > MAX_FRAMES) return `too many frames (${p.frames}, at most ${MAX_FRAMES})`;
1944
+ if (typeof p.fps !== "number" || !(p.fps > 0)) return `fps must be positive (got ${String(p.fps)})`;
1945
+ const frames = p.frames;
1946
+ const hold = p.hold && Number.isFinite(p.hold.at) && p.hold.ms > 0 ? { index: Math.max(1, Math.min(frames - 2, Math.round(p.hold.at * (frames - 1)))), ms: p.hold.ms } : void 0;
1947
+ return { plan: p, frames, fps: Math.max(1, Math.min(p.fps, maxFps)), interruptible: p.interruptible !== false, ...hold ? { hold } : {} };
1948
+ }
1949
+ var AnimationScheduler = class {
1950
+ memory = /* @__PURE__ */ new Map();
1951
+ rnd;
1952
+ onInvalid;
1953
+ constructor(rnd = Math.random, onInvalid = () => void 0) {
1954
+ this.rnd = rnd;
1955
+ this.onInvalid = onInvalid;
1956
+ }
1957
+ gapAfter(a, now) {
1958
+ const g = a.def.animationGap ?? DEFAULT_GAP;
1959
+ const min = Math.max(0, g.minMs), max = Math.max(min, g.maxMs);
1960
+ return now + min + this.rnd() * (max - min);
1961
+ }
1962
+ /**
1963
+ * The animations to play now, up to `limit`, among the shown widgets that
1964
+ * have one. Call it only while nothing is playing. A widget seen for the
1965
+ * first time isn't asked: starting up must not set off a gesture. When more
1966
+ * are due than fit, the one that has waited longest goes first (the order
1967
+ * of the page doesn't decide), so none starves.
1968
+ */
1969
+ next(list2, now, maxFps, limit = MAX_CONCURRENT) {
1970
+ const seen = /* @__PURE__ */ new Set();
1971
+ const due = [];
1972
+ for (const a of list2) {
1973
+ seen.add(a.instanceId);
1974
+ const m = this.memory.get(a.instanceId);
1975
+ if (!m) {
1976
+ this.memory.set(a.instanceId, { data: a.data, sources: a.sources, nextIdleAt: this.gapAfter(a, now), endedAt: -Infinity, dueSince: Infinity });
1977
+ continue;
1978
+ }
1979
+ const changed = a.data !== m.data || Object.keys(a.sources).some((k) => a.sources[k] !== m.sources[k]);
1980
+ const prev = m.pending ?? { data: m.data, sources: m.sources };
1981
+ m.data = a.data;
1982
+ m.sources = a.sources;
1983
+ if ((changed || m.pending) && now - m.endedAt >= (a.def.animationCooldownMs ?? 0)) {
1984
+ m.pending = prev;
1985
+ due.push({ a, m, trigger: "data", prev });
1986
+ } else if (now >= m.nextIdleAt) due.push({ a, m, trigger: "idle", prev });
1987
+ }
1988
+ for (const id of this.memory.keys()) if (!seen.has(id)) this.memory.delete(id);
1989
+ for (const d of due) d.m.dueSince = Math.min(d.m.dueSince, d.trigger === "data" ? now : d.m.nextIdleAt);
1990
+ due.sort((x, y) => x.m.dueSince - y.m.dueSince);
1991
+ const out = [];
1992
+ for (const { a, m, trigger, prev } of due) {
1993
+ if (out.length >= limit) break;
1994
+ if (trigger === "idle") m.nextIdleAt = this.gapAfter(a, now);
1995
+ else m.pending = void 0;
1996
+ const plan = a.ask(trigger, this.rnd, trigger === "data" ? prev : void 0);
1997
+ if (plan === null) {
1998
+ m.dueSince = Infinity;
1999
+ continue;
2000
+ }
2001
+ const ok = checkPlan(plan, maxFps);
2002
+ if (typeof ok === "string") {
2003
+ this.onInvalid(a.type, ok);
2004
+ m.dueSince = Infinity;
2005
+ continue;
2006
+ }
2007
+ out.push({ animatable: a, play: ok });
2008
+ }
2009
+ return out;
2010
+ }
2011
+ /** An animation of `instanceId` has just ended (or was cut): its cooldown starts. */
2012
+ ended(instanceId, now, a) {
2013
+ const m = this.memory.get(instanceId);
2014
+ if (!m) return;
2015
+ m.endedAt = now;
2016
+ m.dueSince = Infinity;
2017
+ if (a) m.nextIdleAt = Math.max(m.nextIdleAt, this.gapAfter(a, now));
2018
+ }
2019
+ };
2020
+
2021
+ // packages/core/src/alerts.ts
2022
+ var DEFAULT_SNOOZE_MS = 10 * 6e4;
2023
+
2024
+ // packages/core/src/data.ts
2025
+ var DEFAULT_FETCH_MS = 10 * 6e4;
2026
+
2027
+ // packages/core/src/devices.ts
2028
+ function encodeFor(device, jpegQuality) {
2029
+ if (device.driver === "file") return device.format ?? "jpeg";
2030
+ if (device.driver === "usb") return "jpeg";
2031
+ return jpegQuality > 0 ? "jpeg" : "png";
2032
+ }
2033
+
2034
+ // packages/core/src/alert-paint.ts
2035
+ import { Path2D } from "@napi-rs/canvas";
2036
+ var FLASH_MS = 1e4;
2037
+ var PULSE_MS = 4e3;
2038
+ var MAX_FRAME_AREA = 0.16;
2039
+ var LEVEL_COLORS = {
2040
+ info: { color: "#38bdf8", bg: "#04101a" },
2041
+ warn: { color: "#f59e0b", bg: "#160f02" },
2042
+ critical: { color: "#ef4444", bg: "#190405" }
2043
+ };
2044
+ function alertStepMs(maxFps) {
2045
+ return Math.max(500, Math.ceil(1e3 / Math.max(1, maxFps || 1)));
2046
+ }
2047
+ function alertIntensity(level, elapsed, step) {
2048
+ const k = Math.floor(Math.max(0, elapsed) / step);
2049
+ if (level !== "info" && elapsed < FLASH_MS) return k % 2 === 0 ? 1 : 0.15;
2050
+ const t2 = k * step % PULSE_MS / PULSE_MS;
2051
+ const depth = level === "info" ? 0.3 : 0.45;
2052
+ return Math.round((1 - depth * (0.5 - 0.5 * Math.cos(2 * Math.PI * t2))) * 100) / 100;
2053
+ }
2054
+ function frameWidth(w, h) {
2055
+ const want = Math.max(4, Math.round(Math.min(w, h) * 0.055));
2056
+ const cap = Math.floor(MAX_FRAME_AREA * w * h / (2 * (w + h)));
2057
+ return Math.max(2, Math.min(want, cap));
2058
+ }
2059
+ var circle = (cx, cy, r) => `M${cx - r} ${cy}a${r} ${r} 0 1 0 ${2 * r} 0a${r} ${r} 0 1 0 ${-2 * r} 0`;
2060
+ var ALERT_ICONS = {
2061
+ "triangle-alert": ["m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3", "M12 9v4", "M12 17h.01"],
2062
+ "octagon-alert": ["M12 16h.01", "M12 8v4", "M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z"],
2063
+ info: [circle(12, 12, 10), "M12 16v-4", "M12 8h.01"],
2064
+ bell: ["M10.268 21a2 2 0 0 0 3.464 0", "M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"],
2065
+ "bell-ring": ["M10.268 21a2 2 0 0 0 3.464 0", "M22 8c0-2.3-.8-4.3-2-6", "M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326", "M4 2C2.8 3.7 2 5.7 2 8"],
2066
+ flame: ["M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4"],
2067
+ droplet: ["M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z"],
2068
+ phone: ["M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"],
2069
+ "phone-incoming": ["M16 2v6h6", "m22 2-6 6", "M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"],
2070
+ activity: ["M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"],
2071
+ zap: ["M15.914 4a1.5 1.5 0 00-2.474-1.561l-9 9A1.5 1.5 0 005.5 14h4.002a.5.5 0 01.471.666L8.086 20a1.5 1.5 0 002.475 1.56l9-9A1.5 1.5 0 0018.5 10h-3.997a.5.5 0 01-.472-.667z"],
2072
+ "cloud-lightning": ["M6 16.326A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 .5 8.973", "m13 12-3 5h4l-3 5"],
2073
+ wind: ["M12.8 19.6A2 2 0 1 0 14 16H2", "M17.5 8a2.5 2.5 0 1 1 2 4H2", "M9.8 4.4A2 2 0 1 1 11 8H2"],
2074
+ waves: ["M2 12q2.5 2 5 0t5 0 5 0 5 0", "M2 19q2.5 2 5 0t5 0 5 0 5 0", "M2 5q2.5 2 5 0t5 0 5 0 5 0"],
2075
+ thermometer: ["M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z"],
2076
+ siren: ["M7 18v-6a5 5 0 1 1 10 0v6", "M5 21a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2z", "M21 12h1", "M18.5 4.5 18 5", "M2 12h1", "M12 2v1", "m4.929 4.929.707.707", "M12 12v6"],
2077
+ "shield-alert": ["M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z", "M12 8v4", "M12 16h.01"],
2078
+ "door-open": ["M10 21H2", "M10 3H7a2 2 0 00-2 2v16", "M14 12h.01", "M19 21V5a2 2 0 00-1.675-1.974l-6.163-1.013A1 1 0 0010 3v18a1 1 0 001.124.992z", "M22 21h-3"],
2079
+ "git-branch": ["M15 6a9 9 0 0 0-9 9V3", circle(18, 6, 3), circle(6, 18, 3)],
2080
+ "circle-x": [circle(12, 12, 10), "m15 9-6 6", "m9 9 6 6"],
2081
+ bug: ["M12 20v-9", "M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z", "M14.12 3.88 16 2", "M21 21a4 4 0 0 0-3.81-4", "M21 5a4 4 0 0 1-3.55 3.97", "M22 13h-4", "M3 21a4 4 0 0 1 3.81-4", "M3 5a4 4 0 0 0 3.55 3.97", "M6 13H2", "m8 2 1.88 1.88", "M9 7.13V6a3 3 0 1 1 6 0v1.13"],
2082
+ mail: ["m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7", "M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"]
2083
+ };
2084
+ var paths2 = /* @__PURE__ */ new Map();
2085
+ function iconPaths(name) {
2086
+ const d = ALERT_ICONS[name];
2087
+ if (!d) return null;
2088
+ let p = paths2.get(name);
2089
+ if (!p) paths2.set(name, p = d.map((x) => new Path2D(x)));
2090
+ return p;
2091
+ }
2092
+ function iconFor(a) {
2093
+ const icon = a.icon?.trim();
2094
+ if (icon && ALERT_ICONS[icon]) return { path: icon };
2095
+ if (icon && [...icon].length <= 2 && !/^[a-z-]+$/.test(icon)) return { glyph: icon };
2096
+ return { path: a.level === "info" ? "info" : a.level === "critical" ? "octagon-alert" : "triangle-alert" };
2097
+ }
2098
+ function drawIcon(g, a, x, y, size, color, family) {
2099
+ const which = iconFor(a);
2100
+ g.save();
2101
+ if ("glyph" in which) {
2102
+ drawTracked(g, which.glyph, x + size / 2, y + size * 0.82, { size: Math.round(size * 0.86), family, color, align: "center" });
2103
+ } else {
2104
+ g.translate(x, y);
2105
+ g.scale(size / 24, size / 24);
2106
+ g.strokeStyle = color;
2107
+ g.lineWidth = 2;
2108
+ g.lineCap = "round";
2109
+ g.lineJoin = "round";
2110
+ for (const p of iconPaths(which.path)) g.stroke(p);
2111
+ }
2112
+ g.restore();
2113
+ }
2114
+ var mixHex = (a, b, t2) => css(mix(hex(a), hex(b), clamp2(t2)));
2115
+ function paintAlert(g, w, h, shown, o) {
2116
+ const a = shown.top;
2117
+ const { color, bg } = LEVEL_COLORS[a.level];
2118
+ g.save();
2119
+ g.fillStyle = bg;
2120
+ g.fillRect(0, 0, w, h);
2121
+ const b = frameWidth(w, h);
2122
+ g.fillStyle = mixHex(bg, color, 0.12 + 0.88 * o.intensity);
2123
+ g.fillRect(0, 0, w, b);
2124
+ g.fillRect(0, h - b, w, b);
2125
+ g.fillRect(0, b, b, h - 2 * b);
2126
+ g.fillRect(w - b, b, b, h - 2 * b);
2127
+ const shift = o.shift ?? { x: 0, y: 0 };
2128
+ const pad = Math.round(Math.min(w, h) * 0.07);
2129
+ const box = { x: b + pad + shift.x, y: b + pad + shift.y, w: w - 2 * (b + pad), h: h - 2 * (b + pad) };
2130
+ const minPx = Math.max(12, o.minPx);
2131
+ const bold = o.fonts.sansBold;
2132
+ const regular = o.fonts.sans;
2133
+ const small = Math.max(minPx, Math.round(Math.min(box.h, box.w) * 0.12));
2134
+ let counterW = 0;
2135
+ if (shown.more > 0) {
2136
+ const label = `+${shown.more}`;
2137
+ const tw = measureTracked(g, label, { size: small, family: bold });
2138
+ const ph = Math.round(small * 1.35);
2139
+ counterW = Math.round(tw + small);
2140
+ const cx = box.x + box.w - counterW;
2141
+ g.fillStyle = color;
2142
+ g.beginPath();
2143
+ g.roundRect(cx, box.y, counterW, ph, ph / 2);
2144
+ g.fill();
2145
+ drawTracked(g, label, cx + counterW / 2, box.y + ph * 0.5 + small * 0.36, { size: small, family: bold, color: "#0b0b0b", align: "center" });
2146
+ }
2147
+ let sinceW = 0;
2148
+ const sinceSize = Math.max(minPx, Math.round(small * 0.8));
2149
+ const cornerFont = { size: sinceSize, family: regular, color: mixHex(bg, "#ffffff", 0.62) };
2150
+ const cornerMax = Math.round(box.w * (w / h >= 1.5 ? 0.2 : 0.9));
2151
+ let corner = [a.source && o.sinceText ? `${a.source} \xB7 ${o.sinceText}` : a.source ?? o.sinceText].filter((x) => !!x);
2152
+ if (a.source && o.sinceText && measureTracked(g, corner[0], cornerFont) > cornerMax) corner = [a.source, o.sinceText];
2153
+ corner = corner.map((line) => truncate(g, line, cornerMax, cornerFont));
2154
+ corner.forEach((line, i) => {
2155
+ const y2 = box.y + box.h - (corner.length - 1 - i) * Math.round(sinceSize * 1.2);
2156
+ sinceW = Math.max(sinceW, drawTracked(g, line, box.x + box.w, y2, { ...cornerFont, align: "right" }));
2157
+ });
2158
+ const wide = w / h >= 1.5;
2159
+ let col;
2160
+ const iconSize = Math.round(wide ? Math.min(box.h * 0.78, box.w * 0.2) : Math.min(box.w * 0.4, box.h * 0.3));
2161
+ if (wide) {
2162
+ drawIcon(g, a, box.x, box.y + (box.h - iconSize) / 2, iconSize, color, bold);
2163
+ const gap = Math.round(iconSize * 0.3);
2164
+ const side = Math.max(counterW, sinceW);
2165
+ col = { x: box.x + iconSize + gap, y: box.y, w: box.w - iconSize - gap - (side ? side + gap / 2 : 0), h: box.h };
2166
+ } else {
2167
+ drawIcon(g, a, box.x + (box.w - iconSize) / 2, box.y, iconSize, color, bold);
2168
+ const gap = Math.round(iconSize * 0.15);
2169
+ const below = corner.length ? Math.round(sinceSize * (0.1 + 1.2 * corner.length)) : 0;
2170
+ col = { x: box.x, y: box.y + iconSize + gap, w: box.w, h: box.h - iconSize - gap - below };
2171
+ }
2172
+ const align = wide ? "left" : "center";
2173
+ const ax = wide ? col.x : col.x + col.w / 2;
2174
+ const hasText = !!a.text;
2175
+ const hasDetail = !!a.detail;
2176
+ const lower = hasText && hasDetail ? 2 : hasText || hasDetail ? 1 : 0;
2177
+ let size = Math.round(col.h * [0.55, 0.4, 0.34][lower]);
2178
+ const floor = Math.max(minPx * 2, Math.round(col.h * 0.2));
2179
+ size = fitSize(g, a.title, col.w, { size, family: bold }, floor);
2180
+ let titleLines = [a.title];
2181
+ if (measureTracked(g, a.title, { size, family: bold }) > col.w) {
2182
+ size = Math.max(minPx * 1.5, Math.round(col.h * [0.36, 0.27, 0.24][lower]));
2183
+ titleLines = wrapLines(g, a.title, col.w, 2, { size, family: bold });
2184
+ }
2185
+ const tLine = size * 1.08;
2186
+ const textSize = Math.max(minPx, Math.min(Math.round(size * 0.5), Math.round(size * 0.42 + minPx * 0.4)));
2187
+ const lineH = textSize * 1.25;
2188
+ const gapH = textSize * 0.4;
2189
+ const detailGap = hasText && hasDetail ? textSize * 0.25 : 0;
2190
+ const room = col.h - titleLines.length * tLine - gapH - detailGap;
2191
+ const fits = Math.max(1, Math.min(3, Math.floor(room / lineH)));
2192
+ const font = { size: textSize, family: regular };
2193
+ const textLines = hasText ? wrapLines(g, a.text, col.w, hasDetail ? Math.max(1, fits - 1) : fits, font) : [];
2194
+ const detailLines = hasDetail ? wrapLines(g, a.detail, col.w, fits - textLines.length, font) : [];
2195
+ const lowerLines = textLines.length + detailLines.length;
2196
+ const blockH = titleLines.length * tLine + (lowerLines ? gapH + lowerLines * lineH + (textLines.length && detailLines.length ? detailGap : 0) : 0);
2197
+ let y = col.y + Math.max(0, (col.h - blockH) / 2);
2198
+ for (const line of titleLines) {
2199
+ drawTracked(g, line, ax, y + size * 0.86, { size, family: bold, color: "#ffffff", align });
2200
+ y += tLine;
2201
+ }
2202
+ if (lowerLines) y += gapH;
2203
+ for (const line of textLines) {
2204
+ drawTracked(g, line, ax, y + textSize * 0.95, { ...font, color: "#e4e4e7", align });
2205
+ y += lineH;
2206
+ }
2207
+ if (textLines.length && detailLines.length) y += detailGap;
2208
+ const detailColor = mixHex(color, "#ffffff", 0.45);
2209
+ for (const line of detailLines) {
2210
+ drawTracked(g, line, ax, y + textSize * 0.95, { ...font, color: detailColor, align });
2211
+ y += lineH;
2212
+ }
2213
+ g.restore();
2214
+ }
2215
+
2216
+ // packages/core/src/frame-stats.ts
2217
+ var FPS_WINDOW_MS = 5e3;
2218
+ var round = (ms) => Math.round(ms * 10) / 10;
2219
+ var FrameStats = class {
2220
+ sent = [];
2221
+ paint = 0;
2222
+ encode = 0;
2223
+ frames = 0;
2224
+ /** A frame painted (`paintMs` on this thread) and encoded (`encodeMs` in the thread pool, waiting included). */
2225
+ painted(paintMs, encodeMs) {
2226
+ this.paint = this.frames ? this.paint * 0.9 + paintMs * 0.1 : paintMs;
2227
+ this.encode = this.frames ? this.encode * 0.9 + encodeMs * 0.1 : encodeMs;
2228
+ this.frames++;
2229
+ }
2230
+ /** A frame sent to the panel at `at`. */
2231
+ sentAt(at) {
2232
+ this.sent.push(at);
2233
+ if (this.sent.length > 600) this.sent.splice(0, this.sent.length - 600);
2234
+ }
2235
+ read(now = Date.now()) {
2236
+ const from = now - FPS_WINDOW_MS;
2237
+ while (this.sent.length && this.sent[0] < from) this.sent.shift();
2238
+ return { fps: round(this.sent.length * 1e3 / FPS_WINDOW_MS), paintMs: round(this.paint), encodeMs: round(this.encode), frames: this.frames };
2239
+ }
2240
+ };
2241
+
2242
+ // packages/core/src/screen-runner.ts
2243
+ var TICK_MS = 250;
2244
+ function lazyJpeg(c, turned = 0) {
2245
+ let b = null;
2246
+ return () => b ??= (turned ? rotateCanvas(c, (360 - turned) % 360) : c).toBuffer("image/jpeg", 88);
2247
+ }
2248
+ function encode(c, kind, quality, raster) {
2249
+ const t0 = performance.now();
2250
+ const p = kind === "jpeg" ? c.encode("jpeg", Math.max(1, Math.min(100, quality || 90))) : c.encode("png");
2251
+ if (raster) raster.ms += performance.now() - t0;
2252
+ return p;
2253
+ }
2254
+ var MIN_FIT_QUALITY = 20;
2255
+ async function encodeFit(c, kind, quality, maxBytes, raster) {
2256
+ const q0 = Math.max(1, Math.min(100, quality || 90));
2257
+ let out = await encode(c, kind, q0, raster);
2258
+ if (kind !== "jpeg" || !(maxBytes > 0) || out.length <= maxBytes) return { out, quality: q0, over: false };
2259
+ let q = q0;
2260
+ while (q > MIN_FIT_QUALITY) {
2261
+ q = Math.max(MIN_FIT_QUALITY, q - 10);
2262
+ out = await encode(c, kind, q);
2263
+ if (out.length <= maxBytes) return { out, quality: q, over: false };
2264
+ }
2265
+ return { out, quality: q, over: true };
2266
+ }
2267
+ var kb = (n) => `${Math.round(n / 1e3)} KB`;
2268
+ var ScreenRunner = class {
2269
+ device;
2270
+ deviceKey;
2271
+ last = null;
2272
+ lastInfo = null;
2273
+ dirty = true;
2274
+ nextAt = 0;
2275
+ busy = false;
2276
+ pinned = null;
2277
+ playedSlot = /* @__PURE__ */ new Map();
2278
+ interlude = null;
2279
+ /** The buttons of whoever plays the interlude now (Play page). */
2280
+ pad = null;
2281
+ /** Switched off from outside (Home Assistant, the API): black until switched on. Not saved. */
2282
+ off = false;
2283
+ /** An interlude asked for now (the editor, Home Assistant): played as soon as the screen is free. */
2284
+ wanted = null;
2285
+ wantedPlay = false;
2286
+ /** When `fit` last told the log that frames were shrunk, to say it now and then, not every frame. */
2287
+ fitLoggedAt = 0;
2288
+ /** Instance ids on the current page, to know if a data change concerns us. */
2289
+ visibleIds = /* @__PURE__ */ new Set();
2290
+ sourceTypes = /* @__PURE__ */ new Set();
2291
+ page = null;
2292
+ /** Rendered tiles reused between frames (see compositor's TileCache). */
2293
+ tiles = /* @__PURE__ */ new Map();
2294
+ /** The widgets of the last painted page that can animate, and when to ask them (see animation.ts). */
2295
+ animatable = [];
2296
+ scheduler;
2297
+ /** Set while a widget's animation plays: its widget type. */
2298
+ animating = null;
2299
+ closed = false;
2300
+ /** The alert that has the screen now, over everything (set by the runtime, see `setAlert`). */
2301
+ alert = null;
2302
+ /** When the alert on top came up here: it flashes from then. */
2303
+ alertStart = 0;
2304
+ /** What the last alert frame showed, so an equal one isn't painted again. */
2305
+ alertKey = null;
2306
+ /** Real fps, paint and encode times (see frame-stats.ts). */
2307
+ stats = new FrameStats();
2308
+ screen;
2309
+ rt;
2310
+ /** `device`: one already open for this screen (handed over by a thread that stopped). */
2311
+ constructor(screen, rt, device) {
2312
+ this.screen = screen;
2313
+ this.rt = rt;
2314
+ this.deviceKey = JSON.stringify(screen.device);
2315
+ this.device = device ?? rt.openDevice(screen, (m) => rt.log(`screen:${screen.name}`, m));
2316
+ this.pinned = screen.pinnedPage ?? null;
2317
+ this.scheduler = new AnimationScheduler(() => rt.rnd(), (type, why) => rt.log(type, `animation ignored: ${why}`));
2318
+ }
2319
+ /** Encodes a frame within the screen's `maxBytes`, saying so in the log (at most every 10 min) when it had to shrink it. */
2320
+ async fit(c, kind, quality, screen, paintMs = 0) {
2321
+ const t0 = performance.now();
2322
+ const raster = { ms: 0 };
2323
+ const r = await encodeFit(c, kind, quality, screen.maxBytes, raster);
2324
+ this.stats.painted(paintMs + raster.ms, performance.now() - t0 - raster.ms);
2325
+ if ((r.quality !== Math.max(1, Math.min(100, quality || 90)) || r.over) && Date.now() - this.fitLoggedAt > 10 * 6e4) {
2326
+ this.fitLoggedAt = Date.now();
2327
+ this.rt.log(
2328
+ `screen:${screen.name}`,
2329
+ r.over ? `frames don't fit in ${kb(screen.maxBytes)} even at JPEG quality ${r.quality} (${kb(r.out.length)}); the panel may drop them` : `frames over ${kb(screen.maxBytes)} at quality ${quality}: sent at quality ${r.quality} (${kb(r.out.length)})`
2330
+ );
2331
+ }
2332
+ return r.out;
2333
+ }
2334
+ /** Forgets every painted tile: the next frame is painted from scratch (a plugin's code changed). */
2335
+ invalidate() {
2336
+ this.tiles.clear();
2337
+ this.last = null;
2338
+ this.dirty = true;
2339
+ }
2340
+ reconfigure(screen) {
2341
+ const key = JSON.stringify(screen.device);
2342
+ if (key !== this.deviceKey) {
2343
+ this.device.close();
2344
+ this.device = this.rt.openDevice(screen, (m) => this.rt.log(`screen:${screen.name}`, m));
2345
+ this.deviceKey = key;
2346
+ this.last = null;
2347
+ }
2348
+ if (screen.pinnedPage !== this.screen.pinnedPage) this.pinned = screen.pinnedPage ?? null;
2349
+ this.screen = screen;
2350
+ this.tiles.clear();
2351
+ this.dirty = true;
2352
+ }
2353
+ currentPage(now) {
2354
+ const working = this.rt.working(now);
2355
+ const pages = this.screen.pages.filter((p) => whenMatches(p.when, working));
2356
+ return pickPage(pages, now, this.pinned);
2357
+ }
2358
+ /**
2359
+ * The alert for this screen now (or none). One coming up stops what plays
2360
+ * (an interlude, a game, an animation: they check `alert`) and the next
2361
+ * update paints it; one going away gives the pages back.
2362
+ */
2363
+ setAlert(shown, now) {
2364
+ const was = this.alert;
2365
+ this.alert = shown;
2366
+ if (shown && shown.top.id !== was?.top.id) this.alertStart = now;
2367
+ if (shown && !was && this.interlude) {
2368
+ this.rt.log(`screen:${this.screen.name}`, `${this.interlude.type} stopped: an alert`);
2369
+ this.stopInterlude();
2370
+ }
2371
+ if (!shown && was) {
2372
+ this.alertKey = null;
2373
+ this.last = null;
2374
+ this.dirty = true;
2375
+ }
2376
+ }
2377
+ async update(now) {
2378
+ if (this.busy || !this.screen.enabled) return;
2379
+ this.busy = true;
2380
+ try {
2381
+ if (this.alert) {
2382
+ this.wanted = null;
2383
+ await this.paintAlert(this.alert, now);
2384
+ return;
2385
+ }
2386
+ const asked = this.wanted;
2387
+ const play = this.wantedPlay;
2388
+ this.wanted = null;
2389
+ this.wantedPlay = false;
2390
+ if (!this.off && await this.maybeInterlude(now, asked ?? void 0, play)) return;
2391
+ const page = this.currentPage(now);
2392
+ if (page?.id !== this.page?.id) {
2393
+ this.page = page;
2394
+ this.dirty = true;
2395
+ this.rt.pageChanged();
2396
+ }
2397
+ if (!this.dirty && now < this.nextAt) {
2398
+ await this.maybeAnimate(now);
2399
+ return;
2400
+ }
2401
+ this.dirty = false;
2402
+ await this.paint(page, now);
2403
+ await this.maybeAnimate(now);
2404
+ } catch (err) {
2405
+ this.rt.log(`screen:${this.screen.name}`, `paint failed: ${err instanceof Error ? err.message : String(err)}`);
2406
+ } finally {
2407
+ this.busy = false;
2408
+ }
2409
+ }
2410
+ /** Sends a frame and counts it. */
2411
+ async send(out) {
2412
+ await this.device.send(out);
2413
+ this.stats.sentAt(Date.now());
2414
+ }
2415
+ async paint(page, now) {
2416
+ const { screen } = this;
2417
+ const theme = this.rt.theme();
2418
+ const t0 = performance.now();
2419
+ let result = null;
2420
+ let canvas;
2421
+ if (page && !this.off) {
2422
+ result = composePage({
2423
+ cfg: this.rt.config,
2424
+ screen,
2425
+ page,
2426
+ theme,
2427
+ registry: this.rt.registry,
2428
+ now,
2429
+ working: this.rt.working(now),
2430
+ dataOf: (inst) => this.rt.dataOf(inst.id),
2431
+ sourcesOf: (types) => this.rt.sourcesOf(types),
2432
+ log: this.rt.log,
2433
+ demo: this.rt.demoMode,
2434
+ cache: this.tiles,
2435
+ rotate: screen.rotate
2436
+ });
2437
+ canvas = result.canvas;
2438
+ this.animatable = result.animatable;
2439
+ this.nextAt = Math.min(result.nextAt, now + 6e4);
2440
+ for (const t2 of result.tiles) {
2441
+ if (t2.renderMs === void 0 || !t2.shown) continue;
2442
+ const type = page.tiles.find((x) => x.id === t2.id)?.widgets.find((w) => w.id === t2.shown)?.type ?? "?";
2443
+ this.rt.paintTime(t2.shown, type, t2.renderMs, now);
2444
+ }
2445
+ } else {
2446
+ const swap = screen.rotate === 90 || screen.rotate === 270;
2447
+ canvas = CANVAS.createCanvas(swap ? screen.height : screen.width, swap ? screen.width : screen.height);
2448
+ this.animatable = [];
2449
+ this.nextAt = now + 6e4;
2450
+ }
2451
+ const sleeping = this.off || !!(screen.sleepWhenIdle && result?.idle);
2452
+ if (sleeping || !result) {
2453
+ const g = canvas.getContext("2d");
2454
+ g.save();
2455
+ g.setTransform(1, 0, 0, 1, 0, 0);
2456
+ g.fillStyle = "#000";
2457
+ g.fillRect(0, 0, canvas.width, canvas.height);
2458
+ g.restore();
2459
+ }
2460
+ const kind = encodeFor(screen.device, screen.jpegQuality);
2461
+ const out = await this.fit(canvas, kind, screen.jpegQuality, screen, performance.now() - t0);
2462
+ this.lastInfo = { screenId: screen.id, pageId: page?.id ?? null, at: now, image: lazyJpeg(canvas, screen.rotate), tiles: result?.tiles ?? [], interlude: null, sleeping };
2463
+ this.rt.frame(this.lastInfo);
2464
+ if (this.last?.equals(out)) return;
2465
+ this.last = out;
2466
+ await this.send(out);
2467
+ }
2468
+ /**
2469
+ * A frame of the alert: only when it would differ from the last one (the
2470
+ * frame's brightness steps every half second at most, see alert-paint.ts),
2471
+ * so a flashing alert costs 2 frames a second and no more.
2472
+ */
2473
+ async paintAlert(shown, now) {
2474
+ const { screen } = this;
2475
+ const a = shown.top;
2476
+ const intensity = alertIntensity(a.level, now - this.alertStart, alertStepMs(screen.maxFps));
2477
+ const shift = screen.pixelShift.enabled ? pixelShift(now, screen.pixelShift) : { x: 0, y: 0 };
2478
+ const cfg = this.rt.config;
2479
+ const sinceText = createFormatters({ locale: resolveLocale(cfg), timeFormat: cfg.timeFormat, now }).time(a.since);
2480
+ const minPx = legibleCjkPx(screen);
2481
+ const key = JSON.stringify([a.id, a.level, a.title, a.text, a.source, a.detail, a.icon, shown.more, intensity, shift, sinceText, minPx, screen.width, screen.height, screen.rotate]);
2482
+ if (key === this.alertKey) return;
2483
+ this.alertKey = key;
2484
+ const t0 = performance.now();
2485
+ registerFonts();
2486
+ setFontLocale(resolveLocale(cfg));
2487
+ src_exports.setMinCjkPx(minPx);
2488
+ const canvas = CANVAS.createCanvas(screen.width, screen.height);
2489
+ paintAlert(canvas.getContext("2d"), screen.width, screen.height, shown, { intensity, fonts: this.rt.theme().fonts, minPx, sinceText, shift });
2490
+ const kind = encodeFor(screen.device, screen.jpegQuality || 85);
2491
+ const turned = rotateCanvas(canvas, screen.rotate);
2492
+ const out = await this.fit(turned, kind, screen.jpegQuality || 85, screen, performance.now() - t0);
2493
+ this.lastInfo = { screenId: screen.id, pageId: this.page?.id ?? null, at: now, image: lazyJpeg(canvas), tiles: [], interlude: null, alert: a.id, sleeping: false };
2494
+ this.rt.frame(this.lastInfo);
2495
+ if (this.last?.equals(out)) return;
2496
+ this.last = out;
2497
+ await this.send(out);
2498
+ }
2499
+ /**
2500
+ * Plays an interlude if one is due. Returns true while it played (no normal paint this tick).
2501
+ * `play`: someone plays it from the Play page (an interlude with `input`): it gets their
2502
+ * buttons and lasts while they press them, not `maxSeconds`.
2503
+ */
2504
+ async maybeInterlude(now, force, play = false) {
2505
+ const due = this.screen.interludes.find((s) => {
2506
+ if (force) return s.id === force;
2507
+ if (!s.enabled || s.everyMs < 6e4) return false;
2508
+ const slot = Math.floor(now / s.everyMs);
2509
+ return now - slot * s.everyMs < 6e4 && this.playedSlot.get(s.id) !== slot;
2510
+ });
2511
+ if (!due) return false;
2512
+ this.playedSlot.set(due.id, Math.floor(now / Math.max(1, due.everyMs)));
2513
+ const def = this.rt.registry.interlude(due.type);
2514
+ if (!def) return false;
2515
+ const sources = this.rt.sourcesOf(def.sources);
2516
+ const options = def.options ? validate(def.options, due.options).value : {};
2517
+ if (!force && def.skip?.({ sources, now, options })) {
2518
+ this.rt.log(`screen:${this.screen.name}`, `interlude ${due.type} skipped (busy)`);
2519
+ return false;
2520
+ }
2521
+ const [plugin] = due.type.split("/");
2522
+ const seed = Math.floor(now / Math.max(6e4, due.everyMs));
2523
+ const playing = play && !!def.input;
2524
+ const listeners = /* @__PURE__ */ new Set();
2525
+ let lastPress = Date.now();
2526
+ const input = playing ? { on: (l) => (listeners.add(l), () => void listeners.delete(l)) } : void 0;
2527
+ const player = await def.prepare({ ...baseContext(this.rt.config, plugin, this.rt.log, now), options, width: this.screen.width, height: this.screen.height, seed, theme: this.rt.theme(), canvas: CANVAS, sources, ...input ? { input } : {} });
2528
+ if (!player || !(player.frames > 0)) return false;
2529
+ const fps = Math.max(1, Math.min(def.fps, this.screen.maxFps));
2530
+ const frames = playing ? player.frames : Math.min(player.frames, Math.round(due.maxSeconds * fps));
2531
+ this.interlude = { slotId: due.id, type: due.type, stopAt: playing ? Infinity : now + frames / fps * 1e3, play: playing };
2532
+ if (playing) {
2533
+ lastPress = Date.now();
2534
+ this.pad = {
2535
+ send: (e) => {
2536
+ lastPress = Date.now();
2537
+ for (const l of listeners) {
2538
+ try {
2539
+ l(e);
2540
+ } catch (err) {
2541
+ this.rt.log(due.type, `input failed: ${err instanceof Error ? err.message : String(err)}`);
2542
+ }
2543
+ }
2544
+ }
2545
+ };
2546
+ }
2547
+ this.rt.log(`screen:${this.screen.name}`, playing ? `${due.type} being played (ends after ${this.rt.playIdleMs / 1e3} s without a button)` : `playing ${due.type}: ${frames} frames at ${fps} fps`);
2548
+ const kind = encodeFor(this.screen.device, this.screen.jpegQuality || 85);
2549
+ const canvas = CANVAS.createCanvas(this.screen.width, this.screen.height);
2550
+ const g = canvas.getContext("2d");
2551
+ let start = Date.now();
2552
+ const until = playing ? Infinity : Date.now() + due.maxSeconds * 1e3;
2553
+ for (let i = 0; i < frames && this.interlude && !this.alert; i++) {
2554
+ if (Date.now() >= until) break;
2555
+ if (playing && Date.now() - lastPress > this.rt.playIdleMs) {
2556
+ this.rt.log(`screen:${this.screen.name}`, `${due.type}: nobody playing, back to the pages`);
2557
+ break;
2558
+ }
2559
+ const t0 = performance.now();
2560
+ g.save();
2561
+ try {
2562
+ await player.draw(g, i);
2563
+ } catch (err) {
2564
+ this.rt.log(due.type, `frame ${i} failed: ${err instanceof Error ? err.message : String(err)}`);
2565
+ break;
2566
+ } finally {
2567
+ g.restore();
2568
+ }
2569
+ const turned = rotateCanvas(canvas, this.screen.rotate);
2570
+ const out = await this.fit(turned, kind, this.screen.jpegQuality || 85, this.screen, performance.now() - t0);
2571
+ await this.send(out);
2572
+ if (i % 3 === 0) {
2573
+ const snap = CANVAS.createCanvas(canvas.width, canvas.height);
2574
+ snap.getContext("2d").drawImage(canvas, 0, 0);
2575
+ this.lastInfo = { screenId: this.screen.id, pageId: this.page?.id ?? null, at: Date.now(), image: lazyJpeg(snap), tiles: [], interlude: due.type, sleeping: false };
2576
+ this.rt.frame(this.lastInfo);
2577
+ }
2578
+ const wait = start + (i + 1) * 1e3 / fps - Date.now();
2579
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));
2580
+ else {
2581
+ start -= wait;
2582
+ await new Promise((r) => setImmediate(r));
2583
+ }
2584
+ }
2585
+ this.interlude = null;
2586
+ this.pad = null;
2587
+ this.last = null;
2588
+ this.dirty = true;
2589
+ return true;
2590
+ }
2591
+ /**
2592
+ * Plays the animations the shown widgets ask for, if any is due (see
2593
+ * animation.ts). Like an interlude it runs inside `update`, so nothing else
2594
+ * is painted meanwhile, but unlike it the page stays in place: only the
2595
+ * widgets' tiles change from frame to frame. How many play together is
2596
+ * `Runtime.maxConcurrent` (one by default); the rest wait their turn.
2597
+ */
2598
+ async maybeAnimate(now) {
2599
+ if (!this.screen.enabled || this.closed || this.lastInfo?.sleeping || !this.animatable.length) return;
2600
+ const due = this.scheduler.next(this.animatable, now, this.screen.maxFps, this.rt.maxConcurrent);
2601
+ if (!due.length) return;
2602
+ this.animating = due.map((d) => d.animatable.type).join(", ");
2603
+ let completed = false;
2604
+ try {
2605
+ completed = await this.playAnimations(due, now);
2606
+ } finally {
2607
+ this.animating = null;
2608
+ this.last = null;
2609
+ this.dirty = true;
2610
+ for (const d of due) {
2611
+ this.scheduler.ended(d.animatable.instanceId, Date.now(), d.animatable);
2612
+ d.animatable.ended(d.play.plan, completed);
2613
+ }
2614
+ }
2615
+ }
2616
+ /**
2617
+ * One timeline for all: the fastest plan sets the rate and each animation
2618
+ * advances at its own, so they start together and the longest decides when
2619
+ * it is over. The ones that finish earlier stay at rest. With only one it
2620
+ * is just that animation's own frames.
2621
+ */
2622
+ async playAnimations(items, now) {
2623
+ const page = this.page;
2624
+ if (!page) return false;
2625
+ const { screen } = this;
2626
+ const fps = Math.max(...items.map((x) => x.play.fps));
2627
+ const seconds = Math.max(...items.map((x) => (x.play.frames - 1) / x.play.fps));
2628
+ const frames = Math.round(seconds * fps) + 1;
2629
+ const interruptible = items.every((x) => x.play.interruptible);
2630
+ const hold = items.length === 1 ? items[0].play.hold : void 0;
2631
+ const abort = () => this.closed || !!this.alert || interruptible && this.dirty || !this.screen.enabled;
2632
+ this.dirty = false;
2633
+ const memoData = /* @__PURE__ */ new Map();
2634
+ const memoSources = /* @__PURE__ */ new Map();
2635
+ const working = this.rt.working(now);
2636
+ const kind = encodeFor(screen.device, screen.jpegQuality || 85);
2637
+ const sent = [];
2638
+ const t0 = Date.now();
2639
+ for (let s = 1; s < frames - 1; s++) {
2640
+ if (abort()) return false;
2641
+ const animate = items.flatMap(({ animatable: a, play }) => {
2642
+ const i = Math.round(s / fps * play.fps);
2643
+ return i <= 0 || i >= play.frames - 1 ? [] : [{ tileId: a.tileId, instanceId: a.instanceId, frame: { plan: play.plan, i, t: i / (play.frames - 1) } }];
2644
+ });
2645
+ const t02 = performance.now();
2646
+ const result = composePage({
2647
+ cfg: this.rt.config,
2648
+ screen,
2649
+ page,
2650
+ theme: this.rt.theme(),
2651
+ registry: this.rt.registry,
2652
+ now,
2653
+ working,
2654
+ dataOf: (inst) => {
2655
+ if (!memoData.has(inst.id)) memoData.set(inst.id, this.rt.dataOf(inst.id));
2656
+ return memoData.get(inst.id);
2657
+ },
2658
+ sourcesOf: (types) => {
2659
+ const k = JSON.stringify(types ?? []);
2660
+ if (!memoSources.has(k)) memoSources.set(k, this.rt.sourcesOf(types));
2661
+ return memoSources.get(k);
2662
+ },
2663
+ log: this.rt.log,
2664
+ demo: this.rt.demoMode,
2665
+ cache: this.tiles,
2666
+ animate,
2667
+ rotate: screen.rotate
2668
+ });
2669
+ sent.push({ out: this.fit(result.canvas, kind, screen.jpegQuality || 85, screen, performance.now() - t02), snap: s % 3 === 1 ? result.canvas : null });
2670
+ await new Promise((r) => setImmediate(r));
2671
+ }
2672
+ const outs = await Promise.all(sent.map((x) => x.out));
2673
+ const what = items.map((x) => `${x.animatable.type} ${x.play.plan.id}`).join(" + ");
2674
+ this.rt.log(`screen:${screen.name}`, `animating ${what}: ${sent.length} frames at ${fps} fps (painted in ${Date.now() - t0} ms)`);
2675
+ const holdAt = hold ? Math.max(0, Math.min(sent.length - 1, hold.index - 1)) : -1;
2676
+ let start = Date.now();
2677
+ for (let k = 0; k < sent.length; k++) {
2678
+ if (abort()) return false;
2679
+ const due = Math.floor((Date.now() - start) * fps / 1e3);
2680
+ if (k < due - 1 && k !== holdAt && k < sent.length - 1) continue;
2681
+ await this.send(outs[k]);
2682
+ const snap = sent[k].snap;
2683
+ if (snap) {
2684
+ this.lastInfo = { screenId: screen.id, pageId: page.id, at: Date.now(), image: lazyJpeg(snap, screen.rotate), tiles: [], interlude: null, animation: items.map((x) => x.animatable.type).join(", "), sleeping: false };
2685
+ this.rt.frame(this.lastInfo);
2686
+ }
2687
+ if (hold && k === holdAt) {
2688
+ const until = Date.now() + hold.ms;
2689
+ while (Date.now() < until && !abort()) await new Promise((r) => setTimeout(r, Math.min(250, until - Date.now())));
2690
+ start = Date.now() - (k + 1) * 1e3 / fps;
2691
+ continue;
2692
+ }
2693
+ const wait = start + (k + 1) * 1e3 / fps - Date.now();
2694
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));
2695
+ }
2696
+ return true;
2697
+ }
2698
+ /**
2699
+ * Plays an interlude as soon as the screen is free: now if it is, or right
2700
+ * after the paint or animation under way (asked in the middle of one, it
2701
+ * used to be dropped without a word).
2702
+ */
2703
+ async playNow(slotId, play = false) {
2704
+ if (this.off || this.alert) return;
2705
+ this.wanted = slotId;
2706
+ this.wantedPlay = play;
2707
+ if (this.busy) return;
2708
+ this.busy = true;
2709
+ try {
2710
+ this.wanted = null;
2711
+ this.wantedPlay = false;
2712
+ await this.maybeInterlude(Date.now(), slotId, play);
2713
+ } finally {
2714
+ this.busy = false;
2715
+ }
2716
+ }
2717
+ stopInterlude() {
2718
+ this.interlude = null;
2719
+ this.pad = null;
2720
+ }
2721
+ dataChanged(change) {
2722
+ if (change.instance && this.visibleIds.has(change.instance) || change.source && this.sourceTypes.has(change.source)) this.dirty = true;
2723
+ }
2724
+ setPinned(pageId) {
2725
+ this.pinned = pageId;
2726
+ this.dirty = true;
2727
+ }
2728
+ setOff(off) {
2729
+ this.off = off;
2730
+ if (off) this.stopInterlude();
2731
+ this.dirty = true;
2732
+ }
2733
+ /** A button from the Play page, for the interlude being played; false when none is. */
2734
+ press(e) {
2735
+ if (!this.pad || !PAD_KEYS.includes(e.key)) return false;
2736
+ this.pad.send({ key: e.key, pressed: !!e.pressed });
2737
+ return true;
2738
+ }
2739
+ deviceTaken = false;
2740
+ takeDevice() {
2741
+ this.deviceTaken = true;
2742
+ return this.device;
2743
+ }
2744
+ close() {
2745
+ this.closed = true;
2746
+ this.interlude = null;
2747
+ if (!this.deviceTaken) this.device.close();
2748
+ }
2749
+ };
2750
+
2751
+ // packages/core/src/threads/clone.ts
2752
+ import { Image, createCanvas as createCanvas6 } from "@napi-rs/canvas";
2753
+ var PICTURE = "\0kioskoPicture";
2754
+ var BUFFER = "\0kioskoBuffer";
2755
+ var CLONED_AS_IS = [Date, RegExp, ArrayBuffer, Error, DataView];
2756
+ function unpack(value, pictures, keep = 256) {
2757
+ const seen = /* @__PURE__ */ new Map();
2758
+ const walk = (v) => {
2759
+ if (v === null || typeof v !== "object") return v;
2760
+ if (seen.has(v)) return seen.get(v);
2761
+ if (v[PICTURE]) return picture(v, pictures, keep);
2762
+ const buf = v[BUFFER];
2763
+ if (buf) return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
2764
+ if (ArrayBuffer.isView(v) || CLONED_AS_IS.some((c) => v instanceof c)) return v;
2765
+ if (Array.isArray(v)) {
2766
+ seen.set(v, v);
2767
+ for (let i = 0; i < v.length; i++) v[i] = walk(v[i]);
2768
+ return v;
2769
+ }
2770
+ if (v instanceof Map) {
2771
+ seen.set(v, v);
2772
+ for (const [k, x] of v) v.set(k, walk(x));
2773
+ return v;
2774
+ }
2775
+ if (v instanceof Set) {
2776
+ const items = [...v];
2777
+ seen.set(v, v);
2778
+ v.clear();
2779
+ for (const x of items) v.add(walk(x));
2780
+ return v;
2781
+ }
2782
+ seen.set(v, v);
2783
+ for (const [k, x] of Object.entries(v)) v[k] = walk(x);
2784
+ return v;
2785
+ };
2786
+ return walk(value);
2787
+ }
2788
+ function picture(p, pictures, keep) {
2789
+ const known = pictures.get(p.id);
2790
+ if (known) {
2791
+ pictures.delete(p.id);
2792
+ pictures.set(p.id, known);
2793
+ return known;
2794
+ }
2795
+ let made;
2796
+ if (p[PICTURE] === "image") {
2797
+ const img = new Image();
2798
+ img.src = Buffer.from(p.bytes.buffer, p.bytes.byteOffset, p.bytes.byteLength);
2799
+ made = img;
2800
+ } else {
2801
+ const c = createCanvas6(p.width, p.height);
2802
+ const g = c.getContext("2d");
2803
+ const data = g.createImageData(p.width, p.height);
2804
+ data.data.set(p.bytes);
2805
+ g.putImageData(data, 0, 0);
2806
+ made = c;
2807
+ }
2808
+ pictures.set(p.id, made);
2809
+ while (pictures.size > keep) pictures.delete(pictures.keys().next().value);
2810
+ return made;
2811
+ }
2812
+
2813
+ // packages/core/src/runtime.ts
2814
+ var SLOW_WARN_EVERY_MS = 10 * 6e4;
2815
+ var nodePerf = globalThis.performance;
2816
+
2817
+ // packages/core/src/registry.ts
2818
+ import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync, statSync, writeFileSync as writeFileSync2 } from "node:fs";
2819
+ import { join as join5 } from "node:path";
2820
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
2821
+
2822
+ // packages/core/src/plugin-meta.ts
2823
+ var PLATFORMS = ["linux", "darwin", "win32"];
2824
+ function packageMeta(pkg) {
2825
+ const out = {};
2826
+ if (typeof pkg.name === "string") out.name = pkg.name;
2827
+ if (typeof pkg.version === "string") out.version = pkg.version;
2828
+ const id = pkg.kiosko?.id ?? (typeof pkg.name === "string" ? pkg.name.replace(/^@[^/]+\//, "").replace(/^kiosko-plugin-/, "") : void 0);
2829
+ if (typeof id === "string") out.id = id;
2830
+ const sdk = pkg.kiosko?.sdk ?? pkg.peerDependencies?.["@kiosko/sdk"];
2831
+ if (typeof sdk === "string") out.sdk = sdk;
2832
+ if (Array.isArray(pkg.os) && pkg.os.length) {
2833
+ const os = pkg.os.filter((x) => typeof x === "string");
2834
+ const allow = os.filter((x) => !x.startsWith("!"));
2835
+ const deny = os.filter((x) => x.startsWith("!")).map((x) => x.slice(1));
2836
+ out.platforms = PLATFORMS.filter((p) => (!allow.length || allow.includes(p)) && !deny.includes(p));
2837
+ }
2838
+ const langs = pkg.kiosko?.languages;
2839
+ if (Array.isArray(langs) && langs.length) out.languages = langs.filter((x) => typeof x === "string");
2840
+ return out;
2841
+ }
2842
+ function incompatibility(o, env = { sdk: SDK_VERSION, platform: process.platform }) {
2843
+ if (o.sdk && !satisfies(env.sdk, o.sdk)) return `written for the plugin API ${o.sdk}; this Kiosko has ${env.sdk}`;
2844
+ if (o.platforms && !o.platforms.includes(env.platform)) return `works on ${o.platforms.map(platformName).join(", ")}, not on ${platformName(env.platform)}`;
2845
+ return null;
2846
+ }
2847
+ var platformName = (p) => p === "darwin" ? "macOS" : p === "win32" ? "Windows" : p === "linux" ? "Linux" : p;
2848
+ var pluginOf = (type) => type.split("/")[0] ?? type;
2849
+ var fullType = (pluginId, type) => type.includes("/") ? type : `${pluginId}/${type}`;
2850
+ function isLanguageTag(k) {
2851
+ if (!/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(k)) return false;
2852
+ try {
2853
+ return Intl.getCanonicalLocales(k).length === 1;
2854
+ } catch {
2855
+ return false;
2856
+ }
2857
+ }
2858
+ function declaredLanguages(def, meta = {}) {
2859
+ return def.languages?.length ? [...def.languages] : meta.languages?.length ? [...meta.languages] : languagesOf(def);
2860
+ }
2861
+ function languagesOf(def) {
2862
+ const out = /* @__PURE__ */ new Set();
2863
+ const seen = /* @__PURE__ */ new WeakSet();
2864
+ const walk = (v, key = "") => {
2865
+ if (!v || typeof v !== "object" || seen.has(v)) return;
2866
+ seen.add(v);
2867
+ if (Array.isArray(v)) return void v.forEach((x) => walk(x));
2868
+ const o = v;
2869
+ const keys = Object.keys(o);
2870
+ if (keys.includes("en") && keys.every((k) => isLanguageTag(k) && typeof o[k] === "string")) {
2871
+ for (const k of keys) out.add(k);
2872
+ return;
2873
+ }
2874
+ for (const [k, x] of Object.entries(o)) if (typeof x !== "function" && k !== "default") walk(x, k);
2875
+ };
2876
+ walk({ name: def.name, description: def.description, widgets: def.widgets, sources: def.sources, interludes: def.interludes, templates: def.templates });
2877
+ if (!out.size) out.add("en");
2878
+ return [...out].sort((a, b) => a === "en" ? -1 : b === "en" ? 1 : a.localeCompare(b));
2879
+ }
2880
+
2881
+ // packages/core/src/sdk-resolver.ts
2882
+ import { existsSync as existsSync3 } from "node:fs";
2883
+ import module from "node:module";
2884
+ import { join as join4 } from "node:path";
2885
+ import { pathToFileURL } from "node:url";
2886
+ var SHARED = ["@kiosko/sdk", "@loksly/lcd-canvas-kit", "@loksly/weather-astro", "@napi-rs/canvas"];
2887
+ var BUNDLED = { "@kiosko/sdk": "sdk.js", "@loksly/lcd-canvas-kit": "kit.js", "@loksly/weather-astro": "weather-astro.js" };
2888
+ var installed = false;
2889
+ function installSdkResolver() {
2890
+ if (installed) return;
2891
+ installed = true;
2892
+ const urls = /* @__PURE__ */ new Map();
2893
+ for (const name of SHARED) {
2894
+ const local = BUNDLED[name] ? join4(import.meta.dirname, BUNDLED[name]) : null;
2895
+ if (local && existsSync3(local)) {
2896
+ urls.set(name, pathToFileURL(local).href);
2897
+ continue;
2898
+ }
2899
+ try {
2900
+ urls.set(name, import.meta.resolve(name));
2901
+ } catch {
2902
+ }
2903
+ }
2904
+ const register = module.registerHooks;
2905
+ if (!register) return;
2906
+ register({
2907
+ resolve(specifier, context, next) {
2908
+ const url = urls.get(specifier);
2909
+ if (url) return { url, shortCircuit: true, format: url.endsWith(".ts") ? "module-typescript" : "module" };
2910
+ return next(specifier, context);
2911
+ }
2912
+ });
2913
+ }
2914
+
2915
+ // packages/core/src/registry.ts
2916
+ var ID = /^[a-z0-9][a-z0-9-]*$/;
2917
+ var Registry = class {
2918
+ plugins = /* @__PURE__ */ new Map();
2919
+ /** Problems found while loading, for the editor's Plugins page. */
2920
+ problems = [];
2921
+ /**
2922
+ * Plugins found but not loaded because they don't fit this Kiosko (plugin
2923
+ * API version, operating system). Those found through their package.json
2924
+ * were refused before their code ran.
2925
+ */
2926
+ refused = [];
2927
+ /** Where a plugin's code came from, to load it again (`reload`). */
2928
+ entries = /* @__PURE__ */ new Map();
2929
+ /** The module each plugin's code came from (its URL), for a screen's thread to load it too. */
2930
+ modules = /* @__PURE__ */ new Map();
2931
+ reloads = 0;
2932
+ refuse(r) {
2933
+ this.refused.push({ origin: r.origin, reason: r.reason, ...r.id ? { id: r.id } : {}, ...r.version ? { version: r.version } : {} });
2934
+ this.problems.push({ origin: r.origin, message: `${r.id ? `"${r.id}" ` : ""}not loaded: ${r.reason}` });
2935
+ }
2936
+ /** `module`: the URL its code can be imported from again (see `threadPlugins`). */
2937
+ add(def, origin = "builtin", module3) {
2938
+ if (!def || typeof def !== "object" || !ID.test(def.id ?? "")) {
2939
+ this.problems.push({ origin, message: `invalid plugin id ${JSON.stringify(def?.id)}` });
2940
+ return;
2941
+ }
2942
+ const why = incompatibility(def);
2943
+ if (why) return this.refuse({ id: def.id, version: def.version, origin, reason: why });
2944
+ if (this.plugins.has(def.id)) {
2945
+ this.problems.push({ origin, message: `plugin "${def.id}" already loaded from ${this.plugins.get(def.id).origin}` });
2946
+ return;
2947
+ }
2948
+ this.plugins.set(def.id, { def, origin, enabled: true });
2949
+ if (module3) this.modules.set(def.id, module3);
2950
+ else this.modules.delete(def.id);
2951
+ }
2952
+ /** Forgets a plugin (removed, or about to be loaded again). Its module stays in memory: ES modules can't be unloaded. */
2953
+ remove(id) {
2954
+ this.entries.delete(id);
2955
+ this.modules.delete(id);
2956
+ return this.plugins.delete(id);
2957
+ }
2958
+ /**
2959
+ * Imports a plugin's code again from where it came, so a rebuilt or
2960
+ * updated plugin runs without restarting Kiosko. Only its entry file is
2961
+ * read again: a plugin should be one bundled file (what `npm run build`
2962
+ * makes). Returns the problem, or null.
2963
+ */
2964
+ async reload(id) {
2965
+ const e = this.entries.get(id);
2966
+ if (!e) return this.plugins.has(id) ? `"${id}" is built in and can't be reloaded` : `"${id}" is not loaded`;
2967
+ const old = this.plugins.get(id);
2968
+ this.plugins.delete(id);
2969
+ const problems = this.problems.length;
2970
+ try {
2971
+ const def = await this.loadEntry(e.entry, e.origin, `${Date.now()}-${++this.reloads}`);
2972
+ if (def && this.plugins.has(id)) {
2973
+ this.plugins.get(id).enabled = old.enabled;
2974
+ return null;
2975
+ }
2976
+ } catch (err) {
2977
+ this.problems.push({ origin: e.origin, message: err instanceof Error ? err.message : String(err) });
2978
+ }
2979
+ this.plugins.set(id, old);
2980
+ this.entries.set(id, e);
2981
+ return this.problems.slice(problems).map((p) => p.message).join("; ") || `"${id}" did not load again`;
2982
+ }
2983
+ /** Loads one plugin folder (just installed or linked), as `loadDir` does for each. Returns the ids it added. */
2984
+ async loadOne(folder) {
2985
+ installSdkResolver();
2986
+ const before = new Set(this.plugins.keys());
2987
+ await this.loadFolder(folder);
2988
+ return [...this.plugins.keys()].filter((id) => !before.has(id));
2989
+ }
2990
+ /**
2991
+ * The plugins that came from npm, with their package and the version
2992
+ * installed: the ones that can be updated. Installed in the plugins folder
2993
+ * (read from their package.json) or brought along with Kiosko (`npm:`
2994
+ * origin). Built-in, linked and hand-copied plugins are left out.
2995
+ */
2996
+ packages() {
2997
+ const out = [];
2998
+ for (const { def, origin } of this.plugins.values()) {
2999
+ if (origin.startsWith("npm:")) {
3000
+ out.push({ id: def.id, package: origin.slice(4), version: def.version });
3001
+ continue;
3002
+ }
3003
+ if (!/[\\/]node_modules[\\/]/.test(origin)) continue;
3004
+ try {
3005
+ const pkg = JSON.parse(readFileSync(join5(origin, "package.json"), "utf8"));
3006
+ if (pkg.name) out.push({ id: def.id, package: pkg.name, version: pkg.version ?? def.version });
3007
+ } catch {
3008
+ }
3009
+ }
3010
+ return out;
3011
+ }
3012
+ /**
3013
+ * What a screen's thread loads to have the same plugins, in the same
3014
+ * order: the built-in ones by id (the thread brings its own copies) and the
3015
+ * rest by the URL of their module (the version reloaded last, if it was).
3016
+ * Plugins added with no module (a test's) can't be loaded there.
3017
+ */
3018
+ threadPlugins() {
3019
+ return this.list().map(({ def, origin }) => ({ id: def.id, origin, module: this.modules.get(def.id) ?? null }));
3020
+ }
3021
+ /** Where a loaded plugin came from (its folder), or undefined for a built-in one. */
3022
+ originOf(id) {
3023
+ return this.entries.get(id)?.origin;
3024
+ }
3025
+ setDisabled(ids) {
3026
+ for (const p of this.plugins.values()) p.enabled = !ids.includes(p.def.id);
3027
+ }
3028
+ list() {
3029
+ return [...this.plugins.values()];
3030
+ }
3031
+ plugin(id) {
3032
+ return this.plugins.get(id);
3033
+ }
3034
+ find(kind, type) {
3035
+ const [pid, id] = type.split("/");
3036
+ const p = pid ? this.plugins.get(pid) : void 0;
3037
+ if (!p || !p.enabled) return void 0;
3038
+ return p.def[kind]?.find((x) => x.id === id);
3039
+ }
3040
+ widget(type) {
3041
+ return this.find("widgets", type);
3042
+ }
3043
+ source(type) {
3044
+ return this.find("sources", type);
3045
+ }
3046
+ interlude(type) {
3047
+ return this.find("interludes", type);
3048
+ }
3049
+ /**
3050
+ * Loads external plugins from `dir`: each subfolder whose package.json has
3051
+ * `"kiosko": { "plugin": "./entry.js" }` (or a `main`), plus packages
3052
+ * installed there with npm (`node_modules/kiosko-plugin-*`).
3053
+ */
3054
+ async loadDir(dir) {
3055
+ if (!existsSync4(dir)) return;
3056
+ installSdkResolver();
3057
+ const marker = join5(dir, "package.json");
3058
+ if (!existsSync4(marker)) {
3059
+ try {
3060
+ writeFileSync2(marker, `${JSON.stringify({ name: "kiosko-user-plugins", private: true, type: "module" }, null, 2)}
3061
+ `);
3062
+ } catch {
3063
+ }
3064
+ }
3065
+ const candidates = [];
3066
+ for (const name of readdirSync2(dir)) {
3067
+ if (name === "node_modules" || name.startsWith(".")) continue;
3068
+ candidates.push(join5(dir, name));
3069
+ }
3070
+ const nm = join5(dir, "node_modules");
3071
+ if (existsSync4(nm)) {
3072
+ for (const name of readdirSync2(nm)) {
3073
+ if (name.startsWith("@")) {
3074
+ for (const sub of readdirSync2(join5(nm, name))) if (sub.startsWith("kiosko-plugin-")) candidates.push(join5(nm, name, sub));
3075
+ } else if (name.startsWith("kiosko-plugin-")) candidates.push(join5(nm, name));
3076
+ }
3077
+ }
3078
+ for (const folder of candidates) await this.loadFolder(folder);
3079
+ }
3080
+ async loadFolder(folder) {
3081
+ try {
3082
+ if (!statSync(folder).isDirectory()) {
3083
+ if (/\.m?js$/.test(folder)) await this.loadEntry(folder, folder);
3084
+ return;
3085
+ }
3086
+ const pkgPath = join5(folder, "package.json");
3087
+ let entry = ["index.mjs", "index.js"].map((f) => join5(folder, f)).find(existsSync4);
3088
+ if (existsSync4(pkgPath)) {
3089
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
3090
+ const meta = packageMeta(pkg);
3091
+ const why = incompatibility(meta);
3092
+ if (why) return this.refuse({ id: meta.id, version: meta.version, origin: folder, reason: why });
3093
+ const rel = pkg.kiosko?.plugin ?? pkg.main;
3094
+ if (rel) entry = join5(folder, rel);
3095
+ }
3096
+ if (!entry || !existsSync4(entry)) {
3097
+ this.problems.push({ origin: folder, message: 'no entry point (package.json "kiosko.plugin", "main" or index.js)' });
3098
+ return;
3099
+ }
3100
+ await this.loadEntry(entry, folder);
3101
+ } catch (err) {
3102
+ this.problems.push({ origin: folder, message: err instanceof Error ? err.message : String(err) });
3103
+ }
3104
+ }
3105
+ async loadEntry(entry, origin, version) {
3106
+ const url = pathToFileURL2(entry).href + (version ? `?v=${version}` : "");
3107
+ const mod = await import(url);
3108
+ if (!mod.default) {
3109
+ this.problems.push({ origin, message: "the module has no default export (use `export default definePlugin({...})`)" });
3110
+ return void 0;
3111
+ }
3112
+ const before = this.plugins.size;
3113
+ this.add(mod.default, origin, url);
3114
+ if (this.plugins.size > before) this.entries.set(mod.default.id, { entry, origin });
3115
+ return mod.default;
3116
+ }
3117
+ /**
3118
+ * The values a source offers for an option (see `SourceDefinition.choices`),
3119
+ * from `data` (its latest), or from its demo data when it has none yet.
3120
+ * At most 1000, never throwing: a list that fails is empty, with why.
3121
+ */
3122
+ choices(source, list2, data, locale) {
3123
+ const def = this.source(source);
3124
+ const fn = def?.choices?.[list2];
3125
+ if (!def || !fn) return { choices: [], from: "none", error: def ? `${source} has no list "${list2}"` : `no source ${source}` };
3126
+ const from = data !== void 0 ? "live" : def.demo ? "demo" : "none";
3127
+ if (from === "none") return { choices: [], from };
3128
+ try {
3129
+ const value = from === "live" ? data : def.demo({ now: Date.now(), locale });
3130
+ const out = fn(value, { locale, t: (x) => localize(x, locale) });
3131
+ const clean = (Array.isArray(out) ? out : []).filter((c) => !!c && typeof c.value === "string" && c.value !== "").slice(0, 1e3).map((c) => ({ value: c.value, ...typeof c.label === "string" && c.label !== c.value ? { label: c.label } : {}, ...typeof c.group === "string" ? { group: c.group } : {} }));
3132
+ return { choices: clean, from };
3133
+ } catch (err) {
3134
+ return { choices: [], from, error: err instanceof Error ? err.message : String(err) };
3135
+ }
3136
+ }
3137
+ /** What the editor needs to know about every widget, source and interlude (JSON-safe). */
3138
+ catalog(locale) {
3139
+ const L = (x) => localize(x, locale);
3140
+ const has = (type) => !!(this.widget(type) ?? this.source(type) ?? this.interlude(type));
3141
+ return this.list().map(({ def, origin, enabled }) => ({
3142
+ id: def.id,
3143
+ name: L(def.name),
3144
+ version: def.version,
3145
+ description: L(def.description),
3146
+ author: def.author,
3147
+ homepage: def.homepage,
3148
+ repository: def.repository,
3149
+ license: def.license,
3150
+ icon: def.icon,
3151
+ sdk: def.sdk ?? null,
3152
+ platforms: def.platforms ?? null,
3153
+ /** The languages its texts come in (declared, or read from its texts). */
3154
+ languages: declaredLanguages(def),
3155
+ permissions: def.permissions ?? {},
3156
+ /** What it needs from other plugins, and whether that is here (installed and on). */
3157
+ requires: (def.requires ?? []).map((type) => ({ type, plugin: pluginOf(type), ok: has(type) })),
3158
+ /** What it uses from other plugins when they are there. */
3159
+ optional: (def.optional ?? []).map((type) => ({ type, plugin: pluginOf(type), ok: has(type) })),
3160
+ templates: (def.templates ?? []).map((tp) => {
3161
+ const tiles = (list2) => list2?.map((tile) => ({ ...tile, widgets: tile.widgets.map((w) => typeof w === "string" ? fullType(def.id, w) : [fullType(def.id, w[0]), w[1]]) }));
3162
+ return { id: `${def.id}/${tp.id}`, name: L(tp.name), icon: tp.icon ?? "layout-template", wide: tiles(tp.wide), square: tiles(tp.square), tall: tiles(tp.tall) };
3163
+ }),
3164
+ builtin: origin === "builtin",
3165
+ origin,
3166
+ enabled,
3167
+ widgets: (def.widgets ?? []).map((w) => ({
3168
+ type: `${def.id}/${w.id}`,
3169
+ name: L(w.name),
3170
+ description: L(w.description),
3171
+ icon: w.icon,
3172
+ category: w.category ?? "info",
3173
+ tags: w.tags ?? [],
3174
+ /** Its name and description in every language it has, so a search in any of them finds it. */
3175
+ searchText: [w.name, w.description].flatMap((x) => x === void 0 ? [] : typeof x === "string" ? [x] : Object.values(x)).join(" "),
3176
+ size: w.size ?? {},
3177
+ chrome: w.chrome ?? "card",
3178
+ options: w.options ? toJsonSchema(w.options) : null,
3179
+ sources: w.sources ?? [],
3180
+ hasFetch: !!w.fetch,
3181
+ intervalMs: w.intervalMs ?? null,
3182
+ // Defaults of the instance switches, or null when the widget lacks the hook behind them.
3183
+ takeOver: w.urgent ? w.takeOver ?? true : null,
3184
+ hideWhenEmpty: w.empty ? w.hideWhenEmpty ?? false : null
3185
+ })),
3186
+ sources: (def.sources ?? []).map((s) => {
3187
+ const field = sourceOptionsField(s);
3188
+ return { type: `${def.id}/${s.id}`, name: L(s.name), description: L(s.description), options: field ? toJsonSchema(field) : null, intervalMs: s.read ? sourceTiming(s).intervalMs : null, polled: !!s.read, background: canRunInBackground(s) };
3189
+ }),
3190
+ interludes: (def.interludes ?? []).map((i) => ({ type: `${def.id}/${i.id}`, name: L(i.name), description: L(i.description), icon: i.icon, fps: i.fps, input: !!i.input, options: i.options ? toJsonSchema(i.options) : null }))
3191
+ }));
3192
+ }
3193
+ };
3194
+
3195
+ // packages/core/src/licenses.ts
3196
+ var PERMISSIVE = ["MIT", "MIT-0", "ISC", "BSD-2-Clause", "BSD-3-Clause", "BSD-3-Clause-Clear", "0BSD", "Apache-2.0", "Zlib", "Unlicense", "CC0-1.0", "BSL-1.0", "PostgreSQL", "NCSA", "X11", "Python-2.0", "BlueOak-1.0.0", "UPL-1.0", "Artistic-2.0", "WTFPL", "CC-BY-4.0"];
3197
+ var COPYLEFT = [
3198
+ "GPL-2.0-only",
3199
+ "GPL-2.0-or-later",
3200
+ "GPL-3.0-only",
3201
+ "GPL-3.0-or-later",
3202
+ "LGPL-2.1-only",
3203
+ "LGPL-2.1-or-later",
3204
+ "LGPL-3.0-only",
3205
+ "LGPL-3.0-or-later",
3206
+ "AGPL-3.0-only",
3207
+ "AGPL-3.0-or-later",
3208
+ "MPL-2.0",
3209
+ "EPL-2.0",
3210
+ "EUPL-1.2",
3211
+ "CDDL-1.0",
3212
+ "OSL-3.0",
3213
+ "CC-BY-SA-4.0",
3214
+ // Deprecated spellings npm still accepts.
3215
+ "GPL-2.0",
3216
+ "GPL-3.0",
3217
+ "LGPL-2.1",
3218
+ "LGPL-3.0",
3219
+ "AGPL-3.0"
3220
+ ];
3221
+ var OTHER = ["CC-BY-NC-4.0", "CC-BY-NC-SA-4.0", "CC-BY-ND-4.0", "BUSL-1.1", "Elastic-2.0", "SSPL-1.0"];
3222
+ var KNOWN = new Map([...PERMISSIVE.map((id) => [id, "permissive"]), ...COPYLEFT.map((id) => [id, "copyleft"]), ...OTHER.map((id) => [id, "other"])]);
3223
+ var LOWER = new Map([...KNOWN.keys()].map((id) => [id.toLowerCase(), id]));
3224
+
3225
+ // packages/core/src/threads/worker-main.ts
3226
+ import { parentPort, workerData } from "node:worker_threads";
3227
+ var HEAP_EVERY_MS = 5e3;
3228
+ var errorText = (err) => err instanceof Error ? err.message : String(err);
3229
+ async function loadThreadPlugins(list2, builtins) {
3230
+ installSdkResolver();
3231
+ const registry = new Registry();
3232
+ const problems = [];
3233
+ for (const p of list2) {
3234
+ if (p.origin === "builtin") {
3235
+ const def = builtins.find((d) => d.id === p.id);
3236
+ if (def) registry.add(def);
3237
+ else problems.push(`${p.id}: not built into the thread`);
3238
+ continue;
3239
+ }
3240
+ if (!p.module) {
3241
+ problems.push(`${p.id}: its code can't be loaded again in a thread`);
3242
+ continue;
3243
+ }
3244
+ try {
3245
+ const mod = await import(p.module);
3246
+ if (mod.default) registry.add(mod.default, p.origin, p.module);
3247
+ else problems.push(`${p.id}: no default export`);
3248
+ } catch (err) {
3249
+ problems.push(`${p.id}: ${errorText(err)}`);
3250
+ }
3251
+ }
3252
+ return { registry, problems };
3253
+ }
3254
+ var RelayDevice = class {
3255
+ status = { driver: "virtual", ok: true, message: "sent through the main thread", code: "virtual", framesSent: 0, lastSentAt: null };
3256
+ seq = 0;
3257
+ waiting = /* @__PURE__ */ new Map();
3258
+ post;
3259
+ constructor(post) {
3260
+ this.post = post;
3261
+ }
3262
+ send(frame) {
3263
+ const seq = ++this.seq;
3264
+ return new Promise((resolve2) => {
3265
+ this.waiting.set(seq, resolve2);
3266
+ this.post({ t: "send", seq, frame });
3267
+ });
3268
+ }
3269
+ sent(seq) {
3270
+ this.waiting.get(seq)?.();
3271
+ this.waiting.delete(seq);
3272
+ }
3273
+ close() {
3274
+ for (const done2 of this.waiting.values()) done2();
3275
+ this.waiting.clear();
3276
+ }
3277
+ };
3278
+ var Host = class {
3279
+ config;
3280
+ registry;
3281
+ demoMode;
3282
+ maxConcurrent;
3283
+ playIdleMs;
3284
+ rnd = Math.random;
3285
+ data = /* @__PURE__ */ new Map();
3286
+ sources = /* @__PURE__ */ new Map();
3287
+ /** Pictures already made from the bytes they came as (see clone.ts). */
3288
+ pictures = /* @__PURE__ */ new Map();
3289
+ runner = null;
3290
+ /** Called after each frame: the state may have changed with it (an interlude starting). */
3291
+ afterFrame = () => void 0;
3292
+ device;
3293
+ post;
3294
+ constructor(init, registry, post) {
3295
+ this.config = init.config;
3296
+ this.registry = registry;
3297
+ this.demoMode = init.demo;
3298
+ this.maxConcurrent = init.maxConcurrent;
3299
+ this.playIdleMs = init.playIdleMs;
3300
+ this.post = post;
3301
+ this.device = new RelayDevice(post);
3302
+ }
3303
+ log = (scope, message) => this.post({ t: "log", scope, message });
3304
+ theme() {
3305
+ return themeById(this.config.theme);
3306
+ }
3307
+ working(now) {
3308
+ return isWorking(this.config.workday, now);
3309
+ }
3310
+ dataOf(instanceId) {
3311
+ return this.data.get(instanceId);
3312
+ }
3313
+ sourcesOf(types) {
3314
+ const out = {};
3315
+ for (const t2 of types ?? []) out[t2] = this.sources.get(t2);
3316
+ return out;
3317
+ }
3318
+ paintTime(instance, type, ms, now) {
3319
+ this.post({ t: "paintTime", instance, type, ms, now });
3320
+ }
3321
+ frame(info) {
3322
+ const { image: _, ...rest } = info;
3323
+ this.post({ t: "frame", info: rest });
3324
+ this.afterFrame();
3325
+ }
3326
+ pageChanged() {
3327
+ this.visible();
3328
+ }
3329
+ openDevice() {
3330
+ return this.device;
3331
+ }
3332
+ /** What on the current page counts as visible, as `Runtime.refreshWanted` does on the main thread. */
3333
+ visible() {
3334
+ const r = this.runner;
3335
+ if (!r) return;
3336
+ r.visibleIds.clear();
3337
+ r.sourceTypes.clear();
3338
+ for (const { page, widget } of widgetsOf(r.screen)) {
3339
+ const def = this.registry.widget(widget.type);
3340
+ if (!def || widget.disabled) continue;
3341
+ if (!r.page || r.page.id === page.id) {
3342
+ r.visibleIds.add(widget.id);
3343
+ for (const s of def.sources ?? []) r.sourceTypes.add(s);
3344
+ }
3345
+ }
3346
+ }
3347
+ };
3348
+ async function runScreenThread(builtins = []) {
3349
+ const port = parentPort;
3350
+ if (!port) throw new Error("runScreenThread runs in a worker thread");
3351
+ const init = workerData;
3352
+ const post = (m) => port.postMessage(m);
3353
+ const early = [];
3354
+ let handle = null;
3355
+ port.on("message", (m) => handle ? handle(m) : early.push(m));
3356
+ const { registry, problems } = await loadThreadPlugins(init.plugins, builtins);
3357
+ registry.setDisabled(init.config.plugins.disabled);
3358
+ const host = new Host(init, registry, post);
3359
+ const runner = new ScreenRunner(init.screen, host);
3360
+ host.runner = runner;
3361
+ if (init.pinned !== runner.pinned) runner.setPinned(init.pinned);
3362
+ if (init.off) runner.setOff(true);
3363
+ host.visible();
3364
+ let lastState = "";
3365
+ let heapAt = 0;
3366
+ let heapBytes = 0;
3367
+ const tellState = () => {
3368
+ if (Date.now() - heapAt >= HEAP_EVERY_MS) {
3369
+ heapAt = Date.now();
3370
+ const m = process.memoryUsage();
3371
+ heapBytes = m.heapUsed + m.external;
3372
+ }
3373
+ const state = {
3374
+ page: runner.page?.id ?? null,
3375
+ interlude: runner.interlude ? { type: runner.interlude.type, play: runner.interlude.play } : null,
3376
+ animating: runner.animating,
3377
+ stats: runner.stats.read(),
3378
+ heapBytes
3379
+ };
3380
+ const key = JSON.stringify(state);
3381
+ if (key === lastState) return;
3382
+ lastState = key;
3383
+ post({ t: "state", state });
3384
+ };
3385
+ host.afterFrame = tellState;
3386
+ let timer = null;
3387
+ const close = () => {
3388
+ if (timer) clearInterval(timer);
3389
+ timer = null;
3390
+ runner.close();
3391
+ host.device.close();
3392
+ port.close();
3393
+ };
3394
+ handle = (m) => {
3395
+ switch (m.t) {
3396
+ case "apply": {
3397
+ host.config = m.config;
3398
+ registry.setDisabled(m.config.plugins.disabled);
3399
+ runner.reconfigure(m.screen);
3400
+ host.visible();
3401
+ return;
3402
+ }
3403
+ case "data": {
3404
+ const value = unpack(m.value, host.pictures);
3405
+ if (m.instance) {
3406
+ if (value === void 0) host.data.delete(m.instance);
3407
+ else host.data.set(m.instance, value);
3408
+ }
3409
+ if (m.source) {
3410
+ if (value === void 0) host.sources.delete(m.source);
3411
+ else host.sources.set(m.source, value);
3412
+ }
3413
+ runner.dataChanged({ ...m.instance ? { instance: m.instance } : {}, ...m.source ? { source: m.source } : {} });
3414
+ return;
3415
+ }
3416
+ case "alert":
3417
+ runner.setAlert(m.shown, Date.now());
3418
+ return;
3419
+ case "pin":
3420
+ runner.setPinned(m.page);
3421
+ return;
3422
+ case "off":
3423
+ runner.setOff(m.off);
3424
+ return;
3425
+ case "play":
3426
+ void runner.playNow(m.slot, m.play).then(tellState);
3427
+ tellState();
3428
+ return;
3429
+ case "stop":
3430
+ runner.stopInterlude();
3431
+ return;
3432
+ case "press":
3433
+ if (PAD_KEYS.includes(m.e.key)) runner.press(m.e);
3434
+ return;
3435
+ case "sent":
3436
+ host.device.sent(m.seq);
3437
+ return;
3438
+ case "image": {
3439
+ let image2 = null;
3440
+ void (async () => {
3441
+ try {
3442
+ const info = runner.lastInfo;
3443
+ if (info) image2 = await info.image();
3444
+ } catch {
3445
+ image2 = null;
3446
+ }
3447
+ post({ t: "image", req: m.req, image: image2 });
3448
+ })();
3449
+ return;
3450
+ }
3451
+ case "close":
3452
+ close();
3453
+ return;
3454
+ }
3455
+ };
3456
+ for (const m of early.splice(0)) handle(m);
3457
+ post({ t: "ready", problems });
3458
+ const loop = async () => {
3459
+ await runner.update(Date.now());
3460
+ tellState();
3461
+ };
3462
+ timer = setInterval(() => void loop(), TICK_MS);
3463
+ void loop();
3464
+ }
3465
+
3466
+ // packages/core/src/store/tar.ts
3467
+ var MAX_TARBALL_BYTES = 20 * 1024 * 1024;
3468
+
3469
+ // plugins/core/src/index.ts
3470
+ import { readdir, readFile, stat } from "node:fs/promises";
3471
+ import { join as join6 } from "node:path";
3472
+ function fit(g, text2, family, w, h, max = 400) {
3473
+ let size = Math.min(max, h);
3474
+ g.font = `${size}px "${family}"`;
3475
+ const width = g.measureText(text2).width;
3476
+ if (width > w) size = Math.floor(size * w / width);
3477
+ return Math.max(8, size);
3478
+ }
3479
+ function isoWeek(d) {
3480
+ const t0 = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
3481
+ t0.setUTCDate(t0.getUTCDate() + 4 - (t0.getUTCDay() || 7));
3482
+ return Math.ceil(((t0.getTime() - Date.UTC(t0.getUTCFullYear(), 0, 1)) / 864e5 + 1) / 7);
3483
+ }
3484
+ var DATE_FORMATS = {
3485
+ long: { weekday: "long", day: "numeric", month: "long" },
3486
+ short: { weekday: "short", day: "numeric", month: "short" },
3487
+ numeric: { day: "numeric", month: "numeric", year: "numeric" }
3488
+ };
3489
+ function wallClock(now, timeZone) {
3490
+ const zone = timeZone.trim();
3491
+ if (!zone) return now;
3492
+ try {
3493
+ const parts = new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" }).formatToParts(now);
3494
+ const n = (type) => Number(parts.find((p) => p.type === type)?.value ?? 0);
3495
+ return new Date(n("year"), n("month") - 1, n("day"), n("hour"), n("minute"), n("second"), (now % 1e3 + 1e3) % 1e3).getTime();
3496
+ } catch {
3497
+ return now;
3498
+ }
3499
+ }
3500
+ var clock = defineWidget({
3501
+ id: "clock",
3502
+ name: { en: "Clock", es: "Reloj", de: "Uhr", "zh-Hant": "\u6642\u9418", "zh-Hans": "\u65F6\u949F" },
3503
+ description: { en: "Big digital clock, with optional seconds and date.", es: "Reloj digital grande, con segundos y fecha opcionales.", de: "Gro\xDFe Digitaluhr, wahlweise mit Sekunden und Datum.", "zh-Hant": "\u5927\u578B\u6578\u4F4D\u6642\u9418\uFF0C\u53EF\u9078\u64C7\u986F\u793A\u79D2\u6578\u548C\u65E5\u671F\u3002", "zh-Hans": "\u5927\u53F7\u6570\u5B57\u65F6\u949F\uFF0C\u53EF\u9009\u663E\u793A\u79D2\u6570\u548C\u65E5\u671F\u3002" },
3504
+ icon: "clock",
3505
+ category: "time",
3506
+ chrome: "bare",
3507
+ size: { min: { w: 120, h: 60 }, preferred: { w: 320, h: 200 } },
3508
+ options: t.object({
3509
+ showSeconds: t.boolean({ label: { en: "Show seconds", es: "Mostrar segundos", de: "Sekunden anzeigen", "zh-Hant": "\u986F\u793A\u79D2\u6578", "zh-Hans": "\u663E\u793A\u79D2\u6570" } }),
3510
+ timeFormat: t.enum(["inherit", "24h", "12h"], {
3511
+ label: { en: "Time format", es: "Formato de hora", de: "Zeitformat", "zh-Hant": "\u6642\u9593\u683C\u5F0F", "zh-Hans": "\u65F6\u95F4\u683C\u5F0F" },
3512
+ labels: { inherit: { en: "As in Settings", es: "Como en Ajustes", de: "Wie in den Einstellungen", "zh-Hant": "\u4F9D\u7167\u8A2D\u5B9A", "zh-Hans": "\u8DDF\u968F\u8BBE\u7F6E" }, "24h": { en: "24 hours", es: "24 horas", de: "24 Stunden", "zh-Hant": "24 \u5C0F\u6642\u5236", "zh-Hans": "24 \u5C0F\u65F6\u5236" }, "12h": { en: "12 hours", es: "12 horas", de: "12 Stunden", "zh-Hant": "12 \u5C0F\u6642\u5236", "zh-Hans": "12 \u5C0F\u65F6\u5236" } }
3513
+ }),
3514
+ showDate: t.boolean({ default: true, label: { en: "Show the date below", es: "Fecha debajo", de: "Datum darunter anzeigen", "zh-Hant": "\u5728\u4E0B\u65B9\u986F\u793A\u65E5\u671F", "zh-Hans": "\u5728\u4E0B\u65B9\u663E\u793A\u65E5\u671F" } }),
3515
+ dateFormat: t.enum(["long", "short", "numeric"], {
3516
+ label: { en: "Date format", es: "Formato de la fecha", de: "Datumsformat", "zh-Hant": "\u65E5\u671F\u683C\u5F0F", "zh-Hans": "\u65E5\u671F\u683C\u5F0F" },
3517
+ labels: { long: { en: "Long: Monday, 10 November", es: "Larga: lunes, 10 de noviembre", de: "Lang: Montag, 10. November", "zh-Hant": "\u9577\uFF1A11\u670810\u65E5\u661F\u671F\u4E00", "zh-Hans": "\u957F\uFF1A11\u670810\u65E5\u661F\u671F\u4E00" }, short: { en: "Short: Mon, 10 Nov", es: "Corta: lun, 10 nov", de: "Kurz: Mo., 10. Nov.", "zh-Hant": "\u77ED\uFF1A11\u670810\u65E5\u9031\u4E00", "zh-Hans": "\u77ED\uFF1A11\u670810\u65E5\u5468\u4E00" }, numeric: { en: "Numbers: 10/11/2026", es: "En cifras: 10/11/2026", de: "Zahlen: 10.11.2026", "zh-Hant": "\u6578\u5B57\uFF1A2026/11/10", "zh-Hans": "\u6570\u5B57\uFF1A2026/11/10" } },
3518
+ help: { en: "The long one gets small on a narrow tile.", es: "La larga se queda peque\xF1a en una tesela estrecha.", de: "Das lange wird auf einer schmalen Kachel klein.", "zh-Hant": "\u65B9\u683C\u8F03\u7A84\u6642\uFF0C\u9577\u683C\u5F0F\u6703\u8B8A\u5F97\u5F88\u5C0F\u3002", "zh-Hans": "\u683C\u5B50\u8F83\u7A84\u65F6\uFF0C\u957F\u683C\u5F0F\u4F1A\u53D8\u5F97\u5F88\u5C0F\u3002" }
3519
+ }),
3520
+ timeZone: t.string({
3521
+ placeholder: "America/New_York",
3522
+ label: { en: "Time zone", es: "Zona horaria", de: "Zeitzone", "zh-Hant": "\u6642\u5340", "zh-Hans": "\u65F6\u533A" },
3523
+ help: { en: "Empty: this computer's. A zone name (Europe/London, Asia/Tokyo) makes it the clock of another office; give the widget a title.", es: "Vac\xEDa: la de este ordenador. Con el nombre de una zona (Europe/London, Asia/Tokyo) es el reloj de otra oficina; ponle un t\xEDtulo al widget.", de: "Leer: die dieses Computers. Ein Zonenname (Europe/London, Asia/Tokyo) macht sie zur Uhr eines anderen B\xFCros; gib dem Widget einen Titel.", "zh-Hant": "\u7559\u7A7A\uFF1A\u4F7F\u7528\u9019\u53F0\u96FB\u8166\u7684\u6642\u5340\u3002\u586B\u5165\u6642\u5340\u540D\u7A31\uFF08Europe/London\u3001Asia/Tokyo\uFF09\u5C31\u6210\u4E86\u53E6\u4E00\u9593\u8FA6\u516C\u5BA4\u7684\u6642\u9418\uFF1B\u8A18\u5F97\u5E6B\u5C0F\u5DE5\u5177\u52A0\u4E0A\u6A19\u984C\u3002", "zh-Hans": "\u7559\u7A7A\uFF1A\u4F7F\u7528\u8FD9\u53F0\u7535\u8111\u7684\u65F6\u533A\u3002\u586B\u5199\u65F6\u533A\u540D\u79F0\uFF08Europe/London\u3001Asia/Tokyo\uFF09\u5C31\u6210\u4E86\u53E6\u4E00\u4E2A\u529E\u516C\u5BA4\u7684\u65F6\u949F\uFF1B\u8BB0\u5F97\u7ED9\u5C0F\u7EC4\u4EF6\u52A0\u4E2A\u6807\u9898\u3002" }
3524
+ }),
3525
+ color: t.enum(["ink", "accent", "dim"], { label: { en: "Colour", es: "Color", de: "Farbe", "zh-Hant": "\u984F\u8272", "zh-Hans": "\u989C\u8272" }, labels: { ink: { en: "Text", es: "Texto", de: "Text", "zh-Hant": "\u6587\u5B57", "zh-Hans": "\u6587\u5B57" }, accent: { en: "Accent", es: "Acento", de: "Akzent", "zh-Hant": "\u5F37\u8ABF\u8272", "zh-Hans": "\u5F3A\u8C03\u8272" }, dim: { en: "Dim", es: "Tenue", de: "Ged\xE4mpft", "zh-Hant": "\u6DE1\u8272", "zh-Hans": "\u6697\u6DE1" } } }),
3526
+ align: t.enum(["center", "left", "right"], { label: { en: "Alignment", es: "Alineaci\xF3n", de: "Ausrichtung", "zh-Hant": "\u5C0D\u9F4A", "zh-Hans": "\u5BF9\u9F50" } })
3527
+ }),
3528
+ redraw: "second",
3529
+ render(g, { box, now, options, theme, locale, fmt }) {
3530
+ const at = wallClock(now, options.timeZone);
3531
+ const clock2 = options.timeFormat === "inherit" ? fmt : createFormatters({ locale, timeFormat: options.timeFormat, now });
3532
+ const text2 = clock2.time(at, { seconds: options.showSeconds, ampm: false });
3533
+ const full = clock2.hour12 ? clock2.time(at, { seconds: options.showSeconds }) : text2;
3534
+ const mark = full === text2 ? "" : full.replace(text2, "").trim();
3535
+ const markFirst = !!mark && full.startsWith(mark);
3536
+ const dateText = options.showDate ? new Date(at).toLocaleDateString(locale, DATE_FORMATS[options.dateFormat]) : "";
3537
+ const dateH = options.showDate ? Math.min(box.h * 0.2, 40) : 0;
3538
+ const size = fit(g, text2, theme.fonts.monoBold, box.w * (mark ? 0.76 : 0.96), (box.h - dateH * 1.3) * 0.95);
3539
+ const color = options.color === "accent" ? theme.colors.accent : options.color === "dim" ? theme.colors.inkDim : theme.colors.ink;
3540
+ const block = size * 0.78 + (dateH ? dateH * 1.4 : 0);
3541
+ const base2 = box.y + (box.h - block) / 2 + size * 0.78;
3542
+ g.font = `${size}px "${theme.fonts.monoBold}"`;
3543
+ const digitsW = g.measureText(text2).width;
3544
+ const markSize = Math.max(8, Math.round(size * 0.26));
3545
+ g.font = `${markSize}px "${theme.fonts.sansBold}"`;
3546
+ const markW = mark ? g.measureText(mark).width + size * 0.08 : 0;
3547
+ const total = digitsW + markW;
3548
+ const left = options.align === "left" ? box.x : options.align === "right" ? box.x + box.w - total : box.x + (box.w - total) / 2;
3549
+ const digitsX = markFirst ? left + markW : left;
3550
+ g.textAlign = "left";
3551
+ g.fillStyle = color;
3552
+ g.font = `${size}px "${theme.fonts.monoBold}"`;
3553
+ g.fillText(text2, digitsX, base2);
3554
+ if (mark) {
3555
+ g.fillStyle = theme.colors.inkDim;
3556
+ g.font = `${markSize}px "${theme.fonts.sansBold}"`;
3557
+ g.fillText(mark, markFirst ? left : left + digitsW + size * 0.08, base2 - size * 0.78 + markSize * 0.92);
3558
+ }
3559
+ const x = options.align === "left" ? box.x : options.align === "right" ? box.x + box.w : box.x + box.w / 2;
3560
+ g.textAlign = options.align;
3561
+ if (dateH) {
3562
+ const ds = Math.min(dateH, fit(g, dateText, theme.fonts.sans, box.w * 0.96, dateH));
3563
+ g.font = `${ds}px "${theme.fonts.sans}"`;
3564
+ g.fillStyle = theme.colors.inkDim;
3565
+ g.fillText(dateText, x, base2 + dateH * 1.35);
3566
+ }
3567
+ g.textAlign = "left";
3568
+ }
3569
+ });
3570
+ var date = defineWidget({
3571
+ id: "date",
3572
+ name: { en: "Calendar day", es: "D\xEDa del calendario", de: "Kalendertag", "zh-Hant": "\u65E5\u66C6", "zh-Hans": "\u65E5\u5386" },
3573
+ description: { en: "Day of the month, weekday and week number, like a desk calendar.", es: "El d\xEDa del mes, de la semana y el n\xFAmero de semana, como un taco de calendario.", de: "Tag des Monats, Wochentag und Kalenderwoche, wie ein Tischkalender.", "zh-Hant": "\u7576\u6708\u65E5\u671F\u3001\u661F\u671F\u548C\u9031\u6578\uFF0C\u5C31\u50CF\u684C\u66C6\u4E00\u6A23\u3002", "zh-Hans": "\u5F53\u6708\u65E5\u671F\u3001\u661F\u671F\u548C\u5468\u6570\uFF0C\u5C31\u50CF\u53F0\u5386\u4E00\u6837\u3002" },
3574
+ icon: "calendar",
3575
+ category: "time",
3576
+ size: { min: { w: 120, h: 120 }, preferred: { w: 220, h: 300 } },
3577
+ options: t.object({
3578
+ weekdayColor: t.enum(["accent", "ink", "dim", "alert"], {
3579
+ label: { en: "Weekday colour", es: "Color del d\xEDa de la semana", de: "Farbe des Wochentags", "zh-Hant": "\u661F\u671F\u984F\u8272", "zh-Hans": "\u661F\u671F\u989C\u8272" },
3580
+ labels: { accent: { en: "Accent", es: "Acento", de: "Akzent", "zh-Hant": "\u5F37\u8ABF\u8272", "zh-Hans": "\u5F3A\u8C03\u8272" }, ink: { en: "Text", es: "Texto", de: "Text", "zh-Hant": "\u6587\u5B57", "zh-Hans": "\u6587\u5B57" }, dim: { en: "Dim", es: "Tenue", de: "Ged\xE4mpft", "zh-Hant": "\u6DE1\u8272", "zh-Hans": "\u6697\u6DE1" }, alert: { en: "Red, like a tear-off calendar", es: "Rojo, como un taco de calendario", de: "Rot, wie ein Abrei\xDFkalender", "zh-Hant": "\u7D05\u8272\uFF0C\u50CF\u6495\u9801\u65E5\u66C6", "zh-Hans": "\u7EA2\u8272\uFF0C\u50CF\u624B\u6495\u65E5\u5386" } },
3581
+ help: { en: 'On the panel red means "needs you"; a red weekday spends it every day.', es: "En el panel el rojo significa \xABte necesita\xBB; un d\xEDa de la semana en rojo lo gasta a diario.", de: "Auf dem Panel hei\xDFt Rot \u201Ebraucht dich\u201C; ein roter Wochentag verbraucht das jeden Tag.", "zh-Hant": "\u5728\u9762\u677F\u4E0A\uFF0C\u7D05\u8272\u4EE3\u8868\u300C\u9700\u8981\u4F60\u300D\uFF1B\u661F\u671F\u7528\u7D05\u8272\u7B49\u65BC\u6BCF\u5929\u90FD\u5728\u6D88\u8017\u5B83\u3002", "zh-Hans": "\u5728\u5C4F\u5E55\u4E0A\uFF0C\u7EA2\u8272\u4EE3\u8868\u201C\u9700\u8981\u4F60\u201D\uFF1B\u661F\u671F\u7528\u7EA2\u8272\u7B49\u4E8E\u6BCF\u5929\u90FD\u5728\u6D88\u8017\u5B83\u3002" }
3582
+ }),
3583
+ showWeekNumber: t.boolean({ default: true, label: { en: "Show week number", es: "N\xFAmero de semana", de: "Kalenderwoche anzeigen", "zh-Hant": "\u986F\u793A\u9031\u6578", "zh-Hans": "\u663E\u793A\u5468\u6570" } })
3584
+ }),
3585
+ redraw: "minute",
3586
+ render(g, { box, now, options, theme, kit, locale, t: tr }) {
3587
+ const d = new Date(now);
3588
+ const weekday = d.toLocaleDateString(locale, { weekday: "long" });
3589
+ const month = d.toLocaleDateString(locale, { month: hanScript(locale) ? "short" : "long" });
3590
+ const top = Math.min(box.h * 0.16, 36);
3591
+ const c = theme.colors;
3592
+ const weekdayColor = { accent: c.accent, ink: c.ink, dim: c.inkDim, alert: c.alert }[options.weekdayColor];
3593
+ kit.drawTracked(g, weekday, box.x + box.w / 2, box.y + top, { size: top, family: theme.fonts.sansBold, color: weekdayColor, align: "center", smallCaps: true, tracking: 2 });
3594
+ const num = String(d.getDate());
3595
+ const size = fit(g, num, theme.fonts.sansBold, box.w * 0.9, box.h * 0.56);
3596
+ g.font = `${size}px "${theme.fonts.sansBold}"`;
3597
+ g.fillStyle = theme.colors.ink;
3598
+ g.textAlign = "center";
3599
+ g.fillText(num, box.x + box.w / 2, box.y + top * 1.4 + size * 0.86);
3600
+ g.textAlign = "left";
3601
+ const bottom = box.y + box.h - 4;
3602
+ const ms = Math.min(top, box.h * 0.13);
3603
+ let line = month;
3604
+ if (options.showWeekNumber) line += ` \xB7 ${tr({ en: "wk {n}", es: "sem {n}", de: "KW {n}", "zh-Hant": "\u7B2C {n} \u9031", "zh-Hans": "\u7B2C {n} \u5468" }).replace("{n}", String(isoWeek(d)))}`;
3605
+ const ls = Math.min(ms, fit(g, line, theme.fonts.sans, box.w * 0.96, ms));
3606
+ g.font = `${ls}px "${theme.fonts.sans}"`;
3607
+ g.fillStyle = theme.colors.inkDim;
3608
+ g.textAlign = "center";
3609
+ g.fillText(line, box.x + box.w / 2, bottom);
3610
+ g.textAlign = "left";
3611
+ }
3612
+ });
3613
+ function expandHome(path) {
3614
+ return expandPath(path.trim());
3615
+ }
3616
+ var MAX_FILE_CHARS = 2e4;
3617
+ var text = defineWidget({
3618
+ id: "text",
3619
+ name: { en: "Text note", es: "Nota de texto", de: "Textnotiz", "zh-Hant": "\u6587\u5B57\u4FBF\u689D", "zh-Hans": "\u6587\u5B57\u4FBF\u7B7E" },
3620
+ description: { en: "A note or a motto, auto-sized to fill its tile; or the contents of a file a script writes.", es: "Una nota o un lema, con la letra ajustada a la tesela; o lo que un script escribe en un fichero.", de: "Eine Notiz oder ein Motto, in der Gr\xF6\xDFe an die Kachel angepasst; oder der Inhalt einer Datei, die ein Skript schreibt.", "zh-Hant": "\u4E00\u5247\u4FBF\u689D\u6216\u5EA7\u53F3\u9298\uFF0C\u5B57\u9AD4\u81EA\u52D5\u7E2E\u653E\u586B\u6EFF\u65B9\u683C\uFF1B\u6216\u662F\u986F\u793A\u8173\u672C\u5BEB\u5165\u6A94\u6848\u7684\u5167\u5BB9\u3002", "zh-Hans": "\u4E00\u6761\u4FBF\u7B7E\u6216\u5EA7\u53F3\u94ED\uFF0C\u5B57\u53F7\u81EA\u52A8\u7F29\u653E\u586B\u6EE1\u683C\u5B50\uFF1B\u6216\u8005\u663E\u793A\u811A\u672C\u5199\u5165\u6587\u4EF6\u7684\u5185\u5BB9\u3002" },
3621
+ icon: "type",
3622
+ category: "productivity",
3623
+ size: { min: { w: 120, h: 60 }, preferred: { w: 400, h: 160 } },
3624
+ options: t.object({
3625
+ text: t.string({ default: "Hello, panel!", multiline: true, label: { en: "Text", es: "Texto", de: "Text", "zh-Hant": "\u6587\u5B57", "zh-Hans": "\u6587\u5B57" }, help: { en: "With a file, shown until the file can be read.", es: "Con un fichero, se ve hasta que se pueda leer.", de: "Mit einer Datei: angezeigt, bis die Datei gelesen werden kann.", "zh-Hant": "\u4F7F\u7528\u6A94\u6848\u6642\uFF0C\u5728\u6A94\u6848\u53EF\u8B80\u53D6\u4E4B\u524D\u986F\u793A\u9019\u6BB5\u6587\u5B57\u3002", "zh-Hans": "\u4F7F\u7528\u6587\u4EF6\u65F6\uFF0C\u5728\u6587\u4EF6\u53EF\u8BFB\u53D6\u4E4B\u524D\u663E\u793A\u8FD9\u6BB5\u6587\u5B57\u3002" } }),
3626
+ file: t.string({
3627
+ format: "path",
3628
+ risk: "path",
3629
+ placeholder: "~/status.txt",
3630
+ label: { en: "Text file", es: "Fichero de texto", de: "Textdatei", "zh-Hant": "\u6587\u5B57\u6A94", "zh-Hans": "\u6587\u672C\u6587\u4EF6" },
3631
+ help: {
3632
+ en: "Paints what a script writes there (on call, a deploy, the last backup), read again on every refresh. Empty: the text above.",
3633
+ es: "Pinta lo que un script escribe ah\xED (guardia, despliegue, \xFAltima copia), rele\xEDdo en cada refresco. Vac\xEDo: el texto de arriba.",
3634
+ de: "Zeigt, was ein Skript dort hineinschreibt (Bereitschaft, ein Deployment, das letzte Backup), bei jeder Aktualisierung neu gelesen. Leer: der Text oben.",
3635
+ "zh-Hant": "\u986F\u793A\u8173\u672C\u5BEB\u5165\u7684\u5167\u5BB9\uFF08\u503C\u73ED\u3001\u90E8\u7F72\u3001\u4E0A\u6B21\u5099\u4EFD\uFF09\uFF0C\u6BCF\u6B21\u91CD\u65B0\u6574\u7406\u6642\u91CD\u65B0\u8B80\u53D6\u3002\u7559\u7A7A\uFF1A\u4F7F\u7528\u4E0A\u65B9\u7684\u6587\u5B57\u3002",
3636
+ "zh-Hans": "\u663E\u793A\u811A\u672C\u5199\u5165\u7684\u5185\u5BB9\uFF08\u503C\u73ED\u3001\u90E8\u7F72\u3001\u4E0A\u6B21\u5907\u4EFD\uFF09\uFF0C\u6BCF\u6B21\u5237\u65B0\u65F6\u91CD\u65B0\u8BFB\u53D6\u3002\u7559\u7A7A\uFF1A\u4F7F\u7528\u4E0A\u65B9\u7684\u6587\u5B57\u3002"
3637
+ }
3638
+ }),
3639
+ maxSize: t.integer({ default: 64, min: 10, max: 300, unit: "px", slider: true, label: { en: "Largest letter size", es: "Tama\xF1o m\xE1ximo de letra", de: "Gr\xF6\xDFte Schriftgr\xF6\xDFe", "zh-Hant": "\u6700\u5927\u5B57\u9AD4\u5927\u5C0F", "zh-Hans": "\u6700\u5927\u5B57\u53F7" } }),
3640
+ font: t.enum(["sans", "bold", "mono"], {
3641
+ label: { en: "Font", es: "Letra", de: "Schrift", "zh-Hant": "\u5B57\u578B", "zh-Hans": "\u5B57\u4F53" },
3642
+ labels: { sans: { en: "Regular", es: "Normal", de: "Normal", "zh-Hant": "\u4E00\u822C", "zh-Hans": "\u5E38\u89C4" }, bold: { en: "Bold", es: "Negrita", de: "Fett", "zh-Hant": "\u7C97\u9AD4", "zh-Hans": "\u7C97\u4F53" }, mono: { en: "Monospaced", es: "Monoespaciada", de: "Festbreite", "zh-Hant": "\u7B49\u5BEC", "zh-Hans": "\u7B49\u5BBD" } }
3643
+ }),
3644
+ align: t.enum(["left", "center", "right"], { label: { en: "Alignment", es: "Alineaci\xF3n", de: "Ausrichtung", "zh-Hant": "\u5C0D\u9F4A", "zh-Hans": "\u5BF9\u9F50" }, labels: { left: { en: "Left", es: "Izquierda", de: "Links", "zh-Hant": "\u9760\u5DE6", "zh-Hans": "\u5DE6\u5BF9\u9F50" }, center: { en: "Centre", es: "Centro", de: "Mitte", "zh-Hant": "\u7F6E\u4E2D", "zh-Hans": "\u5C45\u4E2D" }, right: { en: "Right", es: "Derecha", de: "Rechts", "zh-Hant": "\u9760\u53F3", "zh-Hans": "\u53F3\u5BF9\u9F50" } } }),
3645
+ valign: t.enum(["middle", "top", "bottom"], {
3646
+ label: { en: "Vertical alignment", es: "Alineaci\xF3n vertical", de: "Vertikale Ausrichtung", "zh-Hant": "\u5782\u76F4\u5C0D\u9F4A", "zh-Hans": "\u5782\u76F4\u5BF9\u9F50" },
3647
+ labels: { middle: { en: "Middle", es: "En medio", de: "Mitte", "zh-Hant": "\u7F6E\u4E2D", "zh-Hans": "\u5C45\u4E2D" }, top: { en: "Top", es: "Arriba", de: "Oben", "zh-Hant": "\u9760\u4E0A", "zh-Hans": "\u9876\u90E8" }, bottom: { en: "Bottom", es: "Abajo", de: "Unten", "zh-Hant": "\u9760\u4E0B", "zh-Hans": "\u5E95\u90E8" } }
3648
+ }),
3649
+ color: t.color({ default: "", label: { en: "Colour (empty = theme)", es: "Color (vac\xEDo = el del tema)", de: "Farbe (leer = Design)", "zh-Hant": "\u984F\u8272\uFF08\u7559\u7A7A = \u4E3B\u984C\u8272\uFF09", "zh-Hans": "\u989C\u8272\uFF08\u7559\u7A7A = \u4E3B\u9898\u8272\uFF09" } })
3650
+ }),
3651
+ intervalMs: 6e4,
3652
+ timeoutMs: 1e4,
3653
+ async fetch({ options, signal }) {
3654
+ if (!options.file.trim()) return { text: null };
3655
+ const body = await readFile(expandHome(options.file), { encoding: "utf8", signal });
3656
+ return { text: body.slice(0, MAX_FILE_CHARS).replace(/\s+$/, "") };
3657
+ },
3658
+ empty: ({ options, data }) => !noteOf(options, data).trim(),
3659
+ render(g, { box, options, data, theme, kit }) {
3660
+ const family = options.font === "mono" ? theme.fonts.mono : options.font === "bold" ? theme.fonts.sansBold : theme.fonts.sans;
3661
+ const paragraphs = noteOf(options, data).split("\n");
3662
+ let size = options.maxSize;
3663
+ let lines = [];
3664
+ for (; ; size -= 2) {
3665
+ lines = paragraphs.flatMap((p) => p.trim() ? kit.wrapLines(g, p, box.w, 50, { size, family }) : [""]);
3666
+ if (size - 2 < 10 || lines.length * size * 1.2 <= box.h && !lines.some((l) => l.endsWith("\u2026"))) break;
3667
+ }
3668
+ const lh = size * 1.2;
3669
+ const spare = Math.max(0, box.h - lines.length * lh);
3670
+ const top = box.y + (options.valign === "top" ? 0 : options.valign === "bottom" ? spare : spare / 2) + size * 0.85;
3671
+ const x = options.align === "center" ? box.x + box.w / 2 : options.align === "right" ? box.x + box.w : box.x;
3672
+ lines.forEach((l, i) => kit.drawTracked(g, l, x, top + i * lh, { size, family, color: options.color || theme.colors.ink, align: options.align }));
3673
+ }
3674
+ });
3675
+ function noteOf(options, data) {
3676
+ return options.file.trim() && typeof data?.text === "string" ? data.text : options.text;
3677
+ }
3678
+ function parseItems(text2) {
3679
+ return text2.split("\n").map((line) => {
3680
+ const [head = "", ...rest] = line.split("|");
3681
+ return { text: head.trim(), detail: rest.join("|").trim() };
3682
+ }).filter((x) => x.text);
3683
+ }
3684
+ var list = defineWidget({
3685
+ id: "list",
3686
+ name: { en: "List", es: "Lista", de: "Liste", "zh-Hant": "\u6E05\u55AE", "zh-Hans": "\u5217\u8868" },
3687
+ description: { en: "A list you write: to-dos, reminders, the shopping. Shows what fits and how many more.", es: "Una lista que escribes t\xFA: pendientes, recordatorios, la compra. Muestra lo que cabe y cu\xE1ntas m\xE1s hay.", de: "Eine Liste, die du schreibst: Aufgaben, Erinnerungen, der Einkauf. Zeigt, was passt, und wie viele noch fehlen.", "zh-Hant": "\u4F60\u81EA\u5DF1\u5BEB\u7684\u6E05\u55AE\uFF1A\u5F85\u8FA6\u4E8B\u9805\u3001\u63D0\u9192\u3001\u8CFC\u7269\u6E05\u55AE\u3002\u986F\u793A\u653E\u5F97\u4E0B\u7684\u9805\u76EE\uFF0C\u4EE5\u53CA\u9084\u6709\u591A\u5C11\u9805\u3002", "zh-Hans": "\u4F60\u81EA\u5DF1\u5199\u7684\u5217\u8868\uFF1A\u5F85\u529E\u4E8B\u9879\u3001\u63D0\u9192\u3001\u8D2D\u7269\u6E05\u5355\u3002\u663E\u793A\u653E\u5F97\u4E0B\u7684\u6761\u76EE\uFF0C\u4EE5\u53CA\u8FD8\u6709\u591A\u5C11\u6761\u3002" },
3688
+ icon: "list",
3689
+ category: "productivity",
3690
+ size: { min: { w: 160, h: 80 }, preferred: { w: 360, h: 240 } },
3691
+ options: t.object({
3692
+ items: t.string({
3693
+ default: "Water the plants\nCall the bank | before 14:00\nBook the dentist | Dr. Ruiz, any morning\nBuy coffee",
3694
+ multiline: true,
3695
+ label: { en: "Items", es: "Elementos", de: "Eintr\xE4ge", "zh-Hant": "\u9805\u76EE", "zh-Hans": "\u6761\u76EE" },
3696
+ help: { en: 'One per line. Text after a "|" is a detail, shown under the item in the detailed layout.', es: "Uno por l\xEDnea. Lo que va tras una \xAB|\xBB es un detalle, que se ve debajo en el formato detallado.", de: "Einer pro Zeile. Text nach einem \u201E|\u201C ist ein Detail, das im ausf\xFChrlichen Layout unter dem Eintrag steht.", "zh-Hant": "\u6BCF\u884C\u4E00\u9805\u3002\u300C|\u300D\u5F8C\u9762\u7684\u6587\u5B57\u662F\u7D30\u7BC0\uFF0C\u5728\u8A73\u7D30\u7248\u9762\u4E2D\u986F\u793A\u65BC\u9805\u76EE\u4E0B\u65B9\u3002", "zh-Hans": "\u6BCF\u884C\u4E00\u6761\u3002\u201C|\u201D\u540E\u9762\u7684\u6587\u5B57\u662F\u8BE6\u60C5\uFF0C\u5728\u8BE6\u7EC6\u5E03\u5C40\u4E2D\u663E\u793A\u5728\u6761\u76EE\u4E0B\u65B9\u3002" }
3697
+ }),
3698
+ ...listOptions({ layouts: ["one-line", "detailed"] })
3699
+ }),
3700
+ empty: ({ options }) => !parseItems(options.items).length,
3701
+ render(g, ctx) {
3702
+ const { box, options, theme, kit } = ctx;
3703
+ const items = parseItems(options.items);
3704
+ if (!items.length) return drawEmpty(g, ctx, ctx.t({ en: "Nothing on the list", es: "Nada en la lista", de: "Nichts auf der Liste", "zh-Hant": "\u6E05\u55AE\u662F\u7A7A\u7684", "zh-Hans": "\u5217\u8868\u4E3A\u7A7A" }));
3705
+ const plan = listLayout(box, items.length, options, {
3706
+ sizes: { "one-line": { min: 18, max: 44 }, detailed: { min: 36, max: 76 } },
3707
+ // Two lines only when some item has a detail and every row has room for them.
3708
+ auto: (b, n) => items.some((x) => x.detail) && b.h / n >= 40 ? "detailed" : "one-line",
3709
+ minRows: 3
3710
+ });
3711
+ const detailed = plan.layout === "detailed";
3712
+ const { textSize: ts, detailSize: ds } = plan;
3713
+ const dot = Math.max(2, ts * 0.22);
3714
+ const tx = box.x + dot * 4;
3715
+ plan.rows.forEach((row, i) => {
3716
+ const item = items[i];
3717
+ const base2 = detailed ? row.y + ts * 1.05 : row.y + plan.rowH * 0.5 + ts * 0.36;
3718
+ g.fillStyle = theme.colors.accent;
3719
+ g.beginPath();
3720
+ g.arc(box.x + dot * 1.5, base2 - ts * 0.34, dot, 0, Math.PI * 2);
3721
+ g.fill();
3722
+ const main = { size: ts, family: theme.fonts.sans, color: theme.colors.ink };
3723
+ kit.drawTracked(g, kit.truncate(g, item.text, box.x + box.w - tx, main), tx, base2, main);
3724
+ if (detailed && item.detail) {
3725
+ const sub = { size: ds, family: theme.fonts.sans, color: theme.colors.inkDim };
3726
+ kit.drawTracked(g, kit.truncate(g, item.detail, box.x + box.w - tx, sub), tx, base2 + ds * 1.45, sub);
3727
+ }
3728
+ });
3729
+ drawMore(g, ctx, plan, { indent: tx - box.x });
3730
+ },
3731
+ demo: () => ({})
3732
+ });
3733
+ var IMAGE_FILE = /\.(png|jpe?g|webp|gif|avif|bmp|svg)$/i;
3734
+ var turns = /* @__PURE__ */ new Map();
3735
+ async function nextInFolder(dir) {
3736
+ const files = (await readdir(dir, { withFileTypes: true })).filter((f) => f.isFile() && IMAGE_FILE.test(f.name)).map((f) => f.name).sort((a, b) => a.localeCompare(b));
3737
+ if (!files.length) return null;
3738
+ const i = ((turns.get(dir) ?? -1) + 1) % files.length;
3739
+ turns.set(dir, i);
3740
+ return join6(dir, files[i]);
3741
+ }
3742
+ function imageUrl(src, now, addTimestamp = false) {
3743
+ const filled = src.replace(/\{now\}/g, String(now)).replace(/\{unix\}/g, String(Math.floor(now / 1e3)));
3744
+ if (!addTimestamp || filled !== src) return filled;
3745
+ const u = new URL(filled);
3746
+ u.searchParams.set("t", String(now));
3747
+ return u.href;
3748
+ }
3749
+ function placeImage(box, w, h, fit2, position) {
3750
+ const s = fit2 === "cover" ? Math.max(box.w / w, box.h / h) : Math.min(box.w / w, box.h / h);
3751
+ const dw = w * s, dh = h * s;
3752
+ const fx = position === "left" ? 0 : position === "right" ? 1 : 0.5;
3753
+ const fy = position === "top" ? 0 : position === "bottom" ? 1 : 0.5;
3754
+ return { x: box.x + (box.w - dw) * fx, y: box.y + (box.h - dh) * fy, w: dw, h: dh };
3755
+ }
3756
+ var load = (canvas, src) => canvas.loadImageScaled ? canvas.loadImageScaled(src, { width: 1920, height: 1080, fit: "cover" }) : canvas.loadImage(src);
3757
+ var image = defineWidget({
3758
+ id: "image",
3759
+ name: { en: "Picture", es: "Imagen", de: "Bild", "zh-Hant": "\u5716\u7247", "zh-Hans": "\u56FE\u7247" },
3760
+ description: { en: "A local image, a folder of them in turn, or a URL (refreshed every few minutes, good for webcams and charts).", es: "Una imagen local, una carpeta de ellas por turnos o una URL (se refresca cada pocos minutos: webcams, gr\xE1ficas).", de: "Ein lokales Bild, ein Ordner voller Bilder im Wechsel oder eine URL (alle paar Minuten aktualisiert, gut f\xFCr Webcams und Diagramme).", "zh-Hant": "\u672C\u6A5F\u5716\u7247\u3001\u8F2A\u6D41\u986F\u793A\u7684\u5716\u7247\u8CC7\u6599\u593E\uFF0C\u6216 URL\uFF08\u6BCF\u9694\u5E7E\u5206\u9418\u91CD\u65B0\u6574\u7406\uFF0C\u9069\u5408\u7DB2\u8DEF\u651D\u5F71\u6A5F\u548C\u5716\u8868\uFF09\u3002", "zh-Hans": "\u672C\u5730\u56FE\u7247\u3001\u8F6E\u6D41\u663E\u793A\u7684\u56FE\u7247\u6587\u4EF6\u5939\uFF0C\u6216 URL\uFF08\u6BCF\u9694\u51E0\u5206\u949F\u5237\u65B0\u4E00\u6B21\uFF0C\u9002\u5408\u7F51\u7EDC\u6444\u50CF\u5934\u548C\u56FE\u8868\uFF09\u3002" },
3761
+ icon: "image",
3762
+ category: "media",
3763
+ chrome: "bare",
3764
+ size: { min: { w: 60, h: 60 }, preferred: { w: 400, h: 300 } },
3765
+ options: t.object({
3766
+ src: t.string({
3767
+ format: "url",
3768
+ risk: ["network", "path"],
3769
+ placeholder: "https://\u2026 or /path/to/image.png",
3770
+ label: { en: "Image (path, folder or URL)", es: "Imagen (ruta, carpeta o URL)", de: "Bild (Pfad, Ordner oder URL)", "zh-Hant": "\u5716\u7247\uFF08\u8DEF\u5F91\u3001\u8CC7\u6599\u593E\u6216 URL\uFF09", "zh-Hans": "\u56FE\u7247\uFF08\u8DEF\u5F84\u3001\u6587\u4EF6\u5939\u6216 URL\uFF09" },
3771
+ help: {
3772
+ en: "A folder shows its pictures by name, the next one on every refresh. In a URL, {now} and {unix} become the current time (milliseconds, seconds).",
3773
+ es: "Una carpeta ense\xF1a sus im\xE1genes por orden de nombre, la siguiente en cada refresco. En una URL, {now} y {unix} se cambian por la hora actual (milisegundos, segundos).",
3774
+ de: "Ein Ordner zeigt seine Bilder nach Namen, bei jeder Aktualisierung das n\xE4chste. In einer URL werden {now} und {unix} durch die aktuelle Zeit ersetzt (Millisekunden, Sekunden).",
3775
+ "zh-Hant": "\u8CC7\u6599\u593E\u6703\u4F9D\u6A94\u540D\u986F\u793A\u5716\u7247\uFF0C\u6BCF\u6B21\u91CD\u65B0\u6574\u7406\u63DB\u4E0B\u4E00\u5F35\u3002\u5728 URL \u4E2D\uFF0C{now} \u548C {unix} \u6703\u63DB\u6210\u76EE\u524D\u6642\u9593\uFF08\u6BEB\u79D2\u3001\u79D2\uFF09\u3002",
3776
+ "zh-Hans": "\u6587\u4EF6\u5939\u4F1A\u6309\u6587\u4EF6\u540D\u663E\u793A\u56FE\u7247\uFF0C\u6BCF\u6B21\u5237\u65B0\u6362\u4E0B\u4E00\u5F20\u3002\u5728 URL \u4E2D\uFF0C{now} \u548C {unix} \u4F1A\u66FF\u6362\u4E3A\u5F53\u524D\u65F6\u95F4\uFF08\u6BEB\u79D2\u3001\u79D2\uFF09\u3002"
3777
+ }
3778
+ }),
3779
+ addTimestamp: t.boolean({
3780
+ label: { en: "Add a timestamp to the URL", es: "A\xF1adir marca de tiempo a la URL", de: "Zeitstempel an die URL anh\xE4ngen", "zh-Hant": "\u5728 URL \u52A0\u4E0A\u6642\u9593\u6233\u8A18", "zh-Hans": "\u5728 URL \u4E2D\u6DFB\u52A0\u65F6\u95F4\u6233" },
3781
+ help: {
3782
+ en: "Appends t=<now> on every refresh, for webcams that would otherwise be served from a cache.",
3783
+ es: "A\xF1ade t=<ahora> en cada refresco, para webcams que si no se sirven desde una cach\xE9.",
3784
+ de: "H\xE4ngt bei jeder Aktualisierung t=<jetzt> an, f\xFCr Webcams, die sonst aus einem Cache k\xE4men.",
3785
+ "zh-Hant": "\u6BCF\u6B21\u91CD\u65B0\u6574\u7406\u6642\u9644\u52A0 t=<now>\uFF0C\u4EE5\u514D\u7DB2\u8DEF\u651D\u5F71\u6A5F\u7684\u756B\u9762\u4F86\u81EA\u5FEB\u53D6\u3002",
3786
+ "zh-Hans": "\u6BCF\u6B21\u5237\u65B0\u65F6\u9644\u52A0 t=<now>\uFF0C\u907F\u514D\u7F51\u7EDC\u6444\u50CF\u5934\u7684\u753B\u9762\u6765\u81EA\u7F13\u5B58\u3002"
3787
+ }
3788
+ }),
3789
+ fit: t.enum(["cover", "contain"], { label: { en: "Fit", es: "Ajuste", de: "Einpassen", "zh-Hant": "\u7E2E\u653E\u65B9\u5F0F", "zh-Hans": "\u7F29\u653E\u65B9\u5F0F" }, labels: { cover: { en: "Fill (crop)", es: "Llenar (recorta)", de: "F\xFCllen (zuschneiden)", "zh-Hant": "\u586B\u6EFF\uFF08\u88C1\u5207\uFF09", "zh-Hans": "\u586B\u6EE1\uFF08\u88C1\u526A\uFF09" }, contain: { en: "Whole image", es: "Imagen entera", de: "Ganzes Bild", "zh-Hant": "\u5B8C\u6574\u5716\u7247", "zh-Hans": "\u5B8C\u6574\u56FE\u7247" } } }),
3790
+ position: t.enum(["center", "top", "bottom", "left", "right"], {
3791
+ label: { en: "Keep in view", es: "Mantener a la vista", de: "Im Blick behalten", "zh-Hant": "\u4FDD\u7559\u53EF\u898B", "zh-Hans": "\u4FDD\u6301\u53EF\u89C1" },
3792
+ labels: { center: { en: "The centre", es: "El centro", de: "Die Mitte", "zh-Hant": "\u4E2D\u592E", "zh-Hans": "\u4E2D\u95F4" }, top: { en: "The top", es: "La parte de arriba", de: "Oben", "zh-Hant": "\u4E0A\u65B9", "zh-Hans": "\u9876\u90E8" }, bottom: { en: "The bottom", es: "La parte de abajo", de: "Unten", "zh-Hant": "\u4E0B\u65B9", "zh-Hans": "\u5E95\u90E8" }, left: { en: "The left", es: "La izquierda", de: "Links", "zh-Hant": "\u5DE6\u5074", "zh-Hans": "\u5DE6\u4FA7" }, right: { en: "The right", es: "La derecha", de: "Rechts", "zh-Hant": "\u53F3\u5074", "zh-Hans": "\u53F3\u4FA7" } },
3793
+ help: { en: "What filling crops last: the sky of a webcam, the axis of a chart.", es: "Lo \xFAltimo que recorta al llenar: el cielo de una webcam, el eje de una gr\xE1fica.", de: "Was beim F\xFCllen zuletzt abgeschnitten wird: der Himmel einer Webcam, die Achse eines Diagramms.", "zh-Hant": "\u586B\u6EFF\u6642\u6700\u5F8C\u624D\u88C1\u5207\u7684\u90E8\u5206\uFF1A\u4F8B\u5982\u7DB2\u8DEF\u651D\u5F71\u6A5F\u7684\u5929\u7A7A\u3001\u5716\u8868\u7684\u5EA7\u6A19\u8EF8\u3002", "zh-Hans": "\u586B\u6EE1\u65F6\u6700\u540E\u624D\u88C1\u526A\u7684\u90E8\u5206\uFF1A\u4F8B\u5982\u7F51\u7EDC\u6444\u50CF\u5934\u7684\u5929\u7A7A\u3001\u56FE\u8868\u7684\u5750\u6807\u8F74\u3002" }
3794
+ }),
3795
+ dim: t.integer({ default: 0, min: 0, max: 90, step: 5, unit: "%", slider: true, label: { en: "Darken", es: "Oscurecer", de: "Abdunkeln", "zh-Hant": "\u8ABF\u6697", "zh-Hans": "\u8C03\u6697" }, help: { en: "Keeps a photo from outshining everything else.", es: "Para que una foto no deslumbre al resto.", de: "Damit ein Foto nicht alles andere \xFCberstrahlt.", "zh-Hant": "\u907F\u514D\u7167\u7247\u6436\u8D70\u5176\u4ED6\u5167\u5BB9\u7684\u98A8\u91C7\u3002", "zh-Hans": "\u907F\u514D\u7167\u7247\u62A2\u4E86\u5176\u4ED6\u5185\u5BB9\u7684\u98CE\u5934\u3002" } })
3796
+ }),
3797
+ intervalMs: 5 * 6e4,
3798
+ async fetch({ options, canvas, signal }) {
3799
+ if (!options.src) return { img: null };
3800
+ if (/^https?:/.test(options.src)) {
3801
+ const res = await fetch(imageUrl(options.src, Date.now(), options.addTimestamp), { signal });
3802
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
3803
+ return { img: await load(canvas, Buffer.from(await res.arrayBuffer())) };
3804
+ }
3805
+ const path = (await stat(options.src)).isDirectory() ? await nextInFolder(options.src) : options.src;
3806
+ if (!path) throw new Error(`no pictures in ${options.src}`);
3807
+ return { img: await load(canvas, path) };
3808
+ },
3809
+ render(g, { box, data, options, theme, kit, t: tr }) {
3810
+ const img = data?.img;
3811
+ if (!img) {
3812
+ g.fillStyle = theme.colors.surface;
3813
+ g.fillRect(box.x, box.y, box.w, box.h);
3814
+ kit.drawTracked(g, options.src ? "\u2026" : tr({ en: "No image", es: "Sin imagen", de: "Kein Bild", "zh-Hant": "\u6C92\u6709\u5716\u7247", "zh-Hans": "\u6CA1\u6709\u56FE\u7247" }), box.x + box.w / 2, box.y + box.h / 2, { size: Math.min(28, box.h / 4), family: theme.fonts.sans, color: theme.colors.inkFaint, align: "center" });
3815
+ return;
3816
+ }
3817
+ const at = placeImage(box, img.width, img.height, options.fit, options.position);
3818
+ g.save();
3819
+ g.beginPath();
3820
+ g.rect(box.x, box.y, box.w, box.h);
3821
+ g.clip();
3822
+ g.drawImage(img, at.x, at.y, at.w, at.h);
3823
+ g.restore();
3824
+ if (options.dim > 0) {
3825
+ g.fillStyle = `rgba(0,0,0,${options.dim / 100})`;
3826
+ g.fillRect(box.x, box.y, box.w, box.h);
3827
+ }
3828
+ }
3829
+ });
3830
+ var src_default = definePlugin({
3831
+ id: "core",
3832
+ name: { en: "Essentials", es: "B\xE1sicos", de: "Grundlagen", "zh-Hant": "\u57FA\u672C\u5DE5\u5177", "zh-Hans": "\u57FA\u7840\u7EC4\u4EF6" },
3833
+ version: "0.2.8",
3834
+ languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
3835
+ sdk: "^0.2.0",
3836
+ // The picture widget reads the image (or folder, or URL) you give it.
3837
+ permissions: { files: ["user"], network: ["user"] },
3838
+ description: { en: "Clock, date, notes, lists and pictures.", es: "Reloj, fecha, notas, listas e im\xE1genes.", de: "Uhr, Datum, Notizen, Listen und Bilder.", "zh-Hant": "\u6642\u9418\u3001\u65E5\u671F\u3001\u4FBF\u689D\u3001\u6E05\u55AE\u548C\u5716\u7247\u3002", "zh-Hans": "\u65F6\u949F\u3001\u65E5\u671F\u3001\u4FBF\u7B7E\u3001\u5217\u8868\u548C\u56FE\u7247\u3002" },
3839
+ author: "Kiosko",
3840
+ license: "MIT",
3841
+ icon: "box",
3842
+ widgets: [clock, date, text, list, image]
3843
+ });
3844
+
3845
+ // plugins/legacy/src/index.ts
3846
+ import { existsSync as existsSync5, statSync as statSync2 } from "node:fs";
3847
+ import { isAbsolute, join as join7 } from "node:path";
3848
+ import { pathToFileURL as pathToFileURL3 } from "node:url";
3849
+ var loaded = /* @__PURE__ */ new Map();
3850
+ function resolveModule(name, dir) {
3851
+ const expanded = expandPath(name);
3852
+ const base2 = isAbsolute(expanded) ? expanded : join7(expandPath(dir), expanded);
3853
+ for (const p of [base2, `${base2}.mjs`, `${base2}.js`, join7(base2, "index.mjs"), join7(base2, "index.js")]) {
3854
+ if (existsSync5(p) && statSync2(p).isFile()) return p;
3855
+ }
3856
+ return null;
3857
+ }
3858
+ async function load2(path) {
3859
+ const hit = loaded.get(path);
3860
+ if (hit) return hit;
3861
+ const m = (await import(pathToFileURL3(path).href)).default;
3862
+ if (!m || typeof m.draw !== "function") throw new Error(`${path} doesn't export a module (with name and draw)`);
3863
+ loaded.set(path, m);
3864
+ return m;
3865
+ }
3866
+ function legacyLook(theme) {
3867
+ return {
3868
+ fonts: { condensed: theme.fonts.sans, condensedBold: theme.fonts.sansBold, mono: theme.fonts.mono, monoBold: theme.fonts.monoBold },
3869
+ colors: { bg: theme.colors.bg, ink: theme.colors.ink, inkDim: theme.colors.inkDim, inkFaint: theme.colors.inkFaint, alert: theme.colors.alert, warn: theme.colors.warn, info: theme.colors.info, ok: theme.colors.ok }
3870
+ };
3871
+ }
3872
+ var optionsSchema = t.object({
3873
+ module: t.string({ risk: "exec", label: { en: "Module (name or path)", es: "M\xF3dulo (nombre o ruta)", de: "Modul (Name oder Pfad)", "zh-Hant": "\u6A21\u7D44\uFF08\u540D\u7A31\u6216\u8DEF\u5F91\uFF09", "zh-Hans": "\u6A21\u5757\uFF08\u540D\u79F0\u6216\u8DEF\u5F84\uFF09" }, placeholder: "pizarra", help: { en: "Looked up in the folder below unless absolute.", es: "Se busca en la carpeta de abajo salvo que sea absoluta.", de: "Wird im Ordner unten gesucht, au\xDFer der Pfad ist absolut.", "zh-Hant": "\u82E5\u4E0D\u662F\u7D55\u5C0D\u8DEF\u5F91\uFF0C\u6703\u5728\u4E0B\u65B9\u7684\u8CC7\u6599\u593E\u4E2D\u5C0B\u627E\u3002", "zh-Hans": "\u5982\u679C\u4E0D\u662F\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u4F1A\u5728\u4E0B\u65B9\u7684\u6587\u4EF6\u5939\u4E2D\u67E5\u627E\u3002" } }),
3874
+ dir: t.string({ default: "~/.aimonitor/modules", format: "path", risk: "exec", label: { en: "Modules folder", es: "Carpeta de m\xF3dulos", de: "Modulordner", "zh-Hant": "\u6A21\u7D44\u8CC7\u6599\u593E", "zh-Hans": "\u6A21\u5757\u6587\u4EF6\u5939" }, advanced: true }),
3875
+ config: t.map({ label: { en: "Module config (key \u2192 value)", es: "Config del m\xF3dulo (clave \u2192 valor)", de: "Modulkonfiguration (Schl\xFCssel \u2192 Wert)", "zh-Hant": "\u6A21\u7D44\u8A2D\u5B9A\uFF08\u9375 \u2192 \u503C\uFF09", "zh-Hans": "\u6A21\u5757\u914D\u7F6E\uFF08\u952E \u2192 \u503C\uFF09" }, help: { en: "Simple values only; numbers and true/false are converted.", es: "S\xF3lo valores simples; n\xFAmeros y true/false se convierten.", de: "Nur einfache Werte; Zahlen und true/false werden umgewandelt.", "zh-Hant": "\u50C5\u9650\u7C21\u55AE\u503C\uFF1B\u6578\u5B57\u548C true/false \u6703\u81EA\u52D5\u8F49\u63DB\u3002", "zh-Hans": "\u4EC5\u9650\u7B80\u5355\u503C\uFF1B\u6570\u5B57\u548C true/false \u4F1A\u81EA\u52A8\u8F6C\u6362\u3002" } }),
3876
+ json: t.string({ multiline: true, label: { en: "Module config as JSON", es: "Config del m\xF3dulo en JSON", de: "Modulkonfiguration als JSON", "zh-Hant": "JSON \u683C\u5F0F\u7684\u6A21\u7D44\u8A2D\u5B9A", "zh-Hans": "JSON \u683C\u5F0F\u7684\u6A21\u5757\u914D\u7F6E" }, help: { en: "For lists and nested values. Wins over the table above.", es: "Para listas y valores anidados. Manda sobre la tabla de arriba.", de: "F\xFCr Listen und verschachtelte Werte. Hat Vorrang vor der Tabelle oben.", "zh-Hant": "\u7528\u65BC\u6E05\u55AE\u548C\u5DE2\u72C0\u503C\uFF0C\u512A\u5148\u65BC\u4E0A\u65B9\u7684\u8868\u683C\u3002", "zh-Hans": "\u7528\u4E8E\u5217\u8868\u548C\u5D4C\u5957\u503C\uFF0C\u4F18\u5148\u4E8E\u4E0A\u65B9\u7684\u8868\u683C\u3002" }, advanced: true })
3877
+ });
3878
+ function moduleConfig(mod, o) {
3879
+ const kv = Object.fromEntries(Object.entries(o.config).map(([k, v]) => [k, v === "true" ? true : v === "false" ? false : v.trim() !== "" && !Number.isNaN(Number(v)) ? Number(v) : v]));
3880
+ let js = {};
3881
+ try {
3882
+ js = o.json.trim() ? JSON.parse(o.json) : {};
3883
+ } catch {
3884
+ }
3885
+ return { ...mod?.defaults ?? {}, ...kv, ...js };
3886
+ }
3887
+ var module2 = defineWidget({
3888
+ id: "module",
3889
+ name: { en: "aimonitor module", es: "M\xF3dulo de aimonitor", de: "aimonitor-Modul", "zh-Hant": "aimonitor \u6A21\u7D44", "zh-Hans": "aimonitor \u6A21\u5757" },
3890
+ description: { en: "Runs a custom card written for aimonitor (defineModule) unchanged.", es: "Ejecuta sin cambios una tarjeta propia escrita para aimonitor (defineModule).", de: "F\xFChrt eine f\xFCr aimonitor geschriebene eigene Karte (defineModule) unver\xE4ndert aus.", "zh-Hant": "\u539F\u5C01\u4E0D\u52D5\u57F7\u884C\u70BA aimonitor \u64B0\u5BEB\u7684\u81EA\u8A02\u5361\u7247\uFF08defineModule\uFF09\u3002", "zh-Hans": "\u539F\u6837\u8FD0\u884C\u4E3A aimonitor \u7F16\u5199\u7684\u81EA\u5B9A\u4E49\u5361\u7247\uFF08defineModule\uFF09\u3002" },
3891
+ icon: "puzzle",
3892
+ category: "productivity",
3893
+ size: { min: { w: 200, h: 120 }, preferred: { w: 600, h: 440 } },
3894
+ options: optionsSchema,
3895
+ intervalMs: 6e4,
3896
+ async fetch({ options, now, log, canvas }) {
3897
+ if (!options.module) throw new Error("no module set");
3898
+ const path = resolveModule(options.module, options.dir);
3899
+ if (!path) throw new Error(`module "${options.module}" not found in ${options.dir}`);
3900
+ const mod = await load2(path);
3901
+ if (options.json.trim()) JSON.parse(options.json);
3902
+ const data = mod.fetch ? await mod.fetch({ config: moduleConfig(mod, options), now, log, canvas }) : void 0;
3903
+ return { path, data };
3904
+ },
3905
+ // The module's own `updateMs`, as in aimonitor.
3906
+ intervalOf: ({ data }) => data ? loaded.get(data.path)?.updateMs : void 0,
3907
+ render(g, ctx) {
3908
+ const mod = ctx.data ? loaded.get(ctx.data.path) : void 0;
3909
+ if (!mod) {
3910
+ ctx.kit.drawTracked(g, ctx.options.module ? "\u2026" : ctx.t({ en: "Pick a module in the options", es: "Elige un m\xF3dulo en las opciones", de: "W\xE4hle ein Modul in den Optionen", "zh-Hant": "\u8ACB\u5728\u9078\u9805\u4E2D\u9078\u64C7\u6A21\u7D44", "zh-Hans": "\u8BF7\u5728\u9009\u9879\u4E2D\u9009\u62E9\u6A21\u5757" }), ctx.box.x, ctx.box.y + 30, { size: 22, family: ctx.theme.fonts.sans, color: ctx.theme.colors.inkDim });
3911
+ return;
3912
+ }
3913
+ const box = ctx.box;
3914
+ mod.draw(g, { config: moduleConfig(mod, ctx.options), data: ctx.data?.data, now: ctx.now, box, ...legacyLook(ctx.theme), kit: ctx.kit, canvas: ctx.canvas });
3915
+ },
3916
+ redraw: "minute",
3917
+ visible({ options, data, now }) {
3918
+ const mod = data ? loaded.get(data.path) : void 0;
3919
+ return mod?.visible?.({ config: moduleConfig(mod, options), data: data?.data, now }) ?? true;
3920
+ },
3921
+ urgent({ options, data, now }) {
3922
+ const mod = data ? loaded.get(data.path) : void 0;
3923
+ return mod?.urgent?.({ config: moduleConfig(mod, options), data: data?.data, now }) ?? false;
3924
+ }
3925
+ });
3926
+ var src_default2 = definePlugin({
3927
+ id: "legacy",
3928
+ name: { en: "aimonitor compatibility", es: "Compatibilidad aimonitor", de: "aimonitor-Kompatibilit\xE4t", "zh-Hant": "aimonitor \u76F8\u5BB9\u6027", "zh-Hans": "aimonitor \u517C\u5BB9" },
3929
+ version: "0.2.8",
3930
+ languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
3931
+ sdk: "^0.2.0",
3932
+ // Runs the aimonitor modules you point it at, and reads their folder.
3933
+ permissions: { exec: ["user"], files: ["user"] },
3934
+ description: { en: "Run your aimonitor custom modules as widgets.", es: "Tus m\xF3dulos propios de aimonitor, como widgets.", de: "Deine eigenen aimonitor-Module als Widgets.", "zh-Hant": "\u5C07\u4F60\u7684 aimonitor \u81EA\u8A02\u6A21\u7D44\u7576\u4F5C\u5C0F\u5DE5\u5177\u57F7\u884C\u3002", "zh-Hans": "\u628A\u4F60\u7684 aimonitor \u81EA\u5B9A\u4E49\u6A21\u5757\u4F5C\u4E3A\u5C0F\u7EC4\u4EF6\u8FD0\u884C\u3002" },
3935
+ author: "Kiosko",
3936
+ license: "MIT",
3937
+ icon: "puzzle",
3938
+ widgets: [module2]
3939
+ });
3940
+
3941
+ // packages/server/src/official.ts
3942
+ var BUNDLED_PLUGIN_IDS = ["agents", "cats", "system", "vitals", "usage", "weather", "calendar", "news", "mirror", "gitlab", "github", "calls", "timesheet", "llm", "gpu", "homeassistant"];
3943
+ var OPTIONAL_PLUGIN_IDS = ["doom", "video", "fractals", "gaming", "logs", "hazards"];
3944
+ var OFFICIAL_PLUGINS = [
3945
+ ...BUNDLED_PLUGIN_IDS.map((id) => ({ id, npm: `kiosko-plugin-${id}`, bundled: true })),
3946
+ ...OPTIONAL_PLUGIN_IDS.map((id) => ({ id, npm: `kiosko-plugin-${id}`, bundled: false }))
3947
+ ];
3948
+ var BUNDLED_PLUGINS = OFFICIAL_PLUGINS.filter((o) => o.bundled);
3949
+
3950
+ // packages/server/src/builtin.ts
3951
+ var BUILTIN_PLUGINS = [src_default, src_default2];
3952
+
3953
+ // packages/server/src/screen-thread.ts
3954
+ await runScreenThread(BUILTIN_PLUGINS);