kiosko 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +28 -19
  2. package/cli.js +1101 -317
  3. package/package.json +17 -16
  4. package/sdk.js +49 -0
  5. package/web/assets/app.js +4 -4
package/cli.js CHANGED
@@ -8,8 +8,8 @@ var __export = (target, all) => {
8
8
 
9
9
  // packages/server/src/cli.ts
10
10
  import { spawn } from "node:child_process";
11
- import { existsSync as existsSync10, readFileSync as readFileSync7, writeFileSync as writeFileSync11 } from "node:fs";
12
- import { dirname as dirname7, join as join14 } from "node:path";
11
+ import { existsSync as existsSync12, readFileSync as readFileSync7, writeFileSync as writeFileSync11 } from "node:fs";
12
+ import { dirname as dirname7, join as join15 } from "node:path";
13
13
 
14
14
  // packages/sdk/src/workday.ts
15
15
  var DEFAULT_WORKDAY = { days: [1, 2, 3, 4, 5], start: "09:00", end: "17:00", hours: 8, holidays: [], byDay: {} };
@@ -85,6 +85,7 @@ function zoomOf(inst) {
85
85
  if (typeof z !== "number" || !Number.isFinite(z)) return 1;
86
86
  return Math.round(Math.min(ZOOM.max, Math.max(ZOOM.min, z)) * 100) / 100;
87
87
  }
88
+ var DEFAULT_MAX_BYTES = 48e4;
88
89
  var counter = 0;
89
90
  function newId(prefix = "id") {
90
91
  counter = (counter + 1) % 1296;
@@ -114,6 +115,7 @@ function newScreen(name, width = 1920, height = 462, device = { driver: "virtual
114
115
  pixelShift: { enabled: true, amplitude: 2, periodMs: 8 * 6e4 },
115
116
  sleepWhenIdle: false,
116
117
  jpegQuality: 90,
118
+ maxBytes: DEFAULT_MAX_BYTES,
117
119
  maxFps: 12
118
120
  };
119
121
  }
@@ -149,189 +151,30 @@ function* widgetsOf(screen) {
149
151
  }
150
152
 
151
153
  // packages/core/src/config/store.ts
152
- import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
154
+ import { copyFileSync, existsSync as existsSync2, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
153
155
  import { dirname } from "node:path";
154
156
 
155
- // packages/core/src/paths.ts
156
- import { homedir, platform } from "node:os";
157
- import { join } from "node:path";
158
- function kioskoHome() {
159
- if (process.env.KIOSKO_HOME) return process.env.KIOSKO_HOME;
160
- const home = homedir();
161
- switch (platform()) {
162
- case "darwin":
163
- return join(home, "Library", "Application Support", "Kiosko");
164
- case "win32":
165
- return join(process.env.APPDATA ?? join(home, "AppData", "Roaming"), "Kiosko");
166
- default:
167
- return join(process.env.XDG_CONFIG_HOME ?? join(home, ".config"), "kiosko");
168
- }
169
- }
170
- var paths = {
171
- get home() {
172
- return kioskoHome();
173
- },
174
- get config() {
175
- return join(kioskoHome(), "config.json");
176
- },
177
- /** External plugins: one folder (or npm package) per plugin. */
178
- get plugins() {
179
- return join(kioskoHome(), "plugins");
180
- },
181
- /** Per-plugin caches: `data/<plugin>`. */
182
- data(plugin) {
183
- return join(kioskoHome(), "data", plugin.replace(/[^a-z0-9._-]/gi, "_"));
184
- }
185
- };
186
- function expandPath(p) {
187
- const v = p.replace(/\$(?:\{(\w+)\}|(\w+))/g, (whole, a, b) => process.env[a ?? b ?? ""] ?? whole);
188
- return v === "~" || v.startsWith("~/") ? join(homedir(), v.slice(1)) : v;
189
- }
190
-
191
- // packages/sdk/src/format.ts
192
- var TIME_FORMATS = ["auto", "24h", "12h"];
193
- var WORDS = {
194
- en: { now: "now", justNow: "just now", ago: (v) => `${v} ago`, wk: "wk", yr: () => "yr", am: "AM", pm: "PM" },
195
- es: { now: "ahora", justNow: "ahora mismo", ago: (v) => `hace ${v}`, wk: "sem", yr: (n) => n === 1 ? "a\xF1o" : "a\xF1os", am: "a. m.", pm: "p. m." }
196
- };
197
- var langOf = (locale) => locale.toLowerCase().split(/[-_]/)[0] ?? "en";
198
- var wordsFor = (locale) => WORDS[langOf(locale)] ?? WORDS.en;
199
- var pad2 = (n) => String(n).padStart(2, "0");
200
- var cycles = /* @__PURE__ */ new Map();
201
- function usesHour12(locale, timeFormat = "auto") {
202
- if (timeFormat !== "auto") return timeFormat === "12h";
203
- let h12 = cycles.get(locale);
204
- if (h12 === void 0) {
205
- try {
206
- const cycle = new Intl.DateTimeFormat(locale, { hour: "numeric" }).resolvedOptions().hourCycle;
207
- h12 = cycle === "h11" || cycle === "h12";
208
- } catch {
209
- h12 = false;
210
- }
211
- cycles.set(locale, h12);
212
- }
213
- return h12;
214
- }
215
- function toMs(at) {
216
- if (typeof at === "number") return at;
217
- if (typeof at === "string") return Date.parse(at);
218
- return at.getTime();
219
- }
220
- function createFormatters(o) {
221
- const w = wordsFor(o.locale);
222
- const hour12 = usesHour12(o.locale, o.timeFormat);
223
- return {
224
- hour12,
225
- time(at, opts = {}) {
226
- const d = new Date(toMs(at));
227
- const h = d.getHours();
228
- const rest = `:${pad2(d.getMinutes())}${opts.seconds ? `:${pad2(d.getSeconds())}` : ""}`;
229
- if (!hour12) return `${pad2(h)}${rest}`;
230
- const base3 = `${h % 12 || 12}${rest}`;
231
- return opts.ampm === false ? base3 : `${base3} ${h < 12 ? w.am : w.pm}`;
232
- },
233
- ago(at, opts = {}) {
234
- const suffix = opts.suffix !== false;
235
- const ms = (opts.now ?? o.now) - toMs(at);
236
- const min = Math.floor(ms / 6e4);
237
- if (!Number.isFinite(min) || min < 1) return suffix ? w.justNow : w.now;
238
- const h = Math.floor(min / 60);
239
- const d = Math.floor(h / 24);
240
- const v = min < 60 ? `${min} min` : h < 24 ? `${h} h` : d < 14 ? `${d} d` : d < 365 ? `${Math.floor(d / 7)} ${w.wk}` : `${Math.floor(d / 365)} ${w.yr(Math.floor(d / 365))}`;
241
- return suffix ? w.ago(v) : v;
242
- },
243
- duration(ms, opts = {}) {
244
- const round = opts.round === "up" ? Math.ceil : opts.round === "nearest" ? Math.round : Math.floor;
245
- const safe2 = Number.isFinite(ms) ? Math.max(0, ms) : 0;
246
- if (opts.seconds && safe2 < 6e4) return `${round(safe2 / 1e3)} s`;
247
- const min = round(safe2 / 6e4);
248
- if (min < 60) return `${min} min`;
249
- const h = Math.floor(min / 60);
250
- if (h < 24) return opts.compact && min % 60 === 0 ? `${h} h` : `${h} h ${pad2(min % 60)}`;
251
- return opts.compact && h % 24 === 0 ? `${h / 24} d` : `${Math.floor(h / 24)} d ${h % 24} h`;
252
- }
253
- };
254
- }
255
-
256
- // packages/core/src/config/normalize.ts
257
- function normalize(raw) {
258
- const { $schema, ...c } = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
259
- const screens = Array.isArray(c.screens) ? c.screens.map(normalizeScreen) : [];
260
- return {
261
- ...typeof $schema === "string" && $schema ? { $schema } : {},
262
- ...DEFAULT_CONFIG,
263
- ...c,
264
- version: CONFIG_VERSION,
265
- timeFormat: TIME_FORMATS.includes(c.timeFormat) ? c.timeFormat : DEFAULT_CONFIG.timeFormat,
266
- // A copy of the defaults: the editor edits the result in place.
267
- workday: { ...JSON.parse(JSON.stringify(DEFAULT_WORKDAY)), ...c.workday ?? {} },
268
- sources: c.sources ?? {},
269
- plugins: { disabled: c.plugins?.disabled ?? [] },
270
- server: { ...DEFAULT_CONFIG.server, ...c.server ?? {} },
271
- screens
272
- };
273
- }
274
- function normalizeScreen(s, i) {
275
- const width = s.width ?? 1920;
276
- const height = s.height ?? 462;
277
- return {
278
- id: s.id ?? `screen-${i + 1}`,
279
- name: s.name ?? `Screen ${i + 1}`,
280
- enabled: s.enabled ?? true,
281
- width,
282
- height,
283
- rotate: s.rotate ?? 0,
284
- device: s.device ?? { driver: "virtual" },
285
- pages: (s.pages ?? []).map((p, j) => ({
286
- id: p.id ?? `page-${j + 1}`,
287
- name: p.name ?? `Page ${j + 1}`,
288
- enabled: p.enabled ?? true,
289
- durationMs: p.durationMs ?? 10 * 6e4,
290
- when: p.when ?? "always",
291
- grid: p.grid ?? suggestGrid(width, height),
292
- gravity: p.gravity ?? "none",
293
- background: p.background ?? {},
294
- tiles: (p.tiles ?? []).map((t2, k) => ({ id: t2.id ?? `tile-${k + 1}`, x: t2.x ?? 0, y: t2.y ?? 0, w: t2.w ?? 1, h: t2.h ?? 1, ...t2.locked ? { locked: true } : {}, widgets: (t2.widgets ?? []).map((w, n) => ({ ...w, id: w.id ?? `w-${i + 1}-${j + 1}-${k + 1}-${n + 1}`, options: w.options ?? {} })), rotateMs: t2.rotateMs ?? 3e4, chrome: t2.chrome ?? "auto" }))
295
- })),
296
- ...s.pinnedPage ? { pinnedPage: s.pinnedPage } : {},
297
- interludes: (s.interludes ?? []).map((x, k) => ({ id: x.id ?? `interlude-${k + 1}`, type: x.type, enabled: x.enabled ?? true, everyMs: x.everyMs ?? 15 * 6e4, maxSeconds: x.maxSeconds ?? 30, options: x.options ?? {} })),
298
- pixelShift: { enabled: true, amplitude: 2, periodMs: 8 * 6e4, ...s.pixelShift ?? {} },
299
- sleepWhenIdle: s.sleepWhenIdle ?? false,
300
- jpegQuality: s.jpegQuality ?? 90,
301
- maxFps: s.maxFps ?? 12
302
- };
303
- }
304
-
305
- // packages/core/src/config/store.ts
306
- function loadConfig(path = paths.config) {
307
- if (!existsSync(path)) return { config: normalize({}), exists: false };
157
+ // packages/core/src/fsperm.ts
158
+ import { execFileSync } from "node:child_process";
159
+ import { chmodSync } from "node:fs";
160
+ import { userInfo } from "node:os";
161
+ function restrictToOwner(path, os = process.platform) {
308
162
  try {
309
- return { config: normalize(JSON.parse(readFileSync(path, "utf8"))), exists: true };
310
- } catch (err) {
311
- return { config: normalize({}), exists: true, error: err instanceof Error ? err.message : String(err) };
312
- }
313
- }
314
- function saveConfig(config2, path = paths.config) {
315
- mkdirSync(dirname(path), { recursive: true });
316
- if (existsSync(path)) {
317
- try {
318
- copyFileSync(path, `${path}.bak`);
319
- chmodSync(`${path}.bak`, 384);
320
- } catch {
163
+ if (os !== "win32") {
164
+ chmodSync(path, 384);
165
+ return;
321
166
  }
322
- }
323
- const tmp = `${path}.tmp`;
324
- const { $schema, ...rest } = config2;
325
- const out = { $schema: $schema || CONFIG_SCHEMA_ID, ...rest };
326
- writeFileSync(tmp, `${JSON.stringify(out, null, 2)}
327
- `, { mode: 384 });
328
- renameSync(tmp, path);
329
- try {
330
- chmodSync(path, 384);
167
+ const user = process.env.USERNAME || userInfo().username;
168
+ const domain = process.env.USERDOMAIN;
169
+ execFileSync("icacls", [path, "/inheritance:r", "/grant:r", `${domain ? `${domain}\\` : ""}${user}:F`], { stdio: "ignore", windowsHide: true, timeout: 5e3 });
331
170
  } catch {
332
171
  }
333
172
  }
334
173
 
174
+ // packages/core/src/paths.ts
175
+ import { existsSync } from "node:fs";
176
+ import { homedir as homedir2, platform } from "node:os";
177
+
335
178
  // packages/sdk/src/plugin.ts
336
179
  var CATEGORIES = [
337
180
  { id: "agents", label: { en: "AI agents", es: "Agentes IA" } },
@@ -535,6 +378,71 @@ function themeById(id) {
535
378
  return THEMES.find((t2) => t2.id === id) ?? DEFAULT_THEME;
536
379
  }
537
380
 
381
+ // packages/sdk/src/format.ts
382
+ var TIME_FORMATS = ["auto", "24h", "12h"];
383
+ var WORDS = {
384
+ en: { now: "now", justNow: "just now", ago: (v) => `${v} ago`, wk: "wk", yr: () => "yr", am: "AM", pm: "PM" },
385
+ es: { now: "ahora", justNow: "ahora mismo", ago: (v) => `hace ${v}`, wk: "sem", yr: (n) => n === 1 ? "a\xF1o" : "a\xF1os", am: "a. m.", pm: "p. m." }
386
+ };
387
+ var langOf = (locale) => locale.toLowerCase().split(/[-_]/)[0] ?? "en";
388
+ var wordsFor = (locale) => WORDS[langOf(locale)] ?? WORDS.en;
389
+ var pad2 = (n) => String(n).padStart(2, "0");
390
+ var cycles = /* @__PURE__ */ new Map();
391
+ function usesHour12(locale, timeFormat = "auto") {
392
+ if (timeFormat !== "auto") return timeFormat === "12h";
393
+ let h12 = cycles.get(locale);
394
+ if (h12 === void 0) {
395
+ try {
396
+ const cycle = new Intl.DateTimeFormat(locale, { hour: "numeric" }).resolvedOptions().hourCycle;
397
+ h12 = cycle === "h11" || cycle === "h12";
398
+ } catch {
399
+ h12 = false;
400
+ }
401
+ cycles.set(locale, h12);
402
+ }
403
+ return h12;
404
+ }
405
+ function toMs(at) {
406
+ if (typeof at === "number") return at;
407
+ if (typeof at === "string") return Date.parse(at);
408
+ return at.getTime();
409
+ }
410
+ function createFormatters(o) {
411
+ const w = wordsFor(o.locale);
412
+ const hour12 = usesHour12(o.locale, o.timeFormat);
413
+ return {
414
+ hour12,
415
+ time(at, opts = {}) {
416
+ const d = new Date(toMs(at));
417
+ const h = d.getHours();
418
+ const rest = `:${pad2(d.getMinutes())}${opts.seconds ? `:${pad2(d.getSeconds())}` : ""}`;
419
+ if (!hour12) return `${pad2(h)}${rest}`;
420
+ const base3 = `${h % 12 || 12}${rest}`;
421
+ return opts.ampm === false ? base3 : `${base3} ${h < 12 ? w.am : w.pm}`;
422
+ },
423
+ ago(at, opts = {}) {
424
+ const suffix = opts.suffix !== false;
425
+ const ms = (opts.now ?? o.now) - toMs(at);
426
+ const min = Math.floor(ms / 6e4);
427
+ if (!Number.isFinite(min) || min < 1) return suffix ? w.justNow : w.now;
428
+ const h = Math.floor(min / 60);
429
+ const d = Math.floor(h / 24);
430
+ const v = min < 60 ? `${min} min` : h < 24 ? `${h} h` : d < 14 ? `${d} d` : d < 365 ? `${Math.floor(d / 7)} ${w.wk}` : `${Math.floor(d / 365)} ${w.yr(Math.floor(d / 365))}`;
431
+ return suffix ? w.ago(v) : v;
432
+ },
433
+ duration(ms, opts = {}) {
434
+ const round = opts.round === "up" ? Math.ceil : opts.round === "nearest" ? Math.round : Math.floor;
435
+ const safe2 = Number.isFinite(ms) ? Math.max(0, ms) : 0;
436
+ if (opts.seconds && safe2 < 6e4) return `${round(safe2 / 1e3)} s`;
437
+ const min = round(safe2 / 6e4);
438
+ if (min < 60) return `${min} min`;
439
+ const h = Math.floor(min / 60);
440
+ if (h < 24) return opts.compact && min % 60 === 0 ? `${h} h` : `${h} h ${pad2(min % 60)}`;
441
+ return opts.compact && h % 24 === 0 ? `${h / 24} d` : `${Math.floor(h / 24)} d ${h % 24} h`;
442
+ }
443
+ };
444
+ }
445
+
538
446
  // packages/sdk/src/list.ts
539
447
  var LAYOUT_LABELS = {
540
448
  auto: { en: "Automatic", es: "Autom\xE1tico" },
@@ -627,19 +535,151 @@ function drawEmpty(g, ctx, message) {
627
535
  kit.drawTracked(g, kit.truncate(g, message, box.w, font), box.x, box.y + size * 1.1, font);
628
536
  }
629
537
 
630
- // packages/sdk/src/context.ts
631
- function createBaseContext(o) {
632
- const locale = o.locale ?? "en";
633
- return {
634
- now: o.now,
635
- locale,
636
- t: (text2) => localize(text2, locale),
637
- fmt: createFormatters({ locale, timeFormat: o.timeFormat ?? "auto", now: o.now }),
638
- log: o.log ?? (() => void 0),
639
- dataDir: o.dataDir ?? "",
640
- ...o.location ? { location: o.location } : {},
641
- workday: o.workday ?? DEFAULT_WORKDAY
642
- };
538
+ // packages/sdk/src/context.ts
539
+ function createBaseContext(o) {
540
+ const locale = o.locale ?? "en";
541
+ return {
542
+ now: o.now,
543
+ locale,
544
+ t: (text2) => localize(text2, locale),
545
+ fmt: createFormatters({ locale, timeFormat: o.timeFormat ?? "auto", now: o.now }),
546
+ log: o.log ?? (() => void 0),
547
+ dataDir: o.dataDir ?? "",
548
+ cacheDir: o.cacheDir ?? o.dataDir ?? "",
549
+ ...o.location ? { location: o.location } : {},
550
+ workday: o.workday ?? DEFAULT_WORKDAY
551
+ };
552
+ }
553
+
554
+ // packages/sdk/src/system.ts
555
+ import { homedir } from "node:os";
556
+ import { join, win32 } from "node:path";
557
+ function expandPath(p, o = {}) {
558
+ const env = o.env ?? process.env;
559
+ let v = p.replace(/\$(?:\{(\w+)\}|(\w+))/g, (whole, a, b) => env[a ?? b ?? ""] ?? whole);
560
+ if ((o.os ?? process.platform) === "win32") v = v.replace(/%([^%\r\n]+)%/g, (whole, name) => env[name] ?? whole);
561
+ const home = o.home ?? homedir();
562
+ if (v === "~") return home;
563
+ return v.startsWith("~/") || v.startsWith("~\\") ? join(home, v.slice(2)) : v;
564
+ }
565
+
566
+ // packages/core/src/paths.ts
567
+ import { join as join2 } from "node:path";
568
+ function kioskoHome() {
569
+ if (process.env.KIOSKO_HOME) return process.env.KIOSKO_HOME;
570
+ const home = homedir2();
571
+ switch (platform()) {
572
+ case "darwin":
573
+ return join2(home, "Library", "Application Support", "Kiosko");
574
+ case "win32":
575
+ return join2(process.env.APPDATA ?? join2(home, "AppData", "Roaming"), "Kiosko");
576
+ default:
577
+ return join2(process.env.XDG_CONFIG_HOME ?? join2(home, ".config"), "kiosko");
578
+ }
579
+ }
580
+ var paths = {
581
+ get home() {
582
+ return kioskoHome();
583
+ },
584
+ get config() {
585
+ return join2(kioskoHome(), "config.json");
586
+ },
587
+ /** External plugins: one folder (or npm package) per plugin. */
588
+ get plugins() {
589
+ return join2(kioskoHome(), "plugins");
590
+ },
591
+ /**
592
+ * Per-plugin re-fetchable caches, in RAM: `$XDG_RUNTIME_DIR/kiosko-cache/<plugin>`
593
+ * (or `/dev/shm/kiosko-cache-<uid>/<plugin>`). Null where there is no tmpfs.
594
+ * On Windows there is none, but the cache belongs in the machine-local
595
+ * profile (`%LOCALAPPDATA%\\Kiosko\\cache`), not in the roaming one `data/` uses.
596
+ */
597
+ cache(plugin) {
598
+ if (platform() === "win32") return join2(process.env.LOCALAPPDATA ?? join2(homedir2(), "AppData", "Local"), "Kiosko", "cache", plugin.replace(/[^a-z0-9._-]/gi, "_"));
599
+ const base3 = 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;
600
+ return base3 && join2(base3, plugin.replace(/[^a-z0-9._-]/gi, "_"));
601
+ },
602
+ /** Per-plugin data that must persist: `data/<plugin>`. */
603
+ data(plugin) {
604
+ return join2(kioskoHome(), "data", plugin.replace(/[^a-z0-9._-]/gi, "_"));
605
+ }
606
+ };
607
+
608
+ // packages/core/src/config/normalize.ts
609
+ function normalize(raw) {
610
+ const { $schema, ...c } = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
611
+ const screens = Array.isArray(c.screens) ? c.screens.map(normalizeScreen) : [];
612
+ return {
613
+ ...typeof $schema === "string" && $schema ? { $schema } : {},
614
+ ...DEFAULT_CONFIG,
615
+ ...c,
616
+ version: CONFIG_VERSION,
617
+ timeFormat: TIME_FORMATS.includes(c.timeFormat) ? c.timeFormat : DEFAULT_CONFIG.timeFormat,
618
+ // A copy of the defaults: the editor edits the result in place.
619
+ workday: { ...JSON.parse(JSON.stringify(DEFAULT_WORKDAY)), ...c.workday ?? {} },
620
+ sources: c.sources ?? {},
621
+ plugins: { disabled: c.plugins?.disabled ?? [] },
622
+ server: { ...DEFAULT_CONFIG.server, ...c.server ?? {} },
623
+ screens
624
+ };
625
+ }
626
+ function normalizeScreen(s, i) {
627
+ const width = s.width ?? 1920;
628
+ const height = s.height ?? 462;
629
+ return {
630
+ id: s.id ?? `screen-${i + 1}`,
631
+ name: s.name ?? `Screen ${i + 1}`,
632
+ enabled: s.enabled ?? true,
633
+ width,
634
+ height,
635
+ rotate: s.rotate ?? 0,
636
+ device: s.device ?? { driver: "virtual" },
637
+ pages: (s.pages ?? []).map((p, j) => ({
638
+ id: p.id ?? `page-${j + 1}`,
639
+ name: p.name ?? `Page ${j + 1}`,
640
+ enabled: p.enabled ?? true,
641
+ durationMs: p.durationMs ?? 10 * 6e4,
642
+ when: p.when ?? "always",
643
+ grid: p.grid ?? suggestGrid(width, height),
644
+ gravity: p.gravity ?? "none",
645
+ background: p.background ?? {},
646
+ tiles: (p.tiles ?? []).map((t2, k) => ({ id: t2.id ?? `tile-${k + 1}`, x: t2.x ?? 0, y: t2.y ?? 0, w: t2.w ?? 1, h: t2.h ?? 1, ...t2.locked ? { locked: true } : {}, widgets: (t2.widgets ?? []).map((w, n) => ({ ...w, id: w.id ?? `w-${i + 1}-${j + 1}-${k + 1}-${n + 1}`, options: w.options ?? {} })), rotateMs: t2.rotateMs ?? 3e4, chrome: t2.chrome ?? "auto" }))
647
+ })),
648
+ ...s.pinnedPage ? { pinnedPage: s.pinnedPage } : {},
649
+ interludes: (s.interludes ?? []).map((x, k) => ({ id: x.id ?? `interlude-${k + 1}`, type: x.type, enabled: x.enabled ?? true, everyMs: x.everyMs ?? 15 * 6e4, maxSeconds: x.maxSeconds ?? 30, options: x.options ?? {} })),
650
+ pixelShift: { enabled: true, amplitude: 2, periodMs: 8 * 6e4, ...s.pixelShift ?? {} },
651
+ sleepWhenIdle: s.sleepWhenIdle ?? false,
652
+ jpegQuality: s.jpegQuality ?? 90,
653
+ maxBytes: Math.max(0, Math.round(s.maxBytes ?? DEFAULT_MAX_BYTES)),
654
+ maxFps: s.maxFps ?? 12
655
+ };
656
+ }
657
+
658
+ // packages/core/src/config/store.ts
659
+ function loadConfig(path = paths.config) {
660
+ if (!existsSync2(path)) return { config: normalize({}), exists: false };
661
+ try {
662
+ return { config: normalize(JSON.parse(readFileSync(path, "utf8"))), exists: true };
663
+ } catch (err) {
664
+ return { config: normalize({}), exists: true, error: err instanceof Error ? err.message : String(err) };
665
+ }
666
+ }
667
+ function saveConfig(config2, path = paths.config) {
668
+ mkdirSync(dirname(path), { recursive: true });
669
+ if (existsSync2(path)) {
670
+ try {
671
+ copyFileSync(path, `${path}.bak`);
672
+ restrictToOwner(`${path}.bak`);
673
+ } catch {
674
+ }
675
+ }
676
+ const tmp = `${path}.tmp`;
677
+ const { $schema, ...rest } = config2;
678
+ const out = { $schema: $schema || CONFIG_SCHEMA_ID, ...rest };
679
+ writeFileSync(tmp, `${JSON.stringify(out, null, 2)}
680
+ `, { mode: 384 });
681
+ renameSync(tmp, path);
682
+ restrictToOwner(path);
643
683
  }
644
684
 
645
685
  // packages/core/src/config/sources.ts
@@ -915,6 +955,18 @@ function configSchema(plugins) {
915
955
  keepalive: { type: "boolean", default: true, description: "Re-send the last frame now and then so the panel keeps it." }
916
956
  }
917
957
  },
958
+ {
959
+ title: "USB (LY panels)",
960
+ description: "Talks to the panel over USB from Kiosko itself (Thermalright Trofeo Vision and other LY panels): no trcc, no Python. On Windows the device needs the WinUSB driver; on Linux a udev rule.",
961
+ type: "object",
962
+ additionalProperties: false,
963
+ required: ["driver"],
964
+ properties: {
965
+ driver: { const: "usb" },
966
+ serial: { type: "string", description: 'USB serial number of the panel. With several identical panels it is the only way to tell them apart, and a serial that is not found is an error, never "another panel". Empty: the first one found.' },
967
+ keepalive: { type: "number", minimum: 0.1, maximum: 2, default: 1, description: "Seconds between re-sends of an unchanged frame; the firmware drops the picture after 2-3 s without one." }
968
+ }
969
+ },
918
970
  {
919
971
  title: "Frame file",
920
972
  description: "Writes frame.jpg atomically into a folder; an external sender takes it to the panel.",
@@ -1011,6 +1063,7 @@ function configSchema(plugins) {
1011
1063
  },
1012
1064
  sleepWhenIdle: { type: "boolean", default: false, description: "Black panel while every widget of the page has nothing worth showing." },
1013
1065
  jpegQuality: { type: "integer", minimum: 0, maximum: 100, default: 90, description: "JPEG quality of the frames; 0 = PNG." },
1066
+ maxBytes: { type: "integer", minimum: 0, maximum: 2e7, default: 48e4, description: "Largest frame to send, in bytes: a bigger one is re-encoded at a lower JPEG quality until it fits. LY panels (Trofeo Vision\u2026) drop frames over ~500 KB. 0 = no limit." },
1014
1067
  maxFps: { type: "integer", minimum: 1, maximum: 30, default: 12, description: "Frames per second ceiling for animations." }
1015
1068
  }
1016
1069
  }
@@ -1453,7 +1506,7 @@ var pageText = (p) => {
1453
1506
  const ts = pageTypes(p);
1454
1507
  return `page ${q2(p.name)}: ${plural(p.tiles.length, "tile")}${ts.length ? ` (${ts.slice(0, 6).join(", ")}${ts.length > 6 ? `, +${ts.length - 6} more` : ""})` : ""}`;
1455
1508
  };
1456
- var deviceText = (d) => d.driver === "trcc" ? `trcc ${d.url}` : d.driver === "file" ? `file ${d.dir}` : d.driver;
1509
+ var deviceText = (d) => d.driver === "trcc" ? `trcc ${d.url}` : d.driver === "file" ? `file ${d.dir}` : d.driver === "usb" ? `usb${d.serial ? ` ${d.serial}` : ""}` : d.driver;
1457
1510
  var changedKeys = (a, b) => [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].filter((k) => !same(a[k], b[k]));
1458
1511
  function diffTiles(before, after, depth, out) {
1459
1512
  const m = match(before.tiles, after.tiles, rect);
@@ -2218,9 +2271,23 @@ function resolveLocale(cfg) {
2218
2271
  function baseContext(cfg, plugin, log, now) {
2219
2272
  let made = false;
2220
2273
  const dir = paths.data(plugin);
2274
+ const cache = paths.cache(plugin);
2275
+ let cacheMade = false;
2221
2276
  const base3 = createBaseContext({ now, locale: resolveLocale(cfg), timeFormat: cfg.timeFormat, workday: cfg.workday, ...cfg.location ? { location: cfg.location } : {}, log: (msg2) => log(plugin, msg2) });
2222
2277
  return {
2223
2278
  ...base3,
2279
+ get cacheDir() {
2280
+ if (!cache) return this.dataDir;
2281
+ if (!cacheMade) {
2282
+ try {
2283
+ mkdirSync2(cache, { recursive: true });
2284
+ } catch {
2285
+ return this.dataDir;
2286
+ }
2287
+ cacheMade = true;
2288
+ }
2289
+ return cache;
2290
+ },
2224
2291
  get dataDir() {
2225
2292
  if (!made) {
2226
2293
  try {
@@ -2235,15 +2302,15 @@ function baseContext(cfg, plugin, log, now) {
2235
2302
  }
2236
2303
 
2237
2304
  // packages/core/src/fonts.ts
2238
- import { existsSync as existsSync2 } from "node:fs";
2305
+ import { existsSync as existsSync3 } from "node:fs";
2239
2306
  import { createRequire } from "node:module";
2240
- import { dirname as dirname2, join as join2 } from "node:path";
2307
+ import { dirname as dirname2, join as join3 } from "node:path";
2241
2308
  import { GlobalFonts as GlobalFonts2 } from "@napi-rs/canvas";
2242
2309
  var require2 = createRequire(import.meta.url);
2243
2310
  var done = false;
2244
2311
  function ttfDir() {
2245
2312
  try {
2246
- return join2(dirname2(require2.resolve("dejavu-fonts-ttf/package.json")), "ttf");
2313
+ return join3(dirname2(require2.resolve("dejavu-fonts-ttf/package.json")), "ttf");
2247
2314
  } catch {
2248
2315
  return null;
2249
2316
  }
@@ -2258,10 +2325,10 @@ function registerFonts(extra = []) {
2258
2325
  if (done && !extra.length) return;
2259
2326
  const dir = ttfDir();
2260
2327
  for (const [family, file, fallback] of FILES) {
2261
- const p = dir && existsSync2(join2(dir, file)) ? join2(dir, file) : fallback;
2262
- if (existsSync2(p)) GlobalFonts2.registerFromPath(p, family);
2328
+ const p = dir && existsSync3(join3(dir, file)) ? join3(dir, file) : fallback;
2329
+ if (existsSync3(p)) GlobalFonts2.registerFromPath(p, family);
2263
2330
  }
2264
- for (const f of extra) if (existsSync2(f.path)) GlobalFonts2.registerFromPath(f.path, f.family);
2331
+ for (const f of extra) if (existsSync3(f.path)) GlobalFonts2.registerFromPath(f.path, f.family);
2265
2332
  done = true;
2266
2333
  }
2267
2334
 
@@ -2349,7 +2416,7 @@ function drawCard(g, rect2, theme) {
2349
2416
  roundRect(g, rect2.x + 0.5, rect2.y + 0.5, rect2.w - 1, rect2.h - 1, theme.radius);
2350
2417
  g.stroke();
2351
2418
  }
2352
- function paintTile(g, input, tile, rect2, out, nextAt, idles) {
2419
+ function paintTile(g, input, tile, rect2, out, nextAt, idles, animatable) {
2353
2420
  const { theme, now, working } = input;
2354
2421
  const candidates = tile.widgets.filter((w) => !w.disabled && whenMatches(w.when, working)).map((w) => resolve(input, w)).filter((r2) => !!r2);
2355
2422
  const entries = candidates.map((r2) => ({ id: r2.inst.id, ...tileState(r2.def, r2.inst, stateCtx(r2, now, working, input.cfg)) }));
@@ -2374,8 +2441,25 @@ function paintTile(g, input, tile, rect2, out, nextAt, idles) {
2374
2441
  idles.push(safe(() => r.def.idle?.(state) ?? false, false));
2375
2442
  const step = redrawStep(r.def, state);
2376
2443
  if (step) nextAt.v = Math.min(nextAt.v, (Math.floor(now / step) + 1) * step);
2377
- const draw = (tg2) => drawTileContent(tg2, input, r, rect2, chrome, out);
2378
- if (!input.cache) {
2444
+ const animation = r.def.animation;
2445
+ if (animation && !input.preview) {
2446
+ animatable.push({
2447
+ tileId: tile.id,
2448
+ instanceId: r.inst.id,
2449
+ type: r.inst.type,
2450
+ def: r.def,
2451
+ data: r.data,
2452
+ sources: r.sources,
2453
+ ended: (plan, completed) => {
2454
+ const [plugin] = r.inst.type.split("/");
2455
+ safe(() => r.def.animationEnded?.({ ...baseContext(input.cfg, plugin, input.log ?? (() => void 0), input.now), options: r.options, plan, completed, data: r.data }), void 0);
2456
+ },
2457
+ ask: (trigger, rnd, prev) => safe(() => animation({ ...state, box: tileBoxes(theme, input.screen.height, r.inst, rect2, chrome).box, trigger, rnd, ...prev !== void 0 ? { prev } : {} }), null)
2458
+ });
2459
+ }
2460
+ const frame = input.animate?.find((a) => a.tileId === tile.id && a.instanceId === r.inst.id)?.frame;
2461
+ const draw = (tg2) => drawTileContent(tg2, input, r, rect2, chrome, out, frame);
2462
+ if (frame || !input.cache) {
2379
2463
  draw(g);
2380
2464
  return;
2381
2465
  }
@@ -2395,23 +2479,28 @@ function paintTile(g, input, tile, rect2, out, nextAt, idles) {
2395
2479
  g.drawImage(canvas, rect2.x, rect2.y);
2396
2480
  input.cache.set(tile.id, { key, refs, canvas, ...out.error ? { error: out.error } : {} });
2397
2481
  }
2398
- function drawTileContent(g, input, r, rect2, chrome, out) {
2482
+ function tileBoxes(theme, screenH, inst, rect2, chrome) {
2483
+ const m = chromeMetrics(theme, screenH, rect2);
2484
+ const pad = chrome === "card" ? m.pad : 0;
2485
+ const top = rect2.y + pad + (inst.title?.trim() && chrome === "card" ? m.titleBar : 0);
2486
+ const outer = { x: rect2.x + pad, y: top, w: Math.max(1, rect2.w - 2 * pad), h: Math.max(1, rect2.y + rect2.h - pad - top) };
2487
+ const zoom = zoomOf(inst);
2488
+ 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) };
2489
+ return { outer, box, zoom };
2490
+ }
2491
+ function drawTileContent(g, input, r, rect2, chrome, out, anim) {
2399
2492
  const { theme, now, working } = input;
2400
2493
  const m = chromeMetrics(theme, input.screen.height, rect2);
2401
2494
  if (chrome === "card") drawCard(g, rect2, theme);
2402
2495
  const pad = chrome === "card" ? m.pad : 0;
2403
- let top = rect2.y + pad;
2404
2496
  const title = r.inst.title?.trim();
2405
2497
  if (title && chrome === "card") {
2406
2498
  g.font = `${m.title}px "${theme.fonts.sans}"`;
2407
2499
  g.fillStyle = theme.colors.inkDim;
2408
2500
  g.textBaseline = "alphabetic";
2409
2501
  g.fillText(fitText(g, title, rect2.w - 2 * pad), rect2.x + pad, rect2.y + pad + m.title * 0.8);
2410
- top = rect2.y + pad + m.titleBar;
2411
2502
  }
2412
- const outer = { x: rect2.x + pad, y: top, w: Math.max(1, rect2.w - 2 * pad), h: Math.max(1, rect2.y + rect2.h - pad - top) };
2413
- const zoom = zoomOf(r.inst);
2414
- 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) };
2503
+ const { outer, box, zoom } = tileBoxes(theme, input.screen.height, r.inst, rect2, chrome);
2415
2504
  const [plugin] = r.inst.type.split("/");
2416
2505
  const ctx = {
2417
2506
  ...baseContext(input.cfg, plugin, input.log ?? (() => void 0), now),
@@ -2421,7 +2510,8 @@ function drawTileContent(g, input, r, rect2, chrome, out) {
2421
2510
  fonts: theme.fonts,
2422
2511
  kit: src_exports,
2423
2512
  canvas: CANVAS,
2424
- preview: !!input.preview
2513
+ preview: !!input.preview,
2514
+ ...anim ? { anim, frame: anim.i } : {}
2425
2515
  };
2426
2516
  g.save();
2427
2517
  roundRect(g, rect2.x, rect2.y, rect2.w, rect2.h, chrome === "card" ? theme.radius : 0);
@@ -2460,18 +2550,19 @@ function composePage(input) {
2460
2550
  const nextAt = { v: Infinity };
2461
2551
  const idles = [];
2462
2552
  const tiles = [];
2553
+ const animatable = [];
2463
2554
  for (const tile of page.tiles) {
2464
2555
  const rect2 = toPx(tile, page.grid, screen.width, screen.height);
2465
2556
  const out = { id: tile.id, rect: rect2, shown: null };
2466
2557
  tiles.push(out);
2467
- paintTile(g, input, tile, rect2, out, nextAt, idles);
2558
+ paintTile(g, input, tile, rect2, out, nextAt, idles, animatable);
2468
2559
  }
2469
2560
  if (input.cache) {
2470
2561
  for (const id of input.cache.keys()) if (!page.tiles.some((t2) => t2.id === id)) input.cache.delete(id);
2471
2562
  }
2472
2563
  g.restore();
2473
2564
  if (screen.pixelShift.enabled && !input.preview) nextAt.v = Math.min(nextAt.v, (Math.floor(now / screen.pixelShift.periodMs) + 1) * screen.pixelShift.periodMs);
2474
- return { canvas, tiles, idle: idles.length > 0 && idles.every(Boolean), nextAt: nextAt.v };
2565
+ return { canvas, tiles, idle: idles.length > 0 && idles.every(Boolean), nextAt: nextAt.v, animatable };
2475
2566
  }
2476
2567
  function rotateCanvas(src, rotate) {
2477
2568
  if (!rotate) return src;
@@ -2506,6 +2597,93 @@ function composeWidget(o) {
2506
2597
  // packages/core/src/runtime.ts
2507
2598
  import { EventEmitter } from "node:events";
2508
2599
 
2600
+ // packages/core/src/animation.ts
2601
+ var MAX_FRAMES = 600;
2602
+ var MAX_CONCURRENT = 1;
2603
+ var DEFAULT_GAP = { minMs: 2e4, maxMs: 6e4 };
2604
+ function checkPlan(plan, maxFps) {
2605
+ const p = plan;
2606
+ if (!p || typeof p !== "object") return "not an object";
2607
+ if (typeof p.id !== "string" || !p.id) return "no id";
2608
+ if (!Number.isInteger(p.frames) || p.frames < 3) return `frames must be an integer of at least 3 (got ${String(p.frames)})`;
2609
+ if (p.frames > MAX_FRAMES) return `too many frames (${p.frames}, at most ${MAX_FRAMES})`;
2610
+ if (typeof p.fps !== "number" || !(p.fps > 0)) return `fps must be positive (got ${String(p.fps)})`;
2611
+ const frames = p.frames;
2612
+ 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;
2613
+ return { plan: p, frames, fps: Math.max(1, Math.min(p.fps, maxFps)), interruptible: p.interruptible !== false, ...hold ? { hold } : {} };
2614
+ }
2615
+ var AnimationScheduler = class {
2616
+ memory = /* @__PURE__ */ new Map();
2617
+ rnd;
2618
+ onInvalid;
2619
+ constructor(rnd = Math.random, onInvalid = () => void 0) {
2620
+ this.rnd = rnd;
2621
+ this.onInvalid = onInvalid;
2622
+ }
2623
+ gapAfter(a, now) {
2624
+ const g = a.def.animationGap ?? DEFAULT_GAP;
2625
+ const min = Math.max(0, g.minMs), max = Math.max(min, g.maxMs);
2626
+ return now + min + this.rnd() * (max - min);
2627
+ }
2628
+ /**
2629
+ * The animations to play now, up to `limit`, among the shown widgets that
2630
+ * have one. Call it only while nothing is playing. A widget seen for the
2631
+ * first time isn't asked: starting up must not set off a gesture. When more
2632
+ * are due than fit, the one that has waited longest goes first (the order
2633
+ * of the page doesn't decide), so none starves.
2634
+ */
2635
+ next(list2, now, maxFps, limit = MAX_CONCURRENT) {
2636
+ const seen = /* @__PURE__ */ new Set();
2637
+ const due = [];
2638
+ for (const a of list2) {
2639
+ seen.add(a.instanceId);
2640
+ const m = this.memory.get(a.instanceId);
2641
+ if (!m) {
2642
+ this.memory.set(a.instanceId, { data: a.data, sources: a.sources, nextIdleAt: this.gapAfter(a, now), endedAt: -Infinity, dueSince: Infinity });
2643
+ continue;
2644
+ }
2645
+ const changed = a.data !== m.data || Object.keys(a.sources).some((k) => a.sources[k] !== m.sources[k]);
2646
+ const prev = m.pending ?? { data: m.data, sources: m.sources };
2647
+ m.data = a.data;
2648
+ m.sources = a.sources;
2649
+ if ((changed || m.pending) && now - m.endedAt >= (a.def.animationCooldownMs ?? 0)) {
2650
+ m.pending = prev;
2651
+ due.push({ a, m, trigger: "data", prev });
2652
+ } else if (now >= m.nextIdleAt) due.push({ a, m, trigger: "idle", prev });
2653
+ }
2654
+ for (const id of this.memory.keys()) if (!seen.has(id)) this.memory.delete(id);
2655
+ for (const d of due) d.m.dueSince = Math.min(d.m.dueSince, d.trigger === "data" ? now : d.m.nextIdleAt);
2656
+ due.sort((x, y) => x.m.dueSince - y.m.dueSince);
2657
+ const out = [];
2658
+ for (const { a, m, trigger, prev } of due) {
2659
+ if (out.length >= limit) break;
2660
+ if (trigger === "idle") m.nextIdleAt = this.gapAfter(a, now);
2661
+ else m.pending = void 0;
2662
+ const plan = a.ask(trigger, this.rnd, trigger === "data" ? prev : void 0);
2663
+ if (plan === null) {
2664
+ m.dueSince = Infinity;
2665
+ continue;
2666
+ }
2667
+ const ok = checkPlan(plan, maxFps);
2668
+ if (typeof ok === "string") {
2669
+ this.onInvalid(a.type, ok);
2670
+ m.dueSince = Infinity;
2671
+ continue;
2672
+ }
2673
+ out.push({ animatable: a, play: ok });
2674
+ }
2675
+ return out;
2676
+ }
2677
+ /** An animation of `instanceId` has just ended (or was cut): its cooldown starts. */
2678
+ ended(instanceId, now, a) {
2679
+ const m = this.memory.get(instanceId);
2680
+ if (!m) return;
2681
+ m.endedAt = now;
2682
+ m.dueSince = Infinity;
2683
+ if (a) m.nextIdleAt = Math.max(m.nextIdleAt, this.gapAfter(a, now));
2684
+ }
2685
+ };
2686
+
2509
2687
  // packages/core/src/data.ts
2510
2688
  var DEFAULT_FETCH_MS = 10 * 6e4;
2511
2689
  var RETRY_MS = 6e4;
@@ -2749,7 +2927,265 @@ function msg(err) {
2749
2927
 
2750
2928
  // packages/core/src/devices.ts
2751
2929
  import { mkdirSync as mkdirSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
2752
- import { join as join3 } from "node:path";
2930
+ import { join as join4 } from "node:path";
2931
+
2932
+ // packages/usb-ly/src/protocol.ts
2933
+ var VENDOR_ID = 1046;
2934
+ var PID_LY = 21512;
2935
+ var PID_LY1 = 21513;
2936
+ var PRODUCT_IDS = [PID_LY, PID_LY1];
2937
+ var CHUNK_SIZE = 512;
2938
+ var CHUNK_HEADER_SIZE = 16;
2939
+ var CHUNK_DATA_SIZE = 496;
2940
+ var USB_WRITE_SIZE = 4096;
2941
+ var REPLY_SIZE = 512;
2942
+ var HANDSHAKE_TIMEOUT_MS = 1e3;
2943
+ var WRITE_TIMEOUT_MS = 5e3;
2944
+ var ACK_TIMEOUT_MS = 1e3;
2945
+ var MAX_FRAME_BYTES = 511871;
2946
+ function variantOf(pid) {
2947
+ return pid === PID_LY1 ? "ly1" : "ly";
2948
+ }
2949
+ function handshakeRequest() {
2950
+ const b = Buffer.alloc(2048);
2951
+ b[0] = 2;
2952
+ b[1] = 255;
2953
+ b[8] = 1;
2954
+ return b;
2955
+ }
2956
+ var UnrecognisedReply = class extends Error {
2957
+ name = "UnrecognisedReply";
2958
+ };
2959
+ function parseHandshake(resp, pid) {
2960
+ if (resp.length < 37 || resp[0] !== 3 || resp[1] !== 255 || resp[8] !== 1) {
2961
+ const at = (i) => resp.length > i ? String(resp[i]) : "N/A";
2962
+ throw new UnrecognisedReply(`handshake validation failed (length ${resp.length}, [0]=${at(0)}, [1]=${at(1)}, [8]=${at(8)})`);
2963
+ }
2964
+ const raw = resp.subarray(0, Math.min(resp.length, 64));
2965
+ if (variantOf(pid) === "ly") {
2966
+ const r = resp[20] <= 3 ? 1 : resp[20];
2967
+ return { pm: 64 + r, sub: (resp[22] ?? 0) + 1, raw };
2968
+ }
2969
+ return { pm: 49 + resp[20], sub: resp[22] ?? 0, raw };
2970
+ }
2971
+ var ANGLES_1920 = [180, 180, 0, 0, 0, 180, 180, 180, 180];
2972
+ var MODELS = {
2973
+ 64: { width: 1600, height: 720, angles: [180, 180, 180, 0, 180, 180, 180, 180, 180] },
2974
+ 65: { width: 1920, height: 462, angles: ANGLES_1920 },
2975
+ 66: { width: 1920, height: 462, angles: ANGLES_1920 },
2976
+ 68: { width: 1280, height: 480, angles: [0, 0, 90, 0, 0, 0, 0, 0, 0] },
2977
+ 69: { width: 1920, height: 440, angles: ANGLES_1920 }
2978
+ };
2979
+ function modelFor(pm, sub) {
2980
+ const m = MODELS[pm] ?? (pm >= 67 && pm <= 80 ? { width: 480, height: 480, angles: Array(9).fill(0) } : void 0);
2981
+ const rotate = m?.angles[sub];
2982
+ return m && rotate !== void 0 ? { width: m.width, height: m.height, rotate } : void 0;
2983
+ }
2984
+ function prepareFrame(payload, pid) {
2985
+ const total = payload.length;
2986
+ const n = Math.floor(total / CHUNK_DATA_SIZE) + 1;
2987
+ const lastLen = total % CHUNK_DATA_SIZE;
2988
+ const cmd2 = variantOf(pid) === "ly" ? 1 : 2;
2989
+ const padTo = variantOf(pid) === "ly" ? 4 : 1;
2990
+ const padded = Math.ceil(n / padTo) * padTo;
2991
+ const out = Buffer.alloc(padded * CHUNK_SIZE);
2992
+ for (let i = 0; i < n; i++) {
2993
+ const o = i * CHUNK_SIZE;
2994
+ const len = i === n - 1 ? lastLen : CHUNK_DATA_SIZE;
2995
+ out[o] = 1;
2996
+ out[o + 1] = 255;
2997
+ out.writeUInt32LE(total, o + 2);
2998
+ out.writeUInt16LE(len, o + 6);
2999
+ out[o + 8] = cmd2;
3000
+ out.writeUInt16LE(n, o + 9);
3001
+ out.writeUInt16LE(i, o + 11);
3002
+ payload.copy(out, o + CHUNK_HEADER_SIZE, i * CHUNK_DATA_SIZE, i * CHUNK_DATA_SIZE + len);
3003
+ }
3004
+ return out;
3005
+ }
3006
+ function frameWrites(frame, pid) {
3007
+ const out = [];
3008
+ for (let pos = 0; pos < frame.length; pos += USB_WRITE_SIZE) {
3009
+ const remaining = frame.length - pos;
3010
+ const size = remaining >= USB_WRITE_SIZE ? USB_WRITE_SIZE : variantOf(pid) === "ly" ? Math.min(2048, remaining) : remaining;
3011
+ out.push(frame.subarray(pos, pos + size));
3012
+ }
3013
+ return out;
3014
+ }
3015
+ function isAccepted(ack) {
3016
+ return ack.length < 9 || ack[8] === 1;
3017
+ }
3018
+
3019
+ // packages/usb-ly/src/transport.ts
3020
+ var PanelNotFound = class extends Error {
3021
+ name = "PanelNotFound";
3022
+ };
3023
+ var UsbUnavailable = class extends Error {
3024
+ name = "UsbUnavailable";
3025
+ };
3026
+ async function loadUsb() {
3027
+ try {
3028
+ const m = await import("usb");
3029
+ const mod = m.getDeviceList ? m : m.default?.getDeviceList ? m.default : m.usb;
3030
+ if (!mod?.getDeviceList) throw new Error("the usb module has no getDeviceList");
3031
+ return mod;
3032
+ } catch (err) {
3033
+ throw new UsbUnavailable(`cannot load the "usb" package (libusb): ${err instanceof Error ? err.message : String(err)}. Install it with: npm install usb`);
3034
+ }
3035
+ }
3036
+ var call = (fn) => new Promise((resolve6, reject) => fn((err, value) => err ? reject(err) : resolve6(value)));
3037
+ async function serialOf(device) {
3038
+ const index = device.deviceDescriptor.iSerialNumber;
3039
+ if (!index) return void 0;
3040
+ const value = await call((cb) => device.getStringDescriptor(index, (e, v) => cb(e ?? null, v)));
3041
+ return value?.trim() || void 0;
3042
+ }
3043
+ async function findPanels(usb, filter = {}) {
3044
+ const out = [];
3045
+ for (const device of usb.getDeviceList()) {
3046
+ const d = device.deviceDescriptor;
3047
+ if (d.idVendor !== VENDOR_ID || !PRODUCT_IDS.includes(d.idProduct) || filter.pid && d.idProduct !== filter.pid) continue;
3048
+ const found = { pid: d.idProduct, location: `${device.busNumber}-${device.deviceAddress}`, device };
3049
+ try {
3050
+ device.open();
3051
+ try {
3052
+ const serial = await serialOf(device);
3053
+ if (serial) found.serial = serial;
3054
+ } finally {
3055
+ device.close();
3056
+ }
3057
+ } catch (err) {
3058
+ found.error = err instanceof Error ? err.message : String(err);
3059
+ }
3060
+ out.push(found);
3061
+ }
3062
+ return out;
3063
+ }
3064
+ var UsbTransport = class _UsbTransport {
3065
+ detached = false;
3066
+ device;
3067
+ iface;
3068
+ out;
3069
+ inp;
3070
+ constructor(device, iface, out, inp) {
3071
+ this.device = device;
3072
+ this.iface = iface;
3073
+ this.out = out;
3074
+ this.inp = inp;
3075
+ }
3076
+ static async open(found, os = process.platform) {
3077
+ const { device } = found;
3078
+ device.open();
3079
+ let iface;
3080
+ let detached = false;
3081
+ try {
3082
+ if (device.configDescriptor?.bConfigurationValue !== 1) await call((cb) => device.setConfiguration(1, (e) => cb(e ?? null)));
3083
+ iface = device.interface(0);
3084
+ if (os === "linux" && iface.isKernelDriverActive()) {
3085
+ iface.detachKernelDriver();
3086
+ detached = true;
3087
+ }
3088
+ iface.claim();
3089
+ const eps = iface.endpoints;
3090
+ const out = eps.find((e) => e.direction === "out");
3091
+ const inp = eps.find((e) => e.direction === "in");
3092
+ if (!out || !inp) throw new Error("the panel has no bulk IN/OUT endpoints on interface 0");
3093
+ const t2 = new _UsbTransport(device, iface, out, inp);
3094
+ t2.detached = detached;
3095
+ return t2;
3096
+ } catch (err) {
3097
+ try {
3098
+ if (iface && detached) iface.attachKernelDriver();
3099
+ } catch {
3100
+ }
3101
+ device.close();
3102
+ throw err;
3103
+ }
3104
+ }
3105
+ async write(data, timeoutMs) {
3106
+ this.out.timeout = timeoutMs;
3107
+ await call((cb) => this.out.transfer(data, (e, n) => cb(e ?? null, n)));
3108
+ }
3109
+ async read(length, timeoutMs = ACK_TIMEOUT_MS) {
3110
+ this.inp.timeout = timeoutMs;
3111
+ return call((cb) => this.inp.transfer(length, (e, d) => cb(e ?? null, d)));
3112
+ }
3113
+ async close() {
3114
+ try {
3115
+ await call((cb) => this.iface.release(true, (e) => cb(e ?? null)));
3116
+ } catch {
3117
+ }
3118
+ try {
3119
+ if (this.detached) this.iface.attachKernelDriver();
3120
+ } catch {
3121
+ }
3122
+ try {
3123
+ this.device.close();
3124
+ } catch {
3125
+ }
3126
+ }
3127
+ };
3128
+ async function openTransport(o = {}) {
3129
+ const usb = o.usb ?? await loadUsb();
3130
+ const all = await findPanels(usb, o.pid ? { pid: o.pid } : {});
3131
+ const found = o.serial ? all.find((p) => p.serial === o.serial) : all[0];
3132
+ if (!found) {
3133
+ const seen = all.map((p) => p.serial ?? `(${p.error ?? "no serial"}) at ${p.location}`).join(", ");
3134
+ throw new PanelNotFound(o.serial ? `no panel with serial ${o.serial}${all.length ? ` (found: ${seen})` : " (none plugged in)"}` : "no LY panel found");
3135
+ }
3136
+ const transport = await UsbTransport.open(found, o.os);
3137
+ return { transport, pid: found.pid, ...found.serial ? { serial: found.serial } : {}, location: found.location };
3138
+ }
3139
+
3140
+ // packages/usb-ly/src/panel.ts
3141
+ var LyPanel = class _LyPanel {
3142
+ queue = Promise.resolve();
3143
+ info = null;
3144
+ transport;
3145
+ pid;
3146
+ meta;
3147
+ constructor(transport, pid, meta = {}) {
3148
+ this.transport = transport;
3149
+ this.pid = pid;
3150
+ this.meta = meta;
3151
+ }
3152
+ /** Opens the first (or `serial`) panel and handshakes. */
3153
+ static async open(o = {}) {
3154
+ const { transport, pid, serial, location } = await openTransport(o);
3155
+ const panel = new _LyPanel(transport, pid, { ...serial ? { serial } : {}, location });
3156
+ try {
3157
+ await panel.connect();
3158
+ } catch (err) {
3159
+ await transport.close();
3160
+ throw err;
3161
+ }
3162
+ return panel;
3163
+ }
3164
+ async connect() {
3165
+ await this.transport.write(handshakeRequest(), HANDSHAKE_TIMEOUT_MS);
3166
+ const hs = parseHandshake(await this.transport.read(REPLY_SIZE, HANDSHAKE_TIMEOUT_MS), this.pid);
3167
+ const model = modelFor(hs.pm, hs.sub);
3168
+ this.info = { ...hs, pid: this.pid, ...this.meta, ...model ? { model } : {} };
3169
+ return this.info;
3170
+ }
3171
+ /**
3172
+ * Writes one JPEG. Resolves `true` if the panel kept it, `false` if it
3173
+ * dropped it (too big: see MAX_FRAME_BYTES). Rejects on a bus error: the
3174
+ * caller reconnects.
3175
+ */
3176
+ send(jpeg) {
3177
+ const run = async () => {
3178
+ for (const part of frameWrites(prepareFrame(jpeg, this.pid), this.pid)) await this.transport.write(part, WRITE_TIMEOUT_MS);
3179
+ return isAccepted(await this.transport.read(REPLY_SIZE, ACK_TIMEOUT_MS));
3180
+ };
3181
+ const next = this.queue.then(run, run);
3182
+ this.queue = next.catch(() => void 0);
3183
+ return next;
3184
+ }
3185
+ close() {
3186
+ return this.transport.close();
3187
+ }
3188
+ };
2753
3189
 
2754
3190
  // packages/trcc-client/src/client.ts
2755
3191
  import { readdirSync, readFileSync as readFileSync2 } from "node:fs";
@@ -2939,6 +3375,7 @@ function pinFrame(o, key, intervalS, onError) {
2939
3375
  // packages/core/src/devices.ts
2940
3376
  function encodeFor(device, jpegQuality) {
2941
3377
  if (device.driver === "file") return device.format ?? "jpeg";
3378
+ if (device.driver === "usb") return "jpeg";
2942
3379
  return jpegQuality > 0 ? "jpeg" : "png";
2943
3380
  }
2944
3381
  var VirtualDevice = class {
@@ -2950,19 +3387,31 @@ var VirtualDevice = class {
2950
3387
  close() {
2951
3388
  }
2952
3389
  };
3390
+ async function renameReplacing(from, to, rename = renameSync3, tries = 8) {
3391
+ for (let i = 1; ; i++) {
3392
+ try {
3393
+ rename(from, to);
3394
+ return;
3395
+ } catch (err) {
3396
+ const code = err.code;
3397
+ if (i >= tries || !(code === "EPERM" || code === "EBUSY" || code === "EACCES")) throw err;
3398
+ await new Promise((r) => setTimeout(r, 5 * i));
3399
+ }
3400
+ }
3401
+ }
2953
3402
  var FileDevice = class {
2954
3403
  status;
2955
3404
  dir;
2956
3405
  constructor(cfg) {
2957
3406
  this.dir = expandPath(cfg.dir);
2958
- this.status = { driver: "file", ok: true, message: `writing ${join3(this.dir, "frame.jpg")}`, framesSent: 0, lastSentAt: null };
3407
+ this.status = { driver: "file", ok: true, message: `writing ${join4(this.dir, "frame.jpg")}`, framesSent: 0, lastSentAt: null };
2959
3408
  }
2960
3409
  async send(frame) {
2961
3410
  try {
2962
3411
  mkdirSync3(this.dir, { recursive: true });
2963
- const tmp = join3(this.dir, ".frame.tmp");
3412
+ const tmp = join4(this.dir, ".frame.tmp");
2964
3413
  writeFileSync3(tmp, frame);
2965
- renameSync3(tmp, join3(this.dir, "frame.jpg"));
3414
+ await renameReplacing(tmp, join4(this.dir, "frame.jpg"));
2966
3415
  this.status.ok = true;
2967
3416
  this.status.framesSent++;
2968
3417
  this.status.lastSentAt = Date.now();
@@ -3019,10 +3468,139 @@ var TrccDevice = class {
3019
3468
  this.stopPin?.();
3020
3469
  }
3021
3470
  };
3022
- function openDevice(cfg, log) {
3471
+ var UsbDevice = class {
3472
+ status = { driver: "usb", ok: false, message: "connecting\u2026", framesSent: 0, lastSentAt: null };
3473
+ cfg;
3474
+ log;
3475
+ rotate;
3476
+ open;
3477
+ retryMs;
3478
+ panel = null;
3479
+ latest = null;
3480
+ fresh = false;
3481
+ lastWrite = 0;
3482
+ retryAt = 0;
3483
+ failures = 0;
3484
+ closed = false;
3485
+ pumping = null;
3486
+ timer = null;
3487
+ lastMessage = "";
3488
+ constructor(cfg, log, o = {}) {
3489
+ this.cfg = cfg;
3490
+ this.log = log;
3491
+ this.rotate = o.rotate;
3492
+ this.open = o.open ?? ((serial) => LyPanel.open(serial ? { serial } : {}));
3493
+ this.retryMs = o.retryMs ?? 1e3;
3494
+ const every = Math.round(Math.min(2, Math.max(0.1, cfg.keepalive ?? 1)) * 1e3);
3495
+ this.timer = setInterval(() => void this.pump(), Math.min(every, 250));
3496
+ this.timer.unref();
3497
+ }
3498
+ say(message, ok) {
3499
+ this.status.ok = ok;
3500
+ this.status.message = message;
3501
+ if (message !== this.lastMessage) {
3502
+ this.lastMessage = message;
3503
+ this.log(message);
3504
+ }
3505
+ }
3506
+ due(now) {
3507
+ return now - this.lastWrite >= Math.min(2, Math.max(0.1, this.cfg.keepalive ?? 1)) * 1e3;
3508
+ }
3509
+ /** Writes what is pending; concurrent callers share one run. */
3510
+ pump() {
3511
+ if (this.pumping) return this.pumping;
3512
+ const run = async () => {
3513
+ while (!this.closed && this.latest && Date.now() >= this.retryAt && (this.fresh || this.due(Date.now()))) {
3514
+ try {
3515
+ const frame = this.latest;
3516
+ this.fresh = false;
3517
+ if (!this.panel) await this.connect();
3518
+ const kept = await this.panel.send(frame);
3519
+ this.lastWrite = Date.now();
3520
+ this.failures = 0;
3521
+ this.status.framesSent++;
3522
+ this.status.lastSentAt = this.lastWrite;
3523
+ if (!kept) this.say(`the panel dropped a ${Math.round(frame.length / 1024)} KB frame (limit ${Math.round(MAX_FRAME_BYTES / 1024)} KB): lower the JPEG quality`, false);
3524
+ else if (!this.status.ok) this.say(this.describe(), true);
3525
+ } catch (err) {
3526
+ this.fresh = true;
3527
+ const p = this.panel;
3528
+ this.panel = null;
3529
+ void p?.close().catch(() => void 0);
3530
+ this.failures++;
3531
+ this.retryAt = Date.now() + Math.min(30 * this.retryMs, this.retryMs * 2 ** Math.min(this.failures, 5));
3532
+ const why = err instanceof Error ? err.message : String(err);
3533
+ this.say(`${why}${this.cfg.serial && !why.includes(this.cfg.serial) ? ` (serial ${this.cfg.serial})` : ""}; retrying`, false);
3534
+ }
3535
+ }
3536
+ };
3537
+ this.pumping = run().finally(() => this.pumping = null);
3538
+ return this.pumping;
3539
+ }
3540
+ describe() {
3541
+ const i = this.panel?.info;
3542
+ if (!i) return "usb";
3543
+ return `usb ${i.serial ?? i.location ?? ""} PM ${i.pm} SUB ${i.sub}${i.model ? ` ${i.model.width}\xD7${i.model.height}` : ""}`.replace(/\s+/g, " ");
3544
+ }
3545
+ async connect() {
3546
+ const panel = await this.open(this.cfg.serial);
3547
+ this.panel = panel;
3548
+ const m = panel.info?.model;
3549
+ if (m) {
3550
+ this.status.detected = { width: m.width, height: m.height };
3551
+ if (this.rotate !== void 0 && m.rotate !== this.rotate) this.log(`the panel's firmware expects rotation ${m.rotate}\xB0 but this screen has ${this.rotate}\xB0: the picture may come out turned`);
3552
+ }
3553
+ this.say(this.describe(), true);
3554
+ }
3555
+ async send(frame) {
3556
+ this.latest = frame;
3557
+ this.fresh = true;
3558
+ await this.pump();
3559
+ }
3560
+ close() {
3561
+ this.closed = true;
3562
+ if (this.timer) clearInterval(this.timer);
3563
+ this.timer = null;
3564
+ const p = this.panel;
3565
+ this.panel = null;
3566
+ void p?.close().catch(() => void 0);
3567
+ }
3568
+ };
3569
+ async function listUsb() {
3570
+ try {
3571
+ const found = await findPanels(await loadUsb());
3572
+ return { ok: true, panels: found.map((f) => ({ ...f.serial ? { serial: f.serial } : {}, pid: f.pid, location: f.location, ...f.error ? { error: f.error } : {} })) };
3573
+ } catch (err) {
3574
+ return { ok: false, panels: [], error: err instanceof Error ? err.message : String(err) };
3575
+ }
3576
+ }
3577
+ async function discoverUsb() {
3578
+ try {
3579
+ const found = await findPanels(await loadUsb());
3580
+ const out = [];
3581
+ for (const f of found) {
3582
+ let model;
3583
+ if (f.serial) {
3584
+ try {
3585
+ const p = await LyPanel.open({ serial: f.serial });
3586
+ model = p.info?.model;
3587
+ await p.close();
3588
+ } catch {
3589
+ }
3590
+ }
3591
+ out.push({ serial: f.serial ?? "", key: f.serial ?? `usb ${f.location}`, width: model?.width ?? 0, height: model?.height ?? 0, location: f.location, ...f.error ? { error: f.error } : {} });
3592
+ }
3593
+ return out;
3594
+ } catch {
3595
+ return [];
3596
+ }
3597
+ }
3598
+ function openDevice(cfg, log, rotate) {
3023
3599
  switch (cfg.driver) {
3024
3600
  case "trcc":
3025
3601
  return new TrccDevice(cfg, log);
3602
+ case "usb":
3603
+ return new UsbDevice(cfg, log, rotate === void 0 ? {} : { rotate });
3026
3604
  case "file":
3027
3605
  return new FileDevice(cfg);
3028
3606
  default:
@@ -3049,6 +3627,20 @@ function lazyJpeg(c) {
3049
3627
  function encode(c, kind, quality) {
3050
3628
  return kind === "jpeg" ? c.toBuffer("image/jpeg", Math.max(1, Math.min(100, quality || 90))) : c.toBuffer("image/png");
3051
3629
  }
3630
+ var MIN_FIT_QUALITY = 20;
3631
+ function encodeFit(c, kind, quality, maxBytes) {
3632
+ const q0 = Math.max(1, Math.min(100, quality || 90));
3633
+ let out = encode(c, kind, q0);
3634
+ if (kind !== "jpeg" || !(maxBytes > 0) || out.length <= maxBytes) return { out, quality: q0, over: false };
3635
+ let q3 = q0;
3636
+ while (q3 > MIN_FIT_QUALITY) {
3637
+ q3 = Math.max(MIN_FIT_QUALITY, q3 - 10);
3638
+ out = encode(c, kind, q3);
3639
+ if (out.length <= maxBytes) return { out, quality: q3, over: false };
3640
+ }
3641
+ return { out, quality: q3, over: true };
3642
+ }
3643
+ var kb = (n) => `${Math.round(n / 1e3)} KB`;
3052
3644
  var ScreenRunner = class {
3053
3645
  device;
3054
3646
  deviceKey;
@@ -3060,26 +3652,47 @@ var ScreenRunner = class {
3060
3652
  pinned = null;
3061
3653
  playedSlot = /* @__PURE__ */ new Map();
3062
3654
  interlude = null;
3655
+ /** When `fit` last told the log that frames were shrunk, to say it now and then, not every frame. */
3656
+ fitLoggedAt = 0;
3063
3657
  /** Instance ids on the current page, to know if a data change concerns us. */
3064
3658
  visibleIds = /* @__PURE__ */ new Set();
3065
3659
  sourceTypes = /* @__PURE__ */ new Set();
3066
3660
  page = null;
3067
3661
  /** Rendered tiles reused between frames (see compositor's TileCache). */
3068
3662
  tiles = /* @__PURE__ */ new Map();
3663
+ /** The widgets of the last painted page that can animate, and when to ask them (see animation.ts). */
3664
+ animatable = [];
3665
+ scheduler;
3666
+ /** Set while a widget's animation plays: its widget type. */
3667
+ animating = null;
3668
+ closed = false;
3069
3669
  screen;
3070
3670
  rt;
3071
3671
  constructor(screen, rt) {
3072
3672
  this.screen = screen;
3073
3673
  this.rt = rt;
3074
3674
  this.deviceKey = JSON.stringify(screen.device);
3075
- this.device = openDevice(screen.device, (m) => rt.log(`screen:${screen.name}`, m));
3675
+ this.device = openDevice(screen.device, (m) => rt.log(`screen:${screen.name}`, m), screen.rotate);
3076
3676
  this.pinned = screen.pinnedPage ?? null;
3677
+ this.scheduler = new AnimationScheduler(() => rt.rnd(), (type, why) => rt.log(type, `animation ignored: ${why}`));
3678
+ }
3679
+ /** Encodes a frame within the screen's `maxBytes`, saying so in the log (at most every 10 min) when it had to shrink it. */
3680
+ fit(c, kind, quality, screen) {
3681
+ const r = encodeFit(c, kind, quality, screen.maxBytes);
3682
+ if ((r.quality !== Math.max(1, Math.min(100, quality || 90)) || r.over) && Date.now() - this.fitLoggedAt > 10 * 6e4) {
3683
+ this.fitLoggedAt = Date.now();
3684
+ this.rt.log(
3685
+ `screen:${screen.name}`,
3686
+ 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)})`
3687
+ );
3688
+ }
3689
+ return r.out;
3077
3690
  }
3078
3691
  reconfigure(screen) {
3079
3692
  const key = JSON.stringify(screen.device);
3080
3693
  if (key !== this.deviceKey) {
3081
3694
  this.device.close();
3082
- this.device = openDevice(screen.device, (m) => this.rt.log(`screen:${screen.name}`, m));
3695
+ this.device = openDevice(screen.device, (m) => this.rt.log(`screen:${screen.name}`, m), screen.rotate);
3083
3696
  this.deviceKey = key;
3084
3697
  this.last = null;
3085
3698
  }
@@ -3104,9 +3717,13 @@ var ScreenRunner = class {
3104
3717
  this.dirty = true;
3105
3718
  this.rt.refreshWanted();
3106
3719
  }
3107
- if (!this.dirty && now < this.nextAt) return;
3720
+ if (!this.dirty && now < this.nextAt) {
3721
+ await this.maybeAnimate(now);
3722
+ return;
3723
+ }
3108
3724
  this.dirty = false;
3109
3725
  await this.paint(page, now);
3726
+ await this.maybeAnimate(now);
3110
3727
  } catch (err) {
3111
3728
  this.rt.log(`screen:${this.screen.name}`, `paint failed: ${err instanceof Error ? err.message : String(err)}`);
3112
3729
  } finally {
@@ -3134,12 +3751,14 @@ var ScreenRunner = class {
3134
3751
  cache: this.tiles
3135
3752
  });
3136
3753
  canvas = result.canvas;
3754
+ this.animatable = result.animatable;
3137
3755
  this.nextAt = Math.min(result.nextAt, now + 6e4);
3138
3756
  } else {
3139
3757
  canvas = CANVAS.createCanvas(screen.width, screen.height);
3140
3758
  const g = canvas.getContext("2d");
3141
3759
  g.fillStyle = "#000";
3142
3760
  g.fillRect(0, 0, screen.width, screen.height);
3761
+ this.animatable = [];
3143
3762
  this.nextAt = now + 6e4;
3144
3763
  }
3145
3764
  const sleeping = !!(screen.sleepWhenIdle && result?.idle);
@@ -3149,7 +3768,7 @@ var ScreenRunner = class {
3149
3768
  g.fillRect(0, 0, screen.width, screen.height);
3150
3769
  }
3151
3770
  const kind = encodeFor(screen.device, screen.jpegQuality);
3152
- const out = encode(rotateCanvas(canvas, screen.rotate), kind, screen.jpegQuality);
3771
+ const out = this.fit(rotateCanvas(canvas, screen.rotate), kind, screen.jpegQuality, screen);
3153
3772
  this.lastInfo = { screenId: screen.id, pageId: page?.id ?? null, at: now, image: lazyJpeg(canvas), tiles: result?.tiles ?? [], interlude: null, sleeping };
3154
3773
  this.rt.emit("frame", this.lastInfo);
3155
3774
  if (this.last?.equals(out)) return;
@@ -3196,7 +3815,7 @@ var ScreenRunner = class {
3196
3815
  } finally {
3197
3816
  g.restore();
3198
3817
  }
3199
- const out = encode(rotateCanvas(canvas, this.screen.rotate), kind, this.screen.jpegQuality || 85);
3818
+ const out = this.fit(rotateCanvas(canvas, this.screen.rotate), kind, this.screen.jpegQuality || 85, this.screen);
3200
3819
  await this.device.send(out);
3201
3820
  if (i % 3 === 0) {
3202
3821
  const snap = CANVAS.createCanvas(canvas.width, canvas.height);
@@ -3212,6 +3831,110 @@ var ScreenRunner = class {
3212
3831
  this.dirty = true;
3213
3832
  return true;
3214
3833
  }
3834
+ /**
3835
+ * Plays the animations the shown widgets ask for, if any is due (see
3836
+ * animation.ts). Like an interlude it runs inside `update`, so nothing else
3837
+ * is painted meanwhile, but unlike it the page stays in place: only the
3838
+ * widgets' tiles change from frame to frame. How many play together is
3839
+ * `Runtime.maxConcurrent` (one by default); the rest wait their turn.
3840
+ */
3841
+ async maybeAnimate(now) {
3842
+ if (!this.screen.enabled || this.closed || this.lastInfo?.sleeping || !this.animatable.length) return;
3843
+ const due = this.scheduler.next(this.animatable, now, this.screen.maxFps, this.rt.maxConcurrent);
3844
+ if (!due.length) return;
3845
+ this.animating = due.map((d) => d.animatable.type).join(", ");
3846
+ let completed = false;
3847
+ try {
3848
+ completed = await this.playAnimations(due, now);
3849
+ } finally {
3850
+ this.animating = null;
3851
+ this.last = null;
3852
+ this.dirty = true;
3853
+ for (const d of due) {
3854
+ this.scheduler.ended(d.animatable.instanceId, Date.now(), d.animatable);
3855
+ d.animatable.ended(d.play.plan, completed);
3856
+ }
3857
+ }
3858
+ }
3859
+ /**
3860
+ * One timeline for all: the fastest plan sets the rate and each animation
3861
+ * advances at its own, so they start together and the longest decides when
3862
+ * it is over. The ones that finish earlier stay at rest. With only one it
3863
+ * is just that animation's own frames.
3864
+ */
3865
+ async playAnimations(items, now) {
3866
+ const page = this.page;
3867
+ if (!page) return false;
3868
+ const { screen } = this;
3869
+ const fps = Math.max(...items.map((x) => x.play.fps));
3870
+ const seconds = Math.max(...items.map((x) => (x.play.frames - 1) / x.play.fps));
3871
+ const frames = Math.round(seconds * fps) + 1;
3872
+ const interruptible = items.every((x) => x.play.interruptible);
3873
+ const hold = items.length === 1 ? items[0].play.hold : void 0;
3874
+ const abort = () => this.closed || interruptible && this.dirty || !this.screen.enabled;
3875
+ this.dirty = false;
3876
+ const memoData = /* @__PURE__ */ new Map();
3877
+ const memoSources = /* @__PURE__ */ new Map();
3878
+ const working = this.rt.working(now);
3879
+ const kind = encodeFor(screen.device, screen.jpegQuality || 85);
3880
+ const sent = [];
3881
+ const t0 = Date.now();
3882
+ for (let s = 1; s < frames - 1; s++) {
3883
+ if (abort()) return false;
3884
+ const animate = items.flatMap(({ animatable: a, play }) => {
3885
+ const i = Math.round(s / fps * play.fps);
3886
+ return i <= 0 || i >= play.frames - 1 ? [] : [{ tileId: a.tileId, instanceId: a.instanceId, frame: { plan: play.plan, i, t: i / (play.frames - 1) } }];
3887
+ });
3888
+ const result = composePage({
3889
+ cfg: this.rt.config,
3890
+ screen,
3891
+ page,
3892
+ theme: this.rt.theme(),
3893
+ registry: this.rt.registry,
3894
+ now,
3895
+ working,
3896
+ dataOf: (inst) => {
3897
+ if (!memoData.has(inst.id)) memoData.set(inst.id, this.rt.fetches.data(inst.id));
3898
+ return memoData.get(inst.id);
3899
+ },
3900
+ sourcesOf: (types2) => {
3901
+ const k = JSON.stringify(types2 ?? []);
3902
+ if (!memoSources.has(k)) memoSources.set(k, this.rt.hub.pick(types2));
3903
+ return memoSources.get(k);
3904
+ },
3905
+ log: this.rt.log,
3906
+ demo: this.rt.demoMode,
3907
+ cache: this.tiles,
3908
+ animate
3909
+ });
3910
+ sent.push({ out: this.fit(rotateCanvas(result.canvas, screen.rotate), kind, screen.jpegQuality || 85, screen), snap: s % 3 === 1 ? result.canvas : null });
3911
+ await new Promise((r) => setImmediate(r));
3912
+ }
3913
+ const what = items.map((x) => `${x.animatable.type} ${x.play.plan.id}`).join(" + ");
3914
+ this.rt.log(`screen:${screen.name}`, `animating ${what}: ${sent.length} frames at ${fps} fps (painted in ${Date.now() - t0} ms)`);
3915
+ const holdAt = hold ? Math.max(0, Math.min(sent.length - 1, hold.index - 1)) : -1;
3916
+ let start = Date.now();
3917
+ for (let k = 0; k < sent.length; k++) {
3918
+ if (abort()) return false;
3919
+ const due = Math.floor((Date.now() - start) * fps / 1e3);
3920
+ if (k < due - 1 && k !== holdAt && k < sent.length - 1) continue;
3921
+ await this.device.send(sent[k].out);
3922
+ const snap = sent[k].snap;
3923
+ if (snap) {
3924
+ this.lastInfo = { screenId: screen.id, pageId: page.id, at: Date.now(), image: lazyJpeg(snap), tiles: [], interlude: null, animation: items.map((x) => x.animatable.type).join(", "), sleeping: false };
3925
+ this.rt.emit("frame", this.lastInfo);
3926
+ }
3927
+ if (hold && k === holdAt) {
3928
+ const until = Date.now() + hold.ms;
3929
+ while (Date.now() < until && !abort()) await new Promise((r) => setTimeout(r, Math.min(250, until - Date.now())));
3930
+ start = Date.now() - (k + 1) * 1e3 / fps;
3931
+ continue;
3932
+ }
3933
+ const wait = start + (k + 1) * 1e3 / fps - Date.now();
3934
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));
3935
+ }
3936
+ return true;
3937
+ }
3215
3938
  async playNow(slotId) {
3216
3939
  if (this.busy) return;
3217
3940
  this.busy = true;
@@ -3225,6 +3948,7 @@ var ScreenRunner = class {
3225
3948
  this.interlude = null;
3226
3949
  }
3227
3950
  close() {
3951
+ this.closed = true;
3228
3952
  this.interlude = null;
3229
3953
  this.device.close();
3230
3954
  }
@@ -3236,6 +3960,10 @@ var Runtime = class extends EventEmitter {
3236
3960
  runners = /* @__PURE__ */ new Map();
3237
3961
  timer = null;
3238
3962
  logs = [];
3963
+ /** How many animations play together on a screen (see animation.ts). */
3964
+ maxConcurrent = MAX_CONCURRENT;
3965
+ /** Random numbers for the animations; tests replace it with a seeded one. */
3966
+ rnd = Math.random;
3239
3967
  registry;
3240
3968
  /**
3241
3969
  * Demo mode: no source or fetch runs, every widget paints its sample data.
@@ -3363,6 +4091,7 @@ var Runtime = class extends EventEmitter {
3363
4091
  page: r.page?.id ?? null,
3364
4092
  pinned: r.pinned,
3365
4093
  interlude: r.interlude?.type ?? null,
4094
+ animation: r.animating,
3366
4095
  device: r.device.status,
3367
4096
  lastFrameAt: r.lastInfo?.at ?? null,
3368
4097
  sleeping: r.lastInfo?.sleeping ?? false
@@ -3408,14 +4137,14 @@ function withLook(cfg, look) {
3408
4137
  }
3409
4138
 
3410
4139
  // packages/core/src/registry.ts
3411
- import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync, writeFileSync as writeFileSync4 } from "node:fs";
3412
- import { join as join5 } from "node:path";
4140
+ import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync, writeFileSync as writeFileSync4 } from "node:fs";
4141
+ import { join as join6 } from "node:path";
3413
4142
  import { pathToFileURL as pathToFileURL2 } from "node:url";
3414
4143
 
3415
4144
  // packages/core/src/sdk-resolver.ts
3416
- import { existsSync as existsSync3 } from "node:fs";
4145
+ import { existsSync as existsSync4 } from "node:fs";
3417
4146
  import module from "node:module";
3418
- import { join as join4 } from "node:path";
4147
+ import { join as join5 } from "node:path";
3419
4148
  import { pathToFileURL } from "node:url";
3420
4149
  var SHARED = ["@kiosko/sdk", "@loksly/lcd-canvas-kit", "@loksly/weather-astro", "@napi-rs/canvas"];
3421
4150
  var BUNDLED = { "@kiosko/sdk": "sdk.js", "@loksly/lcd-canvas-kit": "kit.js", "@loksly/weather-astro": "weather-astro.js" };
@@ -3425,8 +4154,8 @@ function installSdkResolver() {
3425
4154
  installed = true;
3426
4155
  const urls = /* @__PURE__ */ new Map();
3427
4156
  for (const name of SHARED) {
3428
- const local = BUNDLED[name] ? join4(import.meta.dirname, BUNDLED[name]) : null;
3429
- if (local && existsSync3(local)) {
4157
+ const local = BUNDLED[name] ? join5(import.meta.dirname, BUNDLED[name]) : null;
4158
+ if (local && existsSync4(local)) {
3430
4159
  urls.set(name, pathToFileURL(local).href);
3431
4160
  continue;
3432
4161
  }
@@ -3493,10 +4222,10 @@ var Registry = class {
3493
4222
  * installed there with npm (`node_modules/kiosko-plugin-*`).
3494
4223
  */
3495
4224
  async loadDir(dir) {
3496
- if (!existsSync4(dir)) return;
4225
+ if (!existsSync5(dir)) return;
3497
4226
  installSdkResolver();
3498
- const marker = join5(dir, "package.json");
3499
- if (!existsSync4(marker)) {
4227
+ const marker = join6(dir, "package.json");
4228
+ if (!existsSync5(marker)) {
3500
4229
  try {
3501
4230
  writeFileSync4(marker, `${JSON.stringify({ name: "kiosko-user-plugins", private: true, type: "module" }, null, 2)}
3502
4231
  `);
@@ -3506,14 +4235,14 @@ var Registry = class {
3506
4235
  const candidates = [];
3507
4236
  for (const name of readdirSync2(dir)) {
3508
4237
  if (name === "node_modules" || name.startsWith(".")) continue;
3509
- candidates.push(join5(dir, name));
4238
+ candidates.push(join6(dir, name));
3510
4239
  }
3511
- const nm = join5(dir, "node_modules");
3512
- if (existsSync4(nm)) {
4240
+ const nm = join6(dir, "node_modules");
4241
+ if (existsSync5(nm)) {
3513
4242
  for (const name of readdirSync2(nm)) {
3514
4243
  if (name.startsWith("@")) {
3515
- for (const sub of readdirSync2(join5(nm, name))) if (sub.startsWith("kiosko-plugin-")) candidates.push(join5(nm, name, sub));
3516
- } else if (name.startsWith("kiosko-plugin-")) candidates.push(join5(nm, name));
4244
+ for (const sub of readdirSync2(join6(nm, name))) if (sub.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name, sub));
4245
+ } else if (name.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name));
3517
4246
  }
3518
4247
  }
3519
4248
  for (const folder of candidates) await this.loadFolder(folder);
@@ -3524,14 +4253,14 @@ var Registry = class {
3524
4253
  if (/\.m?js$/.test(folder)) await this.loadEntry(folder, folder);
3525
4254
  return;
3526
4255
  }
3527
- const pkgPath = join5(folder, "package.json");
3528
- let entry = ["index.mjs", "index.js"].map((f) => join5(folder, f)).find(existsSync4);
3529
- if (existsSync4(pkgPath)) {
4256
+ const pkgPath = join6(folder, "package.json");
4257
+ let entry = ["index.mjs", "index.js"].map((f) => join6(folder, f)).find(existsSync5);
4258
+ if (existsSync5(pkgPath)) {
3530
4259
  const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
3531
4260
  const rel = pkg.kiosko?.plugin ?? pkg.main;
3532
- if (rel) entry = join5(folder, rel);
4261
+ if (rel) entry = join6(folder, rel);
3533
4262
  }
3534
- if (!entry || !existsSync4(entry)) {
4263
+ if (!entry || !existsSync5(entry)) {
3535
4264
  this.problems.push({ origin: folder, message: 'no entry point (package.json "kiosko.plugin", "main" or index.js)' });
3536
4265
  return;
3537
4266
  }
@@ -3590,8 +4319,7 @@ var Registry = class {
3590
4319
 
3591
4320
  // plugins/core/src/index.ts
3592
4321
  import { readdir, readFile, stat } from "node:fs/promises";
3593
- import { homedir as homedir2 } from "node:os";
3594
- import { join as join6 } from "node:path";
4322
+ import { join as join7 } from "node:path";
3595
4323
  function fit(g, text2, family, w, h, max = 400) {
3596
4324
  let size = Math.min(max, h);
3597
4325
  g.font = `${size}px "${family}"`;
@@ -3717,8 +4445,7 @@ var date = defineWidget({
3717
4445
  }
3718
4446
  });
3719
4447
  function expandHome(path) {
3720
- const p = path.trim();
3721
- return p === "~" ? homedir2() : p.startsWith("~/") ? join6(homedir2(), p.slice(2)) : p;
4448
+ return expandPath(path.trim());
3722
4449
  }
3723
4450
  var MAX_FILE_CHARS = 2e4;
3724
4451
  var text = defineWidget({
@@ -3841,7 +4568,7 @@ async function nextInFolder(dir) {
3841
4568
  if (!files.length) return null;
3842
4569
  const i = ((turns.get(dir) ?? -1) + 1) % files.length;
3843
4570
  turns.set(dir, i);
3844
- return join6(dir, files[i]);
4571
+ return join7(dir, files[i]);
3845
4572
  }
3846
4573
  function imageUrl(src, now, addTimestamp = false) {
3847
4574
  const filled = src.replace(/\{now\}/g, String(now)).replace(/\{unix\}/g, String(Math.floor(now / 1e3)));
@@ -3927,7 +4654,7 @@ var image = defineWidget({
3927
4654
  var src_default = definePlugin({
3928
4655
  id: "core",
3929
4656
  name: { en: "Essentials", es: "B\xE1sicos" },
3930
- version: "0.1.0",
4657
+ version: "0.2.1",
3931
4658
  description: { en: "Clock, date, notes, lists and pictures.", es: "Reloj, fecha, notas, listas e im\xE1genes." },
3932
4659
  author: "Kiosko",
3933
4660
  license: "MIT",
@@ -3936,16 +4663,15 @@ var src_default = definePlugin({
3936
4663
  });
3937
4664
 
3938
4665
  // plugins/legacy/src/index.ts
3939
- import { existsSync as existsSync5, statSync as statSync2 } from "node:fs";
3940
- import { homedir as homedir3 } from "node:os";
3941
- import { isAbsolute, join as join7 } from "node:path";
4666
+ import { existsSync as existsSync6, statSync as statSync2 } from "node:fs";
4667
+ import { isAbsolute, join as join8 } from "node:path";
3942
4668
  import { pathToFileURL as pathToFileURL3 } from "node:url";
3943
4669
  var loaded = /* @__PURE__ */ new Map();
3944
4670
  function resolveModule(name, dir) {
3945
- const expanded = name.startsWith("~/") ? join7(homedir3(), name.slice(2)) : name;
3946
- const base3 = isAbsolute(expanded) ? expanded : join7(dir.startsWith("~/") ? join7(homedir3(), dir.slice(2)) : dir, expanded);
3947
- for (const p of [base3, `${base3}.mjs`, `${base3}.js`, join7(base3, "index.mjs"), join7(base3, "index.js")]) {
3948
- if (existsSync5(p) && statSync2(p).isFile()) return p;
4671
+ const expanded = expandPath(name);
4672
+ const base3 = isAbsolute(expanded) ? expanded : join8(expandPath(dir), expanded);
4673
+ for (const p of [base3, `${base3}.mjs`, `${base3}.js`, join8(base3, "index.mjs"), join8(base3, "index.js")]) {
4674
+ if (existsSync6(p) && statSync2(p).isFile()) return p;
3949
4675
  }
3950
4676
  return null;
3951
4677
  }
@@ -4020,7 +4746,7 @@ var module2 = defineWidget({
4020
4746
  var src_default2 = definePlugin({
4021
4747
  id: "legacy",
4022
4748
  name: { en: "aimonitor compatibility", es: "Compatibilidad aimonitor" },
4023
- version: "0.1.0",
4749
+ version: "0.2.1",
4024
4750
  description: { en: "Run your aimonitor custom modules as widgets.", es: "Tus m\xF3dulos propios de aimonitor, como widgets." },
4025
4751
  author: "Kiosko",
4026
4752
  license: "MIT",
@@ -4033,16 +4759,16 @@ var BUILTIN_PLUGINS = [src_default, src_default2];
4033
4759
  var OFFICIAL_PLUGINS = ["agents", "cats", "system", "vitals", "usage", "weather", "calendar", "news", "mirror", "gitlab", "github", "calls", "timesheet", "llm", "gpu"].map((id) => ({ id, npm: `kiosko-plugin-${id}` }));
4034
4760
 
4035
4761
  // packages/server/src/config-cli.ts
4036
- import { chmodSync as chmodSync2, copyFileSync as copyFileSync2, existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync6 } from "node:fs";
4762
+ import { copyFileSync as copyFileSync2, existsSync as existsSync8, mkdirSync as mkdirSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync6 } from "node:fs";
4037
4763
  import { tmpdir } from "node:os";
4038
- import { dirname as dirname4, isAbsolute as isAbsolute2, join as join9, relative, resolve as resolve2 } from "node:path";
4764
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join10, relative, resolve as resolve2 } from "node:path";
4039
4765
 
4040
4766
  // packages/server/src/preview.ts
4041
- import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "node:fs";
4042
- import { dirname as dirname3, join as join8 } from "node:path";
4767
+ import { existsSync as existsSync7, mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "node:fs";
4768
+ import { dirname as dirname3, join as join9 } from "node:path";
4043
4769
  function writePreview(rt, screen, page, out, o = {}) {
4044
4770
  const r = rt.preview(screen, page, { demo: o.demo ?? true });
4045
- mkdirSync4(dirname3(out), { recursive: true });
4771
+ if (!existsSync7(dirname3(out))) mkdirSync4(dirname3(out), { recursive: true });
4046
4772
  writeFileSync5(out, r.canvas.toBuffer("image/png"));
4047
4773
  return r.tiles.filter((t2) => t2.error).map((t2) => `tile ${t2.id}: ${t2.error}`);
4048
4774
  }
@@ -4057,7 +4783,7 @@ function renderPreviews(registry2, cfg, dir) {
4057
4783
  try {
4058
4784
  safe2.screens.forEach(
4059
4785
  (s, si) => s.pages.forEach((p, pi) => {
4060
- const file = join8(dir, `${si + 1}-${slug(s.name || s.id)}--${pi + 1}-${slug(p.name || p.id)}.png`);
4786
+ const file = join9(dir, `${si + 1}-${slug(s.name || s.id)}--${pi + 1}-${slug(p.name || p.id)}.png`);
4061
4787
  const problems = writePreview(rt, s, p, file);
4062
4788
  out.push({ screen: s.name || s.id, page: p.name || p.id, file, size: `${s.width}\xD7${s.height}`, problems });
4063
4789
  })
@@ -4114,7 +4840,7 @@ function readConfigText(text2) {
4114
4840
  }
4115
4841
  function readInput(file) {
4116
4842
  const name = file === "-" ? "(stdin)" : file;
4117
- if (file !== "-" && !existsSync6(file)) return { error: `not found: ${file}`, notes: [], name };
4843
+ if (file !== "-" && !existsSync8(file)) return { error: `not found: ${file}`, notes: [], name };
4118
4844
  return { ...readConfigText(readFileSync4(file === "-" ? 0 : file, "utf8")), name };
4119
4845
  }
4120
4846
  var pluginDefs = (r) => r.list().map((p) => p.def);
@@ -4272,7 +4998,7 @@ ${bold("Changes")}: ${summarizeDiff(plan.diff)}`);
4272
4998
  }
4273
4999
  if (plan.carried.length) console.log(dim(` kept from your current config (the file leaves them out): ${plan.carried.join(", ")}`));
4274
5000
  if (!flags.has("--no-preview")) {
4275
- const dir = opts.get("--preview") || join9(tmpdir(), `kiosko-import-${stamp()}`);
5001
+ const dir = opts.get("--preview") || join10(tmpdir(), `kiosko-import-${stamp()}`);
4276
5002
  try {
4277
5003
  const files = renderPreviews(reg, c, dir);
4278
5004
  console.log(`
@@ -4292,14 +5018,11 @@ ${dim("Dry run: nothing was written.")} Run again with --apply to back up the cu
4292
5018
  return 0;
4293
5019
  }
4294
5020
  const backup = `${path}.bak-${stamp()}`;
4295
- if (existsSync6(path)) {
5021
+ if (existsSync8(path)) {
4296
5022
  copyFileSync2(path, backup);
4297
- try {
4298
- chmodSync2(backup, 384);
4299
- } catch {
4300
- }
5023
+ restrictToOwner(backup);
4301
5024
  }
4302
- const saved = existsSync6(backup) ? `; the previous one is in ${backup}` : "";
5025
+ const saved = existsSync8(backup) ? `; the previous one is in ${backup}` : "";
4303
5026
  if (running?.same) {
4304
5027
  const r = await fetch(`${running.base}/api/config`, {
4305
5028
  method: "PUT",
@@ -4344,20 +5067,20 @@ async function configCommand(argv2, ctx) {
4344
5067
  }
4345
5068
 
4346
5069
  // packages/server/src/plugins-cli.ts
4347
- import { execFileSync } from "node:child_process";
4348
- import { existsSync as existsSync7, lstatSync, mkdirSync as mkdirSync6, readFileSync as readFileSync5, rmSync, symlinkSync, writeFileSync as writeFileSync7 } from "node:fs";
4349
- import { basename, join as join10, resolve as resolve3 } from "node:path";
5070
+ import { execFileSync as execFileSync2 } from "node:child_process";
5071
+ import { existsSync as existsSync9, lstatSync, mkdirSync as mkdirSync6, readFileSync as readFileSync5, rmSync, symlinkSync, writeFileSync as writeFileSync7 } from "node:fs";
5072
+ import { basename, join as join11, resolve as resolve3 } from "node:path";
4350
5073
  var npmName = (s) => /^[a-z0-9][\w.-]*$/.test(s) && !s.startsWith("kiosko-plugin-") && !s.includes("/") ? `kiosko-plugin-${s}` : s;
4351
5074
  function ensureFolder() {
4352
5075
  const dir = paths.plugins;
4353
5076
  mkdirSync6(dir, { recursive: true });
4354
- const pkg = join10(dir, "package.json");
4355
- if (!existsSync7(pkg)) writeFileSync7(pkg, `${JSON.stringify({ name: "kiosko-user-plugins", private: true, type: "module" }, null, 2)}
5077
+ const pkg = join11(dir, "package.json");
5078
+ if (!existsSync9(pkg)) writeFileSync7(pkg, `${JSON.stringify({ name: "kiosko-user-plugins", private: true, type: "module" }, null, 2)}
4356
5079
  `);
4357
5080
  return dir;
4358
5081
  }
4359
5082
  function npm(args, cwd) {
4360
- execFileSync(process.platform === "win32" ? "npm.cmd" : "npm", args, { cwd, stdio: "inherit", shell: process.platform === "win32" });
5083
+ execFileSync2(process.platform === "win32" ? "npm.cmd" : "npm", args, { cwd, stdio: "inherit", shell: process.platform === "win32" });
4361
5084
  }
4362
5085
  async function pluginsCommand(argv2, registry2) {
4363
5086
  const [sub = "list", ...names] = argv2;
@@ -4386,12 +5109,12 @@ plugins folder: ${paths.plugins}`);
4386
5109
  const dir = ensureFolder();
4387
5110
  for (const n of names) {
4388
5111
  const src = resolve3(n);
4389
- const pkgPath = join10(src, "package.json");
4390
- if (!existsSync7(pkgPath)) throw new Error(`${src} has no package.json`);
5112
+ const pkgPath = join11(src, "package.json");
5113
+ if (!existsSync9(pkgPath)) throw new Error(`${src} has no package.json`);
4391
5114
  const pkg = JSON.parse(readFileSync5(pkgPath, "utf8"));
4392
5115
  const entry = pkg.kiosko?.plugin;
4393
- if (entry && !existsSync7(join10(src, entry))) console.warn(`warning: ${entry} doesn't exist yet in ${src} (run its build)`);
4394
- const target = join10(dir, pkg.kiosko?.id ?? basename(src).replace(/^kiosko-plugin-/, ""));
5116
+ if (entry && !existsSync9(join11(src, entry))) console.warn(`warning: ${entry} doesn't exist yet in ${src} (run its build)`);
5117
+ const target = join11(dir, pkg.kiosko?.id ?? basename(src).replace(/^kiosko-plugin-/, ""));
4395
5118
  const existing = (() => {
4396
5119
  try {
4397
5120
  return lstatSync(target);
@@ -4412,7 +5135,7 @@ plugins folder: ${paths.plugins}`);
4412
5135
  const dir = ensureFolder();
4413
5136
  for (const n of names) {
4414
5137
  const id = n.replace(/^kiosko-plugin-/, "");
4415
- const link = join10(dir, id);
5138
+ const link = join11(dir, id);
4416
5139
  const st = (() => {
4417
5140
  try {
4418
5141
  return lstatSync(link);
@@ -4436,15 +5159,17 @@ plugins folder: ${paths.plugins}`);
4436
5159
 
4437
5160
  // packages/server/src/gallery.ts
4438
5161
  import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync8 } from "node:fs";
4439
- import { join as join11 } from "node:path";
5162
+ import { join as join12 } from "node:path";
4440
5163
  var DEMO_URL = "https://kioskolcd.dev/demo/";
5164
+ var RELEASES_URL = "https://github.com/kiosko-lcd/kiosko/releases/latest";
5165
+ var USB_URL = "https://github.com/kiosko-lcd/kiosko/blob/main/docs/usb.md";
4441
5166
  var esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
4442
5167
  function buildGallery(registry2, o) {
4443
5168
  const locale = o.locale ?? "en";
4444
5169
  const theme = themeById(o.theme);
4445
5170
  const now = o.now ?? Date.now();
4446
5171
  const cfg = normalize({ locale, theme: theme.id, location: { latitude: 40.4168, longitude: -3.7038, name: "Madrid" } });
4447
- mkdirSync7(join11(o.out, "img"), { recursive: true });
5172
+ mkdirSync7(join12(o.out, "img"), { recursive: true });
4448
5173
  const L = (x) => localize(x, locale);
4449
5174
  const sections = [];
4450
5175
  let count = 0;
@@ -4456,7 +5181,7 @@ function buildGallery(registry2, o) {
4456
5181
  const height = Math.min(720, pref.h);
4457
5182
  const file = `img/${def.id}-${w.id}.png`;
4458
5183
  const r = composeWidget({ cfg, registry: registry2, theme, type: `${def.id}/${w.id}`, width, height, now, ...w.chrome === "bare" ? {} : { title: L(w.name) } });
4459
- writeFileSync8(join11(o.out, file), r.canvas.toBuffer("image/png"));
5184
+ writeFileSync8(join12(o.out, file), r.canvas.toBuffer("image/png"));
4460
5185
  count++;
4461
5186
  const wide = width >= 900;
4462
5187
  return `<figure class="${wide ? "wide" : ""}"><div class="shot"><img src="${file}" width="${width}" height="${height}" loading="lazy" alt="${esc(L(w.name))}"></div><figcaption><b>${esc(L(w.name))}</b> <code>${def.id}/${w.id}</code><span>${esc(L(w.description))}</span></figcaption></figure>`;
@@ -4464,7 +5189,7 @@ function buildGallery(registry2, o) {
4464
5189
  sections.push(`<section><h2>${esc(L(def.name))} <small>${esc(def.id)} \xB7 v${esc(def.version)}</small></h2><p>${esc(L(def.description))}</p><div class="grid">${cards.join("")}</div></section>`);
4465
5190
  }
4466
5191
  writeFileSync8(
4467
- join11(o.out, "index.html"),
5192
+ join12(o.out, "index.html"),
4468
5193
  `<!doctype html><html lang="${locale}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kiosko widget gallery</title>
4469
5194
  <style>
4470
5195
  :root{color-scheme:dark;--bg:#0a0d13;--panel:#121722;--line:rgba(255,255,255,.08);--text:#e7ecf4;--dim:#a3adbf}
@@ -4477,8 +5202,9 @@ figure{margin:0;background:var(--panel);border:1px solid var(--line);border-radi
4477
5202
  figure .shot{background:#000;display:grid;place-items:center;padding:8px}figure img{display:block;max-width:100%;height:auto}figcaption{padding:10px 12px;display:flex;flex-wrap:wrap;gap:4px 8px;align-items:baseline}
4478
5203
  figcaption code{color:#22d3ee;font-size:12px}figcaption span{flex-basis:100%;color:var(--dim);font-size:13px}
4479
5204
  a{color:#22d3ee}
5205
+ p.os{margin-top:14px}p.os b{color:var(--text)}
4480
5206
  a.try{display:inline-block;margin-top:10px;padding:8px 14px;border-radius:10px;background:linear-gradient(135deg,#8b5cf6,#22d3ee);color:#fff;font-weight:600;text-decoration:none}
4481
- </style></head><body><header><h1>Kiosko widget gallery</h1><p>${count} widgets, painted with their demo data by the same code that drives the panels. <a href="https://github.com/kiosko-lcd/kiosko">Kiosko on GitHub</a></p><p><a class="try" href="${DEMO_URL}">Try the editor in your browser \u2192</a></p></header><main>${sections.join("")}</main></body></html>`
5207
+ </style></head><body><header><h1>Kiosko widget gallery</h1><p>${count} widgets, painted with their demo data by the same code that drives the panels. <a href="https://github.com/kiosko-lcd/kiosko">Kiosko on GitHub</a></p><p><a class="try" href="${DEMO_URL}">Try the editor in your browser \u2192</a></p><p class="os"><b>Now on Linux, macOS and Windows.</b> Windows has an installer, no Node.js needed: <a href="${RELEASES_URL}">download Kiosko for Windows</a>. USB panels talk to Kiosko directly, with no Python: <a href="${USB_URL}">how to connect one</a>.</p></header><main>${sections.join("")}</main></body></html>`
4482
5208
  );
4483
5209
  return count;
4484
5210
  }
@@ -4594,6 +5320,7 @@ function importAimonitor(old, reg, modeOverride, o = {}) {
4594
5320
  pixelShift: { enabled: old.pixelShift?.enabled ?? true, amplitude: old.pixelShift?.amplitude ?? 2, periodMs: old.pixelShift?.periodMs ?? 8 * 6e4 },
4595
5321
  sleepWhenIdle: old.blankWhenIdle ?? true,
4596
5322
  jpegQuality: old.scene?.jpegQuality ?? 90,
5323
+ maxBytes: DEFAULT_MAX_BYTES,
4597
5324
  maxFps: old.easterEgg?.fps ?? 12
4598
5325
  };
4599
5326
  if (old.easterEgg?.enabled !== false) {
@@ -4643,10 +5370,10 @@ function importAimonitor(old, reg, modeOverride, o = {}) {
4643
5370
  }
4644
5371
 
4645
5372
  // packages/server/src/service.ts
4646
- import { execFileSync as execFileSync2 } from "node:child_process";
4647
- import { existsSync as existsSync8, mkdirSync as mkdirSync8, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "node:fs";
4648
- import { homedir as homedir4, platform as platform2 } from "node:os";
4649
- import { dirname as dirname5, join as join12, resolve as resolve4 } from "node:path";
5373
+ import { execFileSync as execFileSync3 } from "node:child_process";
5374
+ import { existsSync as existsSync10, mkdirSync as mkdirSync8, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "node:fs";
5375
+ import { homedir as homedir3, platform as platform2 } from "node:os";
5376
+ import { dirname as dirname5, join as join13, resolve as resolve4, win32 as win322 } from "node:path";
4650
5377
  import { fileURLToPath } from "node:url";
4651
5378
  var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
4652
5379
  function servicePlan(o = {}) {
@@ -4656,10 +5383,10 @@ function servicePlan(o = {}) {
4656
5383
  const args = [...nodeArgs, cli, "start", ...o.args ?? []];
4657
5384
  const os = o.os ?? platform2();
4658
5385
  const sep = os === "win32" ? ";" : ":";
4659
- const path = [dirname5(node), join12(homedir4(), ".local", "bin"), ...os === "darwin" ? ["/opt/homebrew/bin"] : [], "/usr/local/bin", "/usr/bin", "/bin"].join(sep);
5386
+ const path = [dirname5(node), join13(homedir3(), ".local", "bin"), ...os === "darwin" ? ["/opt/homebrew/bin"] : [], "/usr/local/bin", "/usr/bin", "/bin"].join(sep);
4660
5387
  const env = { ...os === "win32" ? {} : { PATH: path }, ...o.env ?? {} };
4661
5388
  if (os === "darwin") {
4662
- const file2 = join12(homedir4(), "Library", "LaunchAgents", "dev.kiosko.plist");
5389
+ const file2 = join13(homedir3(), "Library", "LaunchAgents", "dev.kiosko.plist");
4663
5390
  const content2 = `<?xml version="1.0" encoding="UTF-8"?>
4664
5391
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4665
5392
  <plist version="1.0">
@@ -4676,23 +5403,36 @@ ${Object.entries(env).map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}
4676
5403
  <key>RunAtLoad</key><true/>
4677
5404
  <key>KeepAlive</key><true/>
4678
5405
  <key>ProcessType</key><string>Background</string>
4679
- <key>StandardOutPath</key><string>${xml(join12(homedir4(), "Library", "Logs", "kiosko.log"))}</string>
4680
- <key>StandardErrorPath</key><string>${xml(join12(homedir4(), "Library", "Logs", "kiosko.log"))}</string>
5406
+ <key>StandardOutPath</key><string>${xml(join13(homedir3(), "Library", "Logs", "kiosko.log"))}</string>
5407
+ <key>StandardErrorPath</key><string>${xml(join13(homedir3(), "Library", "Logs", "kiosko.log"))}</string>
4681
5408
  </dict>
4682
5409
  </plist>
4683
5410
  `;
4684
5411
  return { kind: "launchd", file: file2, content: content2, enable: [["launchctl", "load", "-w", file2]], disable: [["launchctl", "unload", "-w", file2]] };
4685
5412
  }
4686
5413
  if (os === "win32") {
4687
- const cmd2 = [node, ...args].map((a) => /\s/.test(a) ? `"${a}"` : a).join(" ");
5414
+ const home = o.home ?? kioskoHome();
5415
+ const file2 = win322.join(home, "kiosko-start.vbs");
5416
+ const log = win322.join(home, "kiosko.log");
5417
+ const q4 = (a) => `"${a}"`;
5418
+ const inner = `${[node, ...args].map(q4).join(" ")} >> ${q4(log)} 2>&1`;
5419
+ const vbs = (s) => `"${s.replace(/"/g, '""')}"`;
5420
+ const content2 = `' Starts Kiosko without a console window. Written by \`kiosko service install\`.\r
5421
+ CreateObject("WScript.Shell").Run ${vbs(`cmd.exe /d /s /c "${inner}"`)}, 0, False\r
5422
+ `;
5423
+ const tr = `wscript.exe //B //Nologo "${file2}"`;
4688
5424
  return {
4689
5425
  kind: "schtasks",
4690
- content: cmd2,
4691
- enable: [["schtasks", "/Create", "/F", "/SC", "ONLOGON", "/RL", "LIMITED", "/TN", "Kiosko", "/TR", cmd2], ["schtasks", "/Run", "/TN", "Kiosko"]],
4692
- disable: [["schtasks", "/End", "/TN", "Kiosko"], ["schtasks", "/Delete", "/F", "/TN", "Kiosko"]]
5426
+ file: file2,
5427
+ content: content2,
5428
+ utf16: true,
5429
+ enable: [["schtasks", "/Create", "/F", "/SC", "ONLOGON", "/RL", "LIMITED", "/TN", "Kiosko", "/TR", tr], ["schtasks", "/Run", "/TN", "Kiosko"]],
5430
+ // `schtasks /End` stops the launcher but leaves node.exe (and the cmd.exe
5431
+ // that holds the log open) running: end them by their command line.
5432
+ disable: [["schtasks", "/End", "/TN", "Kiosko"], stopProcesses(cli), ["schtasks", "/Delete", "/F", "/TN", "Kiosko"]]
4693
5433
  };
4694
5434
  }
4695
- const file = join12(process.env.XDG_CONFIG_HOME ?? join12(homedir4(), ".config"), "systemd", "user", "kiosko.service");
5435
+ const file = join13(process.env.XDG_CONFIG_HOME ?? join13(homedir3(), ".config"), "systemd", "user", "kiosko.service");
4696
5436
  const q3 = (a) => /[\s"\\]/.test(a) ? `"${a.replace(/(["\\])/g, "\\$1")}"` : a;
4697
5437
  const content = `[Unit]
4698
5438
  Description=Kiosko: widgets for USB LCD panels
@@ -4713,6 +5453,11 @@ WantedBy=default.target
4713
5453
  `;
4714
5454
  return { kind: "systemd", file, content, enable: [["systemctl", "--user", "daemon-reload"], ["systemctl", "--user", "enable", "--now", "kiosko.service"]], disable: [["systemctl", "--user", "disable", "--now", "kiosko.service"]] };
4715
5455
  }
5456
+ function stopProcesses(cli) {
5457
+ const like = cli.replace(/'/g, "''").replace(/[[\]`*?]/g, "`$&");
5458
+ const script = `Get-CimInstance Win32_Process | Where-Object { ($_.Name -eq 'node.exe' -or $_.Name -eq 'cmd.exe') -and $_.CommandLine -like '*${like}*' -and $_.ProcessId -ne $PID -and $_.ProcessId -ne ${process.pid} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;
5459
+ return ["powershell", "-NoProfile", "-NonInteractive", "-Command", script];
5460
+ }
4716
5461
  function runService(action, plan) {
4717
5462
  if (action === "print") {
4718
5463
  if (plan.file) console.log(`# ${plan.file}`);
@@ -4723,21 +5468,21 @@ function runService(action, plan) {
4723
5468
  if (action === "install") {
4724
5469
  if (plan.file) {
4725
5470
  mkdirSync8(dirname5(plan.file), { recursive: true });
4726
- writeFileSync9(plan.file, plan.content);
5471
+ writeFileSync9(plan.file, plan.utf16 ? Buffer.concat([Buffer.from([255, 254]), Buffer.from(plan.content, "utf16le")]) : plan.content);
4727
5472
  console.log(`written ${plan.file}`);
4728
5473
  }
4729
- for (const c of plan.enable) execFileSync2(c[0], c.slice(1), { stdio: "inherit" });
5474
+ for (const c of plan.enable) execFileSync3(c[0], c.slice(1), { stdio: "inherit" });
4730
5475
  console.log("Kiosko will start with your session. Editor: http://127.0.0.1:7420/");
4731
5476
  return;
4732
5477
  }
4733
5478
  if (action === "uninstall") {
4734
5479
  for (const c of plan.disable) {
4735
5480
  try {
4736
- execFileSync2(c[0], c.slice(1), { stdio: "inherit" });
5481
+ execFileSync3(c[0], c.slice(1), { stdio: "inherit" });
4737
5482
  } catch {
4738
5483
  }
4739
5484
  }
4740
- if (plan.file && existsSync8(plan.file)) rmSync2(plan.file);
5485
+ if (plan.file && existsSync10(plan.file)) rmSync2(plan.file);
4741
5486
  console.log("removed");
4742
5487
  return;
4743
5488
  }
@@ -4746,10 +5491,10 @@ function runService(action, plan) {
4746
5491
 
4747
5492
  // packages/server/src/server.ts
4748
5493
  import { execFile } from "node:child_process";
4749
- import { existsSync as existsSync9, mkdirSync as mkdirSync9, readFileSync as readFileSync6, statSync as statSync3, writeFileSync as writeFileSync10 } from "node:fs";
5494
+ import { existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync6, statSync as statSync3, writeFileSync as writeFileSync10 } from "node:fs";
4750
5495
  import { createServer } from "node:http";
4751
5496
  import { createRequire as createRequire2 } from "node:module";
4752
- import { dirname as dirname6, extname, join as join13, normalize as normPath, resolve as resolve5 } from "node:path";
5497
+ import { dirname as dirname6, extname, join as join14, normalize as normPath, resolve as resolve5 } from "node:path";
4753
5498
  var require3 = createRequire2(import.meta.url);
4754
5499
  var MIME = {
4755
5500
  ".html": "text/html; charset=utf-8",
@@ -4763,10 +5508,10 @@ var MIME = {
4763
5508
  ".ico": "image/x-icon"
4764
5509
  };
4765
5510
  function webRoot() {
4766
- const bundled = join13(import.meta.dirname, "web");
4767
- if (existsSync9(join13(bundled, "index.html"))) return bundled;
5511
+ const bundled = join14(import.meta.dirname, "web");
5512
+ if (existsSync11(join14(bundled, "index.html"))) return bundled;
4768
5513
  try {
4769
- return join13(dirname6(require3.resolve("@kiosko/web/package.json")), "dist");
5514
+ return join14(dirname6(require3.resolve("@kiosko/web/package.json")), "dist");
4770
5515
  } catch {
4771
5516
  return resolve5(import.meta.dirname, "../../web/dist");
4772
5517
  }
@@ -4915,7 +5660,7 @@ data: ${JSON.stringify({ version: o.version })}
4915
5660
  }
4916
5661
  if (p === "/api/devices/discover" && m === "GET") {
4917
5662
  const url0 = url2.searchParams.get("url") ?? "http://127.0.0.1:8099";
4918
- return json(res, 200, { trcc: await discoverTrcc(url0, url2.searchParams.get("tokenFile") ?? void 0) });
5663
+ return json(res, 200, { trcc: await discoverTrcc(url0, url2.searchParams.get("tokenFile") ?? void 0), usb: await discoverUsb() });
4919
5664
  }
4920
5665
  if (p === "/api/logs" && m === "GET") return json(res, 200, runtime.logs.slice(-200));
4921
5666
  if (p === "/api/plugins/install" && m === "POST") {
@@ -4923,8 +5668,8 @@ data: ${JSON.stringify({ version: o.version })}
4923
5668
  const name = String(b.name ?? "").trim();
4924
5669
  if (!/^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(@[\w.^~<>=-]+)?$/i.test(name)) return json(res, 400, { error: "not a valid npm package name" });
4925
5670
  mkdirSync9(paths.plugins, { recursive: true });
4926
- const pkg = join13(paths.plugins, "package.json");
4927
- if (!existsSync9(pkg)) writeFileSync10(pkg, JSON.stringify({ name: "kiosko-user-plugins", private: true, type: "module" }, null, 2));
5671
+ const pkg = join14(paths.plugins, "package.json");
5672
+ if (!existsSync11(pkg)) writeFileSync10(pkg, JSON.stringify({ name: "kiosko-user-plugins", private: true, type: "module" }, null, 2));
4928
5673
  const npm2 = process.platform === "win32" ? "npm.cmd" : "npm";
4929
5674
  execFile(npm2, ["install", "--no-audit", "--no-fund", "--ignore-scripts", name], { cwd: paths.plugins, timeout: 18e4, shell: process.platform === "win32" }, (err, stdout, stderr) => {
4930
5675
  if (err) return json(res, 500, { error: (stderr || err.message).slice(-2e3) });
@@ -4958,10 +5703,10 @@ data: ${JSON.stringify({ version: o.version })}
4958
5703
  }
4959
5704
  function serveStatic(res, pathname) {
4960
5705
  const rel = normPath(decodeURIComponent(pathname)).replace(/^([/\\])+/, "");
4961
- let file = join13(root, rel || "index.html");
5706
+ let file = join14(root, rel || "index.html");
4962
5707
  if (!file.startsWith(root)) return void json(res, 400, { error: "bad path" });
4963
- if (!existsSync9(file) || statSync3(file).isDirectory()) file = join13(root, "index.html");
4964
- if (!existsSync9(file)) {
5708
+ if (!existsSync11(file) || statSync3(file).isDirectory()) file = join14(root, "index.html");
5709
+ if (!existsSync11(file)) {
4965
5710
  res.writeHead(500, { "content-type": "text/plain" });
4966
5711
  return void res.end("The editor is not built. Run `npm run web:build`.");
4967
5712
  }
@@ -5030,7 +5775,7 @@ function starterConfig(registry2, o = {}) {
5030
5775
  }
5031
5776
 
5032
5777
  // packages/server/src/cli.ts
5033
- var VERSION = "0.1.0";
5778
+ var VERSION = "0.2.1";
5034
5779
  var USAGE2 = `Kiosko ${VERSION}: a widget mosaic for USB LCD panels
5035
5780
 
5036
5781
  kiosko start [--port 7420] [--host 127.0.0.1] [--config file] [--open] [--demo]
@@ -5040,18 +5785,23 @@ var USAGE2 = `Kiosko ${VERSION}: a widget mosaic for USB LCD panels
5040
5785
  kiosko config validate <file> [--json] check a config (e.g. one an AI wrote)
5041
5786
  kiosko config import <file> [--apply] review it (changes, preview, risky values) and use it
5042
5787
  kiosko doctor
5788
+ kiosko usb [list] the LY panels libusb sees, with their serial numbers
5789
+ kiosko usb test [--serial S] [--seconds 10] [--size 1920x462] [--rotate 180]
5790
+ drive a panel with the sample screen (experimental)
5043
5791
  kiosko gallery [--out gallery] [--locale en] [--theme midnight]
5044
5792
  kiosko plugins [list|add <id>\u2026|link <folder>\u2026|remove <id>\u2026]
5045
5793
  kiosko service install|uninstall|print (start with your session)
5046
5794
  kiosko version`;
5047
5795
  var argv = process.argv.slice(2);
5048
- var cmd = argv[0] && !argv[0].startsWith("-") ? argv[0] : "start";
5796
+ var FLAG_COMMANDS = /* @__PURE__ */ new Set(["--help", "-h", "--version", "-v"]);
5797
+ var cmd = argv[0] && (!argv[0].startsWith("-") || FLAG_COMMANDS.has(argv[0])) ? argv[0] : "start";
5049
5798
  var flag = (name) => argv.includes(name);
5050
5799
  var opt = (name) => {
5051
5800
  const i = argv.indexOf(name);
5052
5801
  return i >= 0 ? argv[i + 1] : void 0;
5053
5802
  };
5054
5803
  async function registry() {
5804
+ installSdkResolver();
5055
5805
  const r = new Registry();
5056
5806
  for (const p of BUILTIN_PLUGINS) r.add(p);
5057
5807
  await r.loadDir(paths.plugins);
@@ -5137,26 +5887,55 @@ async function main() {
5137
5887
  }
5138
5888
  case "import-aimonitor": {
5139
5889
  const from = opt("--from") ?? `${process.env.HOME ?? ""}/.aimonitor/config.json`;
5140
- if (!existsSync10(from)) {
5890
+ if (!existsSync12(from)) {
5141
5891
  console.error(`not found: ${from}`);
5142
5892
  process.exit(1);
5143
5893
  }
5144
5894
  const reg = await registry();
5145
- const modePath = join14(dirname7(from), "modo");
5146
- const modeOverride = existsSync10(modePath) ? readFileSync7(modePath, "utf8") : null;
5895
+ const modePath = join15(dirname7(from), "modo");
5896
+ const modeOverride = existsSync12(modePath) ? readFileSync7(modePath, "utf8") : null;
5147
5897
  const { config: imported, notes } = importAimonitor(JSON.parse(readFileSync7(from, "utf8")), reg, modeOverride, { withSecrets: flag("--with-secrets") });
5148
5898
  if (modeOverride) notes.push(`mode from ${modePath}: ${modeOverride.trim()}`);
5149
5899
  for (const n of notes) console.log(`- ${n}`);
5150
5900
  if (flag("--write")) {
5151
- if (existsSync10(path)) writeFileSync11(`${path}.bak`, readFileSync7(path));
5901
+ if (existsSync12(path)) writeFileSync11(`${path}.bak`, readFileSync7(path));
5152
5902
  saveConfig(imported, path);
5153
- console.log(`written ${path}${existsSync10(`${path}.bak`) ? ` (previous one in ${path}.bak)` : ""}`);
5903
+ console.log(`written ${path}${existsSync12(`${path}.bak`) ? ` (previous one in ${path}.bak)` : ""}`);
5154
5904
  } else {
5155
5905
  console.log(JSON.stringify(imported, null, 2));
5156
5906
  console.log("\n(dry run: add --write to save it)");
5157
5907
  }
5158
5908
  return;
5159
5909
  }
5910
+ case "usb": {
5911
+ if (argv[1] === "test") {
5912
+ process.env.KIOSKO_QUIET ??= "1";
5913
+ const reg = await registry();
5914
+ const [w, h] = (opt("--size") ?? "1920x462").split("x").map(Number);
5915
+ const cfg = starterConfig(reg, { width: w || 1920, height: h || 462 });
5916
+ const screen = cfg.screens[0];
5917
+ screen.device = { driver: "usb", ...opt("--serial") ? { serial: opt("--serial") } : {} };
5918
+ screen.rotate = Number(opt("--rotate") ?? 0);
5919
+ const rt = new Runtime(reg, cfg, { demo: true });
5920
+ rt.start();
5921
+ const seconds = Number(opt("--seconds") ?? 10);
5922
+ let ok = false;
5923
+ for (let i = 0; i < seconds; i++) {
5924
+ await new Promise((r) => setTimeout(r, 1e3));
5925
+ const d = rt.status().screens[0]?.device;
5926
+ ok ||= !!d?.ok;
5927
+ console.log(`${String(i + 1).padStart(2)} s ${d?.ok ? "ok " : "ERR"} ${d?.message ?? ""} frames ${d?.framesSent ?? 0}`);
5928
+ }
5929
+ rt.stop();
5930
+ process.exitCode = ok ? 0 : 1;
5931
+ return;
5932
+ }
5933
+ const usb = await listUsb();
5934
+ if (!usb.ok) console.log(`usb not available: ${usb.error}`);
5935
+ else if (!usb.panels.length) console.log("no LY panel (0416:5408/5409) plugged in");
5936
+ for (const p of usb.panels) console.log(`LY panel ${p.pid.toString(16)} at ${p.location}, serial ${p.serial ?? "(unreadable)"}${p.error ? ` \u2717 ${p.error}` : ""}`);
5937
+ return;
5938
+ }
5160
5939
  case "doctor": {
5161
5940
  const reg = await registry();
5162
5941
  const { config: cfg, exists, error } = loadConfig(path);
@@ -5164,6 +5943,10 @@ async function main() {
5164
5943
  console.log(`config ${path} ${exists ? error ? `INVALID: ${error}` : "ok" : "(not created yet)"}`);
5165
5944
  console.log(`plugins ${reg.list().map((p) => p.def.id).join(", ")}`);
5166
5945
  for (const p of reg.problems) console.log(` \u2717 ${p.origin}: ${p.message}`);
5946
+ const usb = await listUsb();
5947
+ if (!usb.ok) console.log(`usb not available: ${usb.error}`);
5948
+ else if (!usb.panels.length) console.log("usb no LY panel (0416:5408/5409) plugged in");
5949
+ for (const p of usb.panels) console.log(`usb LY panel ${p.pid.toString(16)} at ${p.location}, serial ${p.serial ?? "(unreadable)"}${p.error ? ` \u2717 ${p.error}` : ""}`);
5167
5950
  for (const s of cfg.screens) {
5168
5951
  const missing = s.pages.flatMap((p) => p.tiles.flatMap((t2) => t2.widgets.filter((w) => !reg.widget(w.type)).map((w) => w.type)));
5169
5952
  console.log(`screen ${s.name} ${s.width}\xD7${s.height} ${s.device.driver}${missing.length ? ` \u2717 unknown widgets: ${[...new Set(missing)].join(", ")}` : ""}`);
@@ -5201,6 +5984,7 @@ async function main() {
5201
5984
  return;
5202
5985
  case "version":
5203
5986
  case "--version":
5987
+ case "-v":
5204
5988
  console.log(VERSION);
5205
5989
  return;
5206
5990
  default: