kiosko 0.2.8 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -6,8 +6,8 @@ var __esm = (fn, res) => function __init() {
6
6
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
7
  };
8
8
  var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
9
+ for (var name2 in all)
10
+ __defProp(target, name2, { get: all[name2], enumerable: true });
11
11
  };
12
12
 
13
13
  // packages/sdk/src/workday.ts
@@ -86,12 +86,12 @@ function pickLocale(available2, locale) {
86
86
  function plural(n, forms, locale = "en") {
87
87
  const key = pickLocale(Object.keys(forms), locale) ?? (forms.en ? "en" : Object.keys(forms)[0]);
88
88
  const f = forms[key];
89
- let rule = "other";
89
+ let rule2 = "other";
90
90
  try {
91
- rule = new Intl.PluralRules(key).select(n);
91
+ rule2 = new Intl.PluralRules(key).select(n);
92
92
  } catch {
93
93
  }
94
- const text3 = f[rule] ?? f.other;
94
+ const text3 = f[rule2] ?? f.other;
95
95
  let num = String(n);
96
96
  try {
97
97
  num = new Intl.NumberFormat(key).format(n);
@@ -787,8 +787,8 @@ function moon(ctx, cx, cy, s) {
787
787
  const r = s * 0.24;
788
788
  const pad = 2;
789
789
  const side = Math.ceil(r * 2 + pad * 2);
790
- const off = createCanvas(side, side);
791
- const o = off.getContext("2d");
790
+ const off2 = createCanvas(side, side);
791
+ const o = off2.getContext("2d");
792
792
  const c = side / 2;
793
793
  o.fillStyle = ctx.fillStyle;
794
794
  o.beginPath();
@@ -798,7 +798,7 @@ function moon(ctx, cx, cy, s) {
798
798
  o.beginPath();
799
799
  o.arc(c + r * 0.55, c - r * 0.42, r * 0.92, 0, Math.PI * 2);
800
800
  o.fill();
801
- ctx.drawImage(off, cx - c, cy - c);
801
+ ctx.drawImage(off2, cx - c, cy - c);
802
802
  }
803
803
  function drops(ctx, cx, cy, s, len) {
804
804
  ctx.lineWidth = Math.max(1.5, s * 0.05);
@@ -896,8 +896,8 @@ function drawMoonPhase(ctx, moon2, cx, cy, size, color2) {
896
896
  const r = size / 2;
897
897
  const pad = 2;
898
898
  const side = Math.ceil(size + pad * 2);
899
- const off = createCanvas(side, side);
900
- const o = off.getContext("2d");
899
+ const off2 = createCanvas(side, side);
900
+ const o = off2.getContext("2d");
901
901
  const c = side / 2;
902
902
  o.fillStyle = color2;
903
903
  o.beginPath();
@@ -919,7 +919,7 @@ function drawMoonPhase(ctx, moon2, cx, cy, size, color2) {
919
919
  o.closePath();
920
920
  o.fill();
921
921
  ctx.save();
922
- ctx.drawImage(off, cx - c, cy - c);
922
+ ctx.drawImage(off2, cx - c, cy - c);
923
923
  ctx.strokeStyle = "rgba(255,255,255,0.22)";
924
924
  ctx.lineWidth = Math.max(1, size * 0.02);
925
925
  ctx.beginPath();
@@ -1103,13 +1103,13 @@ function checkPlugin(p, o = {}) {
1103
1103
  for (const size of sizes) {
1104
1104
  for (const theme of themes) {
1105
1105
  for (const locale of locales) {
1106
- const where = `${size.w}x${size.h} ${theme} ${locale}`;
1106
+ const where2 = `${size.w}x${size.h} ${theme} ${locale}`;
1107
1107
  const r2 = renderWidget(w, { size, theme, locale });
1108
- if (r2.error) issues.push({ type, where, problem: `render threw: ${r2.error}` });
1109
- else if (r2.outside > 0) issues.push({ type, where, problem: `painted ${r2.outside} px outside its box` });
1108
+ if (r2.error) issues.push({ type, where: where2, problem: `render threw: ${r2.error}` });
1109
+ else if (r2.outside > 0) issues.push({ type, where: where2, problem: `painted ${r2.outside} px outside its box` });
1110
1110
  if (r2.ms > slow && !r2.error) {
1111
1111
  const ms = Math.min(r2.ms, renderWidget(w, { size, theme, locale }).ms, renderWidget(w, { size, theme, locale }).ms);
1112
- if (ms > slow) issues.push({ type, where, problem: `render took ${Math.round(ms)} ms` });
1112
+ if (ms > slow) issues.push({ type, where: where2, problem: `render took ${Math.round(ms)} ms` });
1113
1113
  }
1114
1114
  }
1115
1115
  }
@@ -1138,9 +1138,9 @@ var init_testing = __esm({
1138
1138
  });
1139
1139
 
1140
1140
  // packages/server/src/cli.ts
1141
- import { spawn } from "node:child_process";
1142
- import { existsSync as existsSync15, readFileSync as readFileSync10, writeFileSync as writeFileSync12 } from "node:fs";
1143
- import { dirname as dirname8, join as join18 } from "node:path";
1141
+ import { spawn as spawn3 } from "node:child_process";
1142
+ import { existsSync as existsSync18, readFileSync as readFileSync13, writeFileSync as writeFileSync13 } from "node:fs";
1143
+ import { dirname as dirname9, join as join20 } from "node:path";
1144
1144
 
1145
1145
  // packages/core/src/config/model.ts
1146
1146
  init_workday();
@@ -1149,9 +1149,9 @@ init_workday();
1149
1149
  function suggestGrid(width, height, target = 80) {
1150
1150
  const rows = Math.max(2, Math.round(height / target));
1151
1151
  const cellH = height / rows;
1152
- const raw = Math.max(2, Math.round(width / cellH));
1153
- const near2 = [raw, raw - 1, raw + 1].filter((n) => n >= 2);
1154
- const cols = [12, 6, 4].map((d) => near2.find((n) => n % d === 0)).find((n) => n !== void 0) ?? raw;
1152
+ const raw2 = Math.max(2, Math.round(width / cellH));
1153
+ const near2 = [raw2, raw2 - 1, raw2 + 1].filter((n) => n >= 2);
1154
+ const cols = [12, 6, 4].map((d) => near2.find((n) => n % d === 0)).find((n) => n !== void 0) ?? raw2;
1155
1155
  const short2 = Math.min(width, height);
1156
1156
  const gap = short2 >= 400 ? 10 : short2 >= 240 ? 6 : 4;
1157
1157
  return { cols, rows, gap, padding: gap };
@@ -1202,6 +1202,12 @@ function rescale(items, from, to) {
1202
1202
  // packages/core/src/config/model.ts
1203
1203
  var CONFIG_VERSION = 1;
1204
1204
  var CONFIG_SCHEMA_ID = "https://kioskolcd.dev/schema/v1/config.json";
1205
+ function deviceRotates(d) {
1206
+ return d.driver === "remote";
1207
+ }
1208
+ function paintTurn(s) {
1209
+ return deviceRotates(s.device) ? 0 : s.rotate;
1210
+ }
1205
1211
  var ZOOM = { min: 0.5, max: 2, step: 0.1 };
1206
1212
  function zoomOf(inst) {
1207
1213
  const z = inst.zoom;
@@ -1228,14 +1234,19 @@ function inQuietHours(quiet, now) {
1228
1234
  var READING_CM = { near: 40, normal: 60, far: 90 };
1229
1235
  var TEXT_SCALE = { min: 0.75, max: 2, step: 0.05 };
1230
1236
  var DEFAULT_MAX_BYTES = 48e4;
1237
+ var SETUP_STATES = ["pending", "done", "skipped"];
1238
+ var STARTER_NAMES = {
1239
+ screen: { en: "My panel", es: "Mi panel", de: "Mein Panel", "zh-Hant": "\u6211\u7684\u9762\u677F", "zh-Hans": "\u6211\u7684\u5C4F\u5E55" },
1240
+ page: { en: "Home", es: "Inicio", de: "Start", "zh-Hant": "\u9996\u9801", "zh-Hans": "\u9996\u9875" }
1241
+ };
1231
1242
  var counter = 0;
1232
1243
  function newId(prefix = "id") {
1233
1244
  counter = (counter + 1) % 1296;
1234
1245
  return `${prefix}-${Date.now().toString(36).slice(-5)}${counter.toString(36).padStart(2, "0")}${Math.floor(Math.random() * 1296).toString(36).padStart(2, "0")}`;
1235
1246
  }
1236
- function newPage(name, width, height, tiles = []) {
1247
+ function newPage(name2, width, height, tiles = []) {
1237
1248
  const grid = suggestGrid(width, height);
1238
- return { id: newId("page"), name, enabled: true, durationMs: 10 * 6e4, when: "always", grid, gravity: width / height > 2.2 ? "left" : "up", background: {}, tiles };
1249
+ return { id: newId("page"), name: name2, enabled: true, durationMs: 10 * 6e4, when: "always", grid, gravity: width / height > 2.2 ? "left" : "up", background: {}, tiles };
1239
1250
  }
1240
1251
  function newTile(r, widgets = []) {
1241
1252
  return { id: newId("tile"), ...r, widgets, rotateMs: 3e4, chrome: "auto" };
@@ -1243,10 +1254,10 @@ function newTile(r, widgets = []) {
1243
1254
  function newWidget(type, options2 = {}, title) {
1244
1255
  return { id: newId("w"), type, options: options2, ...title ? { title } : {} };
1245
1256
  }
1246
- function newScreen(name, width = 1920, height = 462, device = { driver: "virtual" }) {
1257
+ function newScreen(name2, width = 1920, height = 462, device = { driver: "virtual" }) {
1247
1258
  return {
1248
1259
  id: newId("screen"),
1249
- name,
1260
+ name: name2,
1250
1261
  enabled: true,
1251
1262
  width,
1252
1263
  height,
@@ -1374,7 +1385,7 @@ var CATEGORIES = [
1374
1385
  ];
1375
1386
  var ALERT_LEVELS = ["info", "warn", "critical"];
1376
1387
  var PAD_KEYS = ["up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select"];
1377
- var SDK_VERSION = "0.2.8";
1388
+ var SDK_VERSION = "0.2.10";
1378
1389
  function defineWidget(w) {
1379
1390
  return w;
1380
1391
  }
@@ -1517,7 +1528,7 @@ import { join, win32 } from "node:path";
1517
1528
  function expandPath(p, o = {}) {
1518
1529
  const env = o.env ?? process.env;
1519
1530
  let v = p.replace(/\$(?:\{(\w+)\}|(\w+))/g, (whole, a, b) => env[a ?? b ?? ""] ?? whole);
1520
- if ((o.os ?? process.platform) === "win32") v = v.replace(/%([^%\r\n]+)%/g, (whole, name) => env[name] ?? whole);
1531
+ if ((o.os ?? process.platform) === "win32") v = v.replace(/%([^%\r\n]+)%/g, (whole, name2) => env[name2] ?? whole);
1521
1532
  const home = o.home ?? homedir();
1522
1533
  if (v === "~") return home;
1523
1534
  return v.startsWith("~/") || v.startsWith("~\\") ? join(home, v.slice(2)) : v;
@@ -1733,8 +1744,8 @@ var paths = {
1733
1744
  // packages/core/src/config/normalize.ts
1734
1745
  init_format();
1735
1746
  init_workday();
1736
- function normalize(raw) {
1737
- const { $schema, threads, ...c } = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
1747
+ function normalize(raw2) {
1748
+ const { $schema, threads, setup, bootAnimation, ...c } = raw2 && typeof raw2 === "object" && !Array.isArray(raw2) ? raw2 : {};
1738
1749
  const screens = Array.isArray(c.screens) ? c.screens.map(normalizeScreen) : [];
1739
1750
  return {
1740
1751
  ...typeof $schema === "string" && $schema ? { $schema } : {},
@@ -1749,6 +1760,9 @@ function normalize(raw) {
1749
1760
  server: { ...DEFAULT_CONFIG.server, ...c.server ?? {} },
1750
1761
  ...c.homeassistant && typeof c.homeassistant === "object" ? { homeassistant: normalizeHa(c.homeassistant) } : {},
1751
1762
  ...THREADS_MODES.includes(threads) ? { threads } : {},
1763
+ ...SETUP_STATES.includes(setup) ? { setup } : {},
1764
+ // On unless switched off: only `false` is written.
1765
+ ...bootAnimation === false ? { bootAnimation: false } : {},
1752
1766
  screens
1753
1767
  };
1754
1768
  }
@@ -1801,9 +1815,9 @@ function normalizeScreen(s, i) {
1801
1815
  };
1802
1816
  }
1803
1817
  var HHMM = /^([01][0-9]|2[0-3]):[0-5][0-9]$/;
1804
- function normalizeAlerts(raw) {
1805
- if (!raw || typeof raw !== "object") return {};
1806
- const a = raw;
1818
+ function normalizeAlerts(raw2) {
1819
+ if (!raw2 || typeof raw2 !== "object") return {};
1820
+ const a = raw2;
1807
1821
  const minLevel = ALERT_THRESHOLDS.includes(a.minLevel) ? a.minLevel : "info";
1808
1822
  const q3 = a.quiet;
1809
1823
  const quiet = q3 && typeof q3 === "object" && HHMM.test(String(q3.start)) && HHMM.test(String(q3.end)) && q3.start !== q3.end ? { start: q3.start, end: q3.end } : void 0;
@@ -2094,6 +2108,11 @@ function configSchema(plugins) {
2094
2108
  default: "auto",
2095
2109
  description: `Paint each screen in a thread of its own, so a slow widget on one does not slow the others: "auto" (with two or more screens on and a core to spare for each), "always", or "never" (every screen on the main thread: less memory, for a small machine). A screen's "thread" overrides it.`
2096
2110
  },
2111
+ setup: {
2112
+ enum: ["pending", "done", "skipped"],
2113
+ description: `The editor's first-run setup: "pending" as the first run writes it (the panels say how to open the editor), then "done" or "skipped", so it is not offered on its own again (Settings can always run it). Missing: offered while the config is still the first run's.`
2114
+ },
2115
+ bootAnimation: { type: "boolean", default: true, description: "A short animation of the Kiosko mark on every panel when Kiosko starts, before the pages." },
2097
2116
  homeassistant: {
2098
2117
  type: "object",
2099
2118
  additionalProperties: false,
@@ -2164,6 +2183,21 @@ function configSchema(plugins) {
2164
2183
  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." }
2165
2184
  }
2166
2185
  },
2186
+ {
2187
+ title: "Kiosko remote screen",
2188
+ description: "A screen on the network running Kiosko's screen firmware (firmware/esp32-screen: the Waveshare ESP32-C6-LCD-1.47 and others). Kiosko finds it by mDNS, pairs with it once with the code it shows, and sends it frames over an authenticated, encrypted session; the screen turns the picture to the screen's rotation itself. See docs/remote-screen.md.",
2189
+ type: "object",
2190
+ additionalProperties: false,
2191
+ required: ["driver", "uid"],
2192
+ properties: {
2193
+ driver: { const: "remote" },
2194
+ uid: { type: "string", pattern: "^[0-9a-f]{12}$", description: "The screen's unique id (12 hex digits, from its MAC), as it announces itself. It never changes, even when the screen is renamed." },
2195
+ id: { type: "string", description: "The name the screen had when it was added (it may be renamed on the screen's setup page); shown until the screen says its own." },
2196
+ key: { type: "string", pattern: "^[0-9a-f]{64}$", description: "The pairing key (64 hex digits), set by pairing in the editor. Empty: not paired yet.", "x-secret": true },
2197
+ host: { type: "string", description: "Address to use instead of finding it by mDNS (another subnet, a network without multicast).", "x-risk": "network" },
2198
+ port: { type: "integer", minimum: 1, maximum: 65535, default: 7428 }
2199
+ }
2200
+ },
2167
2201
  {
2168
2202
  title: "Frame file",
2169
2203
  description: "Writes frame.jpg atomically into a folder; an external sender takes it to the panel.",
@@ -2306,8 +2340,8 @@ function toPointer(segs) {
2306
2340
  function resolvePointer(root, ref) {
2307
2341
  if (!ref.startsWith("#")) throw new Error(`only local $ref are supported (${ref})`);
2308
2342
  let cur = root;
2309
- for (const raw of ref.slice(1).split("/").slice(1)) {
2310
- const key = decodeURIComponent(raw).replace(/~1/g, "/").replace(/~0/g, "~");
2343
+ for (const raw2 of ref.slice(1).split("/").slice(1)) {
2344
+ const key = decodeURIComponent(raw2).replace(/~1/g, "/").replace(/~0/g, "~");
2311
2345
  cur = Array.isArray(cur) ? cur[Number(key)] : isObj(cur) ? cur[key] : void 0;
2312
2346
  }
2313
2347
  if (cur === void 0) throw new Error(`$ref ${ref} points nowhere`);
@@ -2593,13 +2627,13 @@ function repeated(items, path, what2, out) {
2593
2627
  else seen.set(x.id, i);
2594
2628
  });
2595
2629
  }
2596
- function checkConfig(raw, plugins) {
2630
+ function checkConfig(raw2, plugins) {
2597
2631
  const errors = [];
2598
2632
  const warnings = [];
2599
- if (!isObj2(raw)) return { errors: [issue([], "the config must be a JSON object")], warnings };
2633
+ if (!isObj2(raw2)) return { errors: [issue([], "the config must be a JSON object")], warnings };
2600
2634
  let cfg;
2601
2635
  try {
2602
- cfg = normalize(raw);
2636
+ cfg = normalize(raw2);
2603
2637
  } catch {
2604
2638
  return { errors, warnings };
2605
2639
  }
@@ -2684,9 +2718,9 @@ function checkConfig(raw, plugins) {
2684
2718
  }
2685
2719
  return { errors, warnings };
2686
2720
  }
2687
- function validateConfig(raw, plugins, schema2 = configSchema(plugins)) {
2688
- const shape = validateJson(schema2, raw);
2689
- const more = checkConfig(raw, plugins);
2721
+ function validateConfig(raw2, plugins, schema2 = configSchema(plugins)) {
2722
+ const shape = validateJson(schema2, raw2);
2723
+ const more = checkConfig(raw2, plugins);
2690
2724
  return { errors: [...shape, ...more.errors], warnings: more.warnings };
2691
2725
  }
2692
2726
 
@@ -2723,7 +2757,7 @@ var pageText = (p) => {
2723
2757
  const ts = pageTypes(p);
2724
2758
  return `page ${q2(p.name)}: ${plural2(p.tiles.length, "tile")}${ts.length ? ` (${ts.slice(0, 6).join(", ")}${ts.length > 6 ? `, +${ts.length - 6} more` : ""})` : ""}`;
2725
2759
  };
2726
- 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;
2760
+ 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 === "remote" ? `remote ${d.id ?? d.uid}` : d.driver;
2727
2761
  var changedKeys = (a, b) => [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].filter((k) => !same(a[k], b[k]));
2728
2762
  function diffTiles(before, after, depth, out) {
2729
2763
  const m = match(before.tiles, after.tiles, rect);
@@ -2841,7 +2875,7 @@ function annotatedValues(config2, schema2) {
2841
2875
  const risks = risksOf(v.schema);
2842
2876
  const secret = v.schema["x-secret"] === true;
2843
2877
  if (!risks.length && !secret) return;
2844
- const add = (path, value) => {
2878
+ const add2 = (path, value) => {
2845
2879
  if (isObj3(value) || Array.isArray(value)) return;
2846
2880
  const ptr = toPointer(path);
2847
2881
  const prev = out.get(ptr);
@@ -2857,8 +2891,8 @@ function annotatedValues(config2, schema2) {
2857
2891
  ...v.parent && isObj3(v.parent.value) ? { holder: v.parent.schema } : prev?.holder ? { holder: prev.holder } : {}
2858
2892
  });
2859
2893
  };
2860
- if (Array.isArray(v.value)) v.value.forEach((x, i) => add([...v.path, i], x));
2861
- else add(v.path, v.value);
2894
+ if (Array.isArray(v.value)) v.value.forEach((x, i) => add2([...v.path, i], x));
2895
+ else add2(v.path, v.value);
2862
2896
  });
2863
2897
  return [...out.values()];
2864
2898
  }
@@ -2989,10 +3023,10 @@ function mergeSecrets(incoming, current, schema2) {
2989
3023
  if (!restored.has(parentKey)) {
2990
3024
  if (incContainers.has(parentKey)) continue;
2991
3025
  const holder = incContainers.get(stableKey(current, parentPath.slice(0, -1)));
2992
- const name = parentPath[parentPath.length - 1];
2993
- if (!holder || !isObj3(getAt(out, holder)) || typeof name !== "string") continue;
2994
- setAt(out, [...holder, name], clone2(getAt(current, parentPath)));
2995
- incContainers.set(parentKey, [...holder, name]);
3026
+ const name2 = parentPath[parentPath.length - 1];
3027
+ if (!holder || !isObj3(getAt(out, holder)) || typeof name2 !== "string") continue;
3028
+ setAt(out, [...holder, name2], clone2(getAt(current, parentPath)));
3029
+ incContainers.set(parentKey, [...holder, name2]);
2996
3030
  restored.add(parentKey);
2997
3031
  }
2998
3032
  kept.push({ a: { ...c, path: [...incContainers.get(parentKey), last2] }, from: c });
@@ -3002,11 +3036,11 @@ function mergeSecrets(incoming, current, schema2) {
3002
3036
  changed = false;
3003
3037
  kept.forEach((k, i) => {
3004
3038
  if (reverted.has(i)) return;
3005
- const why = hostMoved(schema2, out, k.a.path, current, k.from.path, k.from.holder);
3006
- if (!why) return;
3039
+ const why2 = hostMoved(schema2, out, k.a.path, current, k.from.path, k.from.holder);
3040
+ if (!why2) return;
3007
3041
  setAt(out, k.a.path, "");
3008
3042
  reverted.add(i);
3009
- toFill.push(item(k.a, why));
3043
+ toFill.push(item(k.a, why2));
3010
3044
  changed = true;
3011
3045
  });
3012
3046
  }
@@ -3016,24 +3050,24 @@ var CARRIED = ["locale", "timeFormat", "theme", "location", "workday", "plugins"
3016
3050
  function planImport(incoming, current, plugins, schema2 = configSchema(plugins)) {
3017
3051
  const report = validateConfig(incoming, plugins, schema2);
3018
3052
  const { config: merged2, ...secrets } = mergeSecrets(incoming, current, schema2);
3019
- const raw = isObj3(merged2) ? { ...merged2 } : {};
3053
+ const raw2 = isObj3(merged2) ? { ...merged2 } : {};
3020
3054
  const carried = [];
3021
3055
  for (const k of CARRIED) {
3022
- if (raw[k] === void 0 && current[k] !== void 0) {
3023
- raw[k] = clone2(current[k]);
3056
+ if (raw2[k] === void 0 && current[k] !== void 0) {
3057
+ raw2[k] = clone2(current[k]);
3024
3058
  carried.push(k);
3025
3059
  }
3026
3060
  }
3027
- if (raw.$schema === void 0 && current.$schema) raw.$schema = current.$schema;
3028
- const sources = isObj3(raw.sources) ? { ...raw.sources } : {};
3061
+ if (raw2.$schema === void 0 && current.$schema) raw2.$schema = current.$schema;
3062
+ const sources = isObj3(raw2.sources) ? { ...raw2.sources } : {};
3029
3063
  for (const [k, v] of Object.entries(current.sources)) {
3030
3064
  if (sources[k] === void 0) {
3031
3065
  sources[k] = clone2(v);
3032
3066
  carried.push(`sources[${JSON.stringify(k)}]`);
3033
3067
  }
3034
3068
  }
3035
- raw.sources = sources;
3036
- const config2 = normalize(raw);
3069
+ raw2.sources = sources;
3070
+ const config2 = normalize(raw2);
3037
3071
  return { report, config: config2, carried, diff: diffConfigs(current, config2), risks: listRisks(config2, schema2, current), secrets };
3038
3072
  }
3039
3073
 
@@ -3072,6 +3106,69 @@ function localizeSample(cfg, locale) {
3072
3106
  };
3073
3107
  }
3074
3108
 
3109
+ // packages/core/src/config/starter.ts
3110
+ init_i18n();
3111
+ function marketOf(locale) {
3112
+ const market = languageById(pickLocale(LANGUAGE_IDS, locale ?? "en") ?? "en")?.plugins;
3113
+ return {
3114
+ offered: (t2) => !market?.without.includes(t2.split("/")[0]) && !market?.instead[t2],
3115
+ instead: (t2) => market?.instead[t2]
3116
+ };
3117
+ }
3118
+ function starterPage(has, o) {
3119
+ const { width, height } = o;
3120
+ const L = (t2) => localize(t2, o.locale ?? "en");
3121
+ const { offered } = marketOf(o.locale);
3122
+ const ok = (t2) => offered(t2) && has(t2) && (o.weather !== false || !t2.startsWith("weather/"));
3123
+ const page = newPage(o.name ?? L(STARTER_NAMES.page), width, height);
3124
+ page.grid = { cols: 24, rows: 6, gap: 10, padding: 10 };
3125
+ page.gravity = "left";
3126
+ const tiles = [];
3127
+ const add2 = (r, types2, title) => {
3128
+ const ws = types2.filter((t2) => ok(typeof t2 === "string" ? t2 : t2[0])).map((t2) => typeof t2 === "string" ? newWidget(t2, {}, title) : newWidget(t2[0], { ...t2[1] }, title));
3129
+ if (ws.length) tiles.push(newTile(r, ws));
3130
+ };
3131
+ const lead = "agents/sessions";
3132
+ const agents = o.agents !== false && ok(lead);
3133
+ if (agents) {
3134
+ add2({ x: 0, y: 0, w: 11, h: 6 }, [lead]);
3135
+ add2({ x: 11, y: 0, w: 5, h: 4 }, ["core/clock"]);
3136
+ } else {
3137
+ add2({ x: 0, y: 0, w: 11, h: 6 }, [["core/clock", { showDate: true }]]);
3138
+ add2({ x: 11, y: 0, w: 5, h: 4 }, ["core/date"]);
3139
+ }
3140
+ add2({ x: 11, y: 4, w: 5, h: 2 }, ["weather/forecast", "mirror/compliments"]);
3141
+ add2({ x: 16, y: 0, w: 8, h: 6 }, ["vitals/vitals", "system/health", "usage/rail", "mirror/countdown"].filter(ok).slice(0, 3));
3142
+ if (!tiles.length) {
3143
+ add2({ x: 0, y: 0, w: 24, h: 6 }, ["core/text"], L({ en: "Welcome", es: "Bienvenida", de: "Willkommen", "zh-Hant": "\u6B61\u8FCE", "zh-Hans": "\u6B22\u8FCE" }));
3144
+ const welcome = tiles[0]?.widgets[0];
3145
+ if (welcome) welcome.options = { text: L({ en: "Hi there.\nDrag widgets from the library to build your panel.", es: "Hola.\nArrastra widgets desde la biblioteca para montar tu panel.", de: "Hallo!\nZieh Widgets aus der Bibliothek, um dein Panel zu gestalten.", "zh-Hant": "\u4F60\u597D\u3002\n\u5F9E\u5C0F\u5DE5\u5177\u5EAB\u62D6\u66F3\u5C0F\u5DE5\u5177\uFF0C\n\u6253\u9020\u4F60\u7684\u9762\u677F\u3002", "zh-Hans": "\u4F60\u597D\u3002\n\u4ECE\u7EC4\u4EF6\u5E93\u62D6\u52A8\u5C0F\u7EC4\u4EF6\uFF0C\n\u5E03\u7F6E\u4F60\u7684\u526F\u5C4F\u3002" }), maxSize: 54 };
3146
+ }
3147
+ page.tiles = tiles;
3148
+ if (height > width) transposePage(page, width, height);
3149
+ else {
3150
+ const grid = suggestGrid(width, height);
3151
+ page.tiles = rescale(page.tiles, page.grid, grid);
3152
+ page.grid = grid;
3153
+ }
3154
+ return page;
3155
+ }
3156
+ function starterInterludes(hasInterlude, locale) {
3157
+ return marketOf(locale).offered("agents/runner") && hasInterlude("agents/runner") ? [{ id: "interlude-runner", type: "agents/runner", enabled: false, everyMs: 15 * 6e4, maxSeconds: 30, options: {} }] : [];
3158
+ }
3159
+ var STARTER_TYPES = /* @__PURE__ */ new Set(["agents/sessions", "core/text", "core/clock", "core/date", "weather/forecast", "mirror/compliments", "usage/rail", "vitals/vitals", "system/health", "mirror/countdown"]);
3160
+ function looksLikeStarter(c) {
3161
+ if (c.screens.length !== 1) return false;
3162
+ const s = c.screens[0];
3163
+ const named = (name2, names) => Object.values(names).includes(name2);
3164
+ if (s.device.driver !== "virtual" || !named(s.name, STARTER_NAMES.screen) || s.pages.length !== 1) return false;
3165
+ const p = s.pages[0];
3166
+ return named(p.name, STARTER_NAMES.page) && p.tiles.length <= 4 && p.tiles.every((t2) => t2.widgets.every((w) => STARTER_TYPES.has(w.type)));
3167
+ }
3168
+ function offersSetup(c) {
3169
+ return c.setup === "pending" || !c.setup && (c.screens.length === 0 || looksLikeStarter(c));
3170
+ }
3171
+
3075
3172
  // packages/core/src/layout/stack.ts
3076
3173
  function pickInStack(entries, now, rotateMs) {
3077
3174
  const urgent = entries.find((e) => e.visible && e.urgent);
@@ -3295,9 +3392,9 @@ var FontFallback = class {
3295
3392
  memo = /* @__PURE__ */ new Map();
3296
3393
  /** Sets the families; true if they changed (callers then forget measured widths). */
3297
3394
  setFamilies(families) {
3298
- const tail = families.map((f) => `, "${f.replace(/"/g, "")}"`).join("");
3299
- if (tail === this.tail) return false;
3300
- this.tail = tail;
3395
+ const tail2 = families.map((f) => `, "${f.replace(/"/g, "")}"`).join("");
3396
+ if (tail2 === this.tail) return false;
3397
+ this.tail = tail2;
3301
3398
  this.memo.clear();
3302
3399
  return true;
3303
3400
  }
@@ -3384,7 +3481,7 @@ var PROBE = "\u9AD4";
3384
3481
  var missingPixels = /* @__PURE__ */ new Map();
3385
3482
  var available = /* @__PURE__ */ new Map();
3386
3483
  var probeCanvas = null;
3387
- function pixelsOf(font, probe = PROBE) {
3484
+ function pixelsOf(font, probe2 = PROBE) {
3388
3485
  probeCanvas ??= createCanvas4(40, 40);
3389
3486
  const g = probeCanvas.getContext("2d");
3390
3487
  g.clearRect(0, 0, 40, 40);
@@ -3392,16 +3489,16 @@ function pixelsOf(font, probe = PROBE) {
3392
3489
  else g.font = font;
3393
3490
  g.fillStyle = "#000";
3394
3491
  g.textBaseline = "top";
3395
- g.fillText(probe, 4, 4);
3492
+ g.fillText(probe2, 4, 4);
3396
3493
  return Buffer.from(g.getImageData(0, 0, 40, 40).data.buffer).toString("base64");
3397
3494
  }
3398
- function hasFontFamily(family, probe = PROBE) {
3399
- const key = `${family}\0${probe}`;
3495
+ function hasFontFamily(family, probe2 = PROBE) {
3496
+ const key = `${family}\0${probe2}`;
3400
3497
  let yes = available.get(key);
3401
3498
  if (yes === void 0) {
3402
- let missing = missingPixels.get(probe);
3403
- if (missing === void 0) missingPixels.set(probe, missing = pixelsOf('28px "Kiosko Missing Font"', probe));
3404
- yes = pixelsOf(`28px "${family.replace(/"/g, "")}"`, probe) !== missing;
3499
+ let missing = missingPixels.get(probe2);
3500
+ if (missing === void 0) missingPixels.set(probe2, missing = pixelsOf('28px "Kiosko Missing Font"', probe2));
3501
+ yes = pixelsOf(`28px "${family.replace(/"/g, "")}"`, probe2) !== missing;
3405
3502
  available.set(key, yes);
3406
3503
  }
3407
3504
  return yes;
@@ -3853,7 +3950,7 @@ var AnimationScheduler = class {
3853
3950
  };
3854
3951
 
3855
3952
  // packages/core/src/runtime.ts
3856
- import { EventEmitter } from "node:events";
3953
+ import { EventEmitter as EventEmitter2 } from "node:events";
3857
3954
  import { availableParallelism as availableParallelism2 } from "node:os";
3858
3955
 
3859
3956
  // packages/core/src/alerts.ts
@@ -3880,9 +3977,9 @@ function text(x, locale) {
3880
3977
  if (x && typeof x === "object" && typeof x.en === "string") return oneLine(localize(x, locale));
3881
3978
  return "";
3882
3979
  }
3883
- function parseAlert(raw, now, locale) {
3884
- if (!raw || typeof raw !== "object") throw new AlertError("an alert is an object", "badAlert");
3885
- const a = raw;
3980
+ function parseAlert(raw2, now, locale) {
3981
+ if (!raw2 || typeof raw2 !== "object") throw new AlertError("an alert is an object", "badAlert");
3982
+ const a = raw2;
3886
3983
  const id = typeof a.id === "string" ? a.id.trim() : "";
3887
3984
  if (!id || id.length > 120) throw new AlertError("an alert needs an id", "badAlert");
3888
3985
  if (!ALERT_LEVELS.includes(a.level)) throw new AlertError(`level must be one of ${ALERT_LEVELS.join(", ")}`, "badAlert");
@@ -3945,8 +4042,8 @@ var AlertBoard = class {
3945
4042
  this.fromPlugins = next;
3946
4043
  }
3947
4044
  /** An alert from outside (`POST /api/alerts`). The same id again replaces it, and it shows again. */
3948
- post(raw, now, locale, screenIds = []) {
3949
- const body2 = raw && typeof raw === "object" ? { ...raw } : raw;
4045
+ post(raw2, now, locale, screenIds = []) {
4046
+ const body2 = raw2 && typeof raw2 === "object" ? { ...raw2 } : raw2;
3950
4047
  if (body2 && typeof body2 === "object" && !body2.id) body2.id = `alert-${now.toString(36)}${Math.floor(Math.random() * 1296).toString(36)}`;
3951
4048
  for (const k of ["source", "detail"]) {
3952
4049
  const v = body2 && typeof body2 === "object" ? body2[k] : void 0;
@@ -3954,7 +4051,7 @@ var AlertBoard = class {
3954
4051
  }
3955
4052
  const a = parseAlert(body2, now, locale);
3956
4053
  if (!EXTERNAL_ID.test(a.id)) throw new AlertError('the id may have only letters, digits, ".", "_" and "-" (up to 80)', "badAlert");
3957
- const screens = raw.screens;
4054
+ const screens = raw2.screens;
3958
4055
  let only;
3959
4056
  if (screens !== void 0) {
3960
4057
  if (!Array.isArray(screens) || !screens.every((s) => typeof s === "string")) throw new AlertError("screens is a list of screen ids", "badAlert");
@@ -4025,9 +4122,9 @@ var AlertBoard = class {
4025
4122
  * settings let through (level, quiet hours; only `critical` while `off`),
4026
4123
  * with the count of the others. Its test alert always does.
4027
4124
  */
4028
- forScreen(screen, now, off = false) {
4125
+ forScreen(screen, now, off2 = false) {
4029
4126
  const cfg = screenAlerts(screen);
4030
- const onlyCritical = off || inQuietHours(cfg.quiet, now);
4127
+ const onlyCritical = off2 || inQuietHours(cfg.quiet, now);
4031
4128
  const min = Math.max(levelRank(cfg.minLevel), onlyCritical ? levelRank("critical") : 0);
4032
4129
  const here = this.list(now).filter((a) => !a.snoozedUntil && (!a.screens || a.screens.includes(screen.id)) && (a.origin === "test" || levelRank(a.level) >= min));
4033
4130
  return here.length ? { top: here[0], more: here.length - 1 } : null;
@@ -4332,12 +4429,12 @@ function parseHandshake(resp, pid) {
4332
4429
  const at = (i) => resp.length > i ? String(resp[i]) : "N/A";
4333
4430
  throw new UnrecognisedReply(`handshake validation failed (length ${resp.length}, [0]=${at(0)}, [1]=${at(1)}, [8]=${at(8)})`);
4334
4431
  }
4335
- const raw = resp.subarray(0, Math.min(resp.length, 64));
4432
+ const raw2 = resp.subarray(0, Math.min(resp.length, 64));
4336
4433
  if (variantOf(pid) === "ly") {
4337
4434
  const r = resp[20] <= 3 ? 1 : resp[20];
4338
- return { pm: 64 + r, sub: (resp[22] ?? 0) + 1, raw };
4435
+ return { pm: 64 + r, sub: (resp[22] ?? 0) + 1, raw: raw2 };
4339
4436
  }
4340
- return { pm: 49 + resp[20], sub: resp[22] ?? 0, raw };
4437
+ return { pm: 49 + resp[20], sub: resp[22] ?? 0, raw: raw2 };
4341
4438
  }
4342
4439
  var ANGLES_1920 = [180, 180, 0, 0, 0, 180, 180, 180, 180];
4343
4440
  var MODELS = {
@@ -4397,9 +4494,9 @@ var UsbUnavailable = class extends Error {
4397
4494
  async function loadUsb() {
4398
4495
  try {
4399
4496
  const m = await import("usb");
4400
- const mod = m.getDeviceList ? m : m.default?.getDeviceList ? m.default : m.usb;
4401
- if (!mod?.getDeviceList) throw new Error("the usb module has no getDeviceList");
4402
- return mod;
4497
+ const mod2 = m.getDeviceList ? m : m.default?.getDeviceList ? m.default : m.usb;
4498
+ if (!mod2?.getDeviceList) throw new Error("the usb module has no getDeviceList");
4499
+ return mod2;
4403
4500
  } catch (err) {
4404
4501
  throw new UsbUnavailable(`cannot load the "usb" package (libusb): ${err instanceof Error ? err.message : String(err)}. Install it with: npm install usb`);
4405
4502
  }
@@ -4567,10 +4664,10 @@ function usbPathForSerial(serial, root = "/sys/bus/usb/devices") {
4567
4664
  } catch {
4568
4665
  return null;
4569
4666
  }
4570
- for (const name of entries) {
4571
- if (!/^\d+-[\d.]+$/.test(name)) continue;
4667
+ for (const name2 of entries) {
4668
+ if (!/^\d+-[\d.]+$/.test(name2)) continue;
4572
4669
  try {
4573
- if (readFileSync2(`${root}/${name}/serial`, "utf8").trim() === serial) return name;
4670
+ if (readFileSync2(`${root}/${name2}/serial`, "utf8").trim() === serial) return name2;
4574
4671
  } catch {
4575
4672
  }
4576
4673
  }
@@ -4648,10 +4745,10 @@ Content-Type: image/${jpeg ? "jpeg" : "png"}\r
4648
4745
  \r
4649
4746
  `
4650
4747
  );
4651
- const tail = Buffer.from(`\r
4748
+ const tail2 = Buffer.from(`\r
4652
4749
  --${boundary}--\r
4653
4750
  `);
4654
- return { body: Buffer.concat([head, image2, tail]), contentType: `multipart/form-data; boundary=${boundary}` };
4751
+ return { body: Buffer.concat([head, image2, tail2]), contentType: `multipart/form-data; boundary=${boundary}` };
4655
4752
  }
4656
4753
  async function sendFrame(o, key, image2) {
4657
4754
  const { body: body2, contentType } = multipartImage(image2);
@@ -4743,6 +4840,996 @@ function pinFrame(o, key, intervalS, onError) {
4743
4840
  };
4744
4841
  }
4745
4842
 
4843
+ // packages/core/src/remote/crypto.ts
4844
+ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual } from "node:crypto";
4845
+
4846
+ // packages/core/src/remote/p256.ts
4847
+ var P = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn;
4848
+ var N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
4849
+ var B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn;
4850
+ var GX = 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n;
4851
+ var GY = 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n;
4852
+ var G = { x: GX, y: GY };
4853
+ var mod = (a, m = P) => (a % m + m) % m;
4854
+ function pow(a, e, m = P) {
4855
+ let r = 1n;
4856
+ a = mod(a, m);
4857
+ while (e > 0n) {
4858
+ if (e & 1n) r = r * a % m;
4859
+ a = a * a % m;
4860
+ e >>= 1n;
4861
+ }
4862
+ return r;
4863
+ }
4864
+ var inv = (a, m = P) => pow(a, m - 2n, m);
4865
+ function onCurve(p) {
4866
+ if (!p) return false;
4867
+ if (p.x < 0n || p.x >= P || p.y < 0n || p.y >= P) return false;
4868
+ return mod(p.y * p.y - (p.x * p.x * p.x - 3n * p.x + B)) === 0n;
4869
+ }
4870
+ var toJac = (p) => p ? { x: p.x, y: p.y, z: 1n } : { x: 1n, y: 1n, z: 0n };
4871
+ function toAffine(j) {
4872
+ if (j.z === 0n) return null;
4873
+ const zi = inv(j.z);
4874
+ const zi2 = zi * zi % P;
4875
+ return { x: mod(j.x * zi2), y: mod(j.y * zi2 * zi) };
4876
+ }
4877
+ function dbl(p) {
4878
+ if (p.z === 0n || p.y === 0n) return { x: 1n, y: 1n, z: 0n };
4879
+ const z2 = mod(p.z * p.z);
4880
+ const m = mod(3n * (p.x - z2) * (p.x + z2));
4881
+ const y2 = mod(p.y * p.y);
4882
+ const s = mod(4n * p.x * y2);
4883
+ const x = mod(m * m - 2n * s);
4884
+ const y = mod(m * (s - x) - 8n * y2 * y2);
4885
+ return { x, y, z: mod(2n * p.y * p.z) };
4886
+ }
4887
+ function add(p, q3) {
4888
+ if (p.z === 0n) return q3;
4889
+ if (q3.z === 0n) return p;
4890
+ const z1 = mod(p.z * p.z), z2 = mod(q3.z * q3.z);
4891
+ const u1 = mod(p.x * z2), u2 = mod(q3.x * z1);
4892
+ const s1 = mod(p.y * z2 * q3.z), s2 = mod(q3.y * z1 * p.z);
4893
+ if (u1 === u2) return s1 === s2 ? dbl(p) : { x: 1n, y: 1n, z: 0n };
4894
+ const h = mod(u2 - u1), r = mod(s2 - s1);
4895
+ const h2 = mod(h * h), h3 = mod(h2 * h);
4896
+ const x = mod(r * r - h3 - 2n * u1 * h2);
4897
+ const y = mod(r * (u1 * h2 - x) - s1 * h3);
4898
+ return { x, y, z: mod(h * p.z * q3.z) };
4899
+ }
4900
+ function pointAdd(a, b) {
4901
+ return toAffine(add(toJac(a), toJac(b)));
4902
+ }
4903
+ function pointNeg(a) {
4904
+ return a ? { x: a.x, y: mod(-a.y) } : null;
4905
+ }
4906
+ function mul(k, p) {
4907
+ k = mod(k, N);
4908
+ let r = { x: 1n, y: 1n, z: 0n };
4909
+ let q3 = toJac(p);
4910
+ let r1 = q3;
4911
+ for (let i = 255; i >= 0; i--) {
4912
+ if (k >> BigInt(i) & 1n) {
4913
+ r = add(r, r1);
4914
+ r1 = dbl(r1);
4915
+ } else {
4916
+ r1 = add(r, r1);
4917
+ r = dbl(r);
4918
+ }
4919
+ }
4920
+ q3 = r;
4921
+ return toAffine(q3);
4922
+ }
4923
+ var hex32 = (n) => n.toString(16).padStart(64, "0");
4924
+ function encodePoint(p) {
4925
+ if (!p) throw new Error("cannot encode the point at infinity");
4926
+ return Buffer.from("04" + hex32(p.x) + hex32(p.y), "hex");
4927
+ }
4928
+ function decodePoint(b) {
4929
+ const buf = Buffer.from(b);
4930
+ let p;
4931
+ if (buf.length === 65 && buf[0] === 4) {
4932
+ p = { x: BigInt("0x" + buf.subarray(1, 33).toString("hex")), y: BigInt("0x" + buf.subarray(33).toString("hex")) };
4933
+ } else if (buf.length === 33 && (buf[0] === 2 || buf[0] === 3)) {
4934
+ const x = BigInt("0x" + buf.subarray(1).toString("hex"));
4935
+ const rhs = mod(x * x * x - 3n * x + B);
4936
+ let y = pow(rhs, (P + 1n) / 4n);
4937
+ if (mod(y * y) !== rhs) throw new Error("not a point of P-256");
4938
+ if ((y & 1n) !== BigInt(buf[0] - 2)) y = mod(-y);
4939
+ p = { x, y };
4940
+ } else throw new Error("bad point encoding");
4941
+ if (!onCurve(p)) throw new Error("not a point of P-256");
4942
+ return p;
4943
+ }
4944
+ var scalarFrom = (b) => BigInt("0x" + (Buffer.from(b).toString("hex") || "0"));
4945
+ var scalarBytes = (n) => Buffer.from(hex32(n), "hex");
4946
+
4947
+ // packages/core/src/remote/crypto.ts
4948
+ var PROTO = 1;
4949
+ var PORT = 7428;
4950
+ var NONCE_LEN = 32;
4951
+ var KEY_LEN = 32;
4952
+ var TAG_LEN = 16;
4953
+ var ID_A = "kiosko";
4954
+ var mn = null;
4955
+ function spakePoints() {
4956
+ mn ??= {
4957
+ M: decodePoint(Buffer.from("02886e2f97ace46e55ba9dd7242579f2993b64e16ef3dcab95afd497333d8fa12f", "hex")),
4958
+ N: decodePoint(Buffer.from("03d8bbd6c639c62937b04d997f38c3770719c629d7014d49a24b4f98baa1292b49", "hex"))
4959
+ };
4960
+ return mn;
4961
+ }
4962
+ var LABEL_AUTH_K = "KSv1 auth kiosko";
4963
+ var LABEL_AUTH_D = "KSv1 auth screen";
4964
+ var hkdf = (ikm, salt, info, len) => Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from(info), len));
4965
+ var hmac = (key, ...parts) => {
4966
+ const h = createHmac("sha256", key);
4967
+ for (const p of parts) h.update(p);
4968
+ return h.digest();
4969
+ };
4970
+ function equal2(a, b) {
4971
+ return a.length === b.length && timingSafeEqual(a, b);
4972
+ }
4973
+ function authMac(key, label, nk, nd, uid) {
4974
+ return hmac(key, label, nk, nd, uid);
4975
+ }
4976
+ function sessionKeys(key, nk, nd, side) {
4977
+ const okm = hkdf(key, Buffer.concat([nk, nd]), "KSv1 session", 64);
4978
+ const k2d = okm.subarray(0, 32), d2k = okm.subarray(32);
4979
+ return side === "kiosko" ? { tx: { key: Buffer.from(k2d), seq: 0n }, rx: { key: Buffer.from(d2k), seq: 0n } } : { tx: { key: Buffer.from(d2k), seq: 0n }, rx: { key: Buffer.from(k2d), seq: 0n } };
4980
+ }
4981
+ function nonceOf(seq) {
4982
+ const n = Buffer.alloc(12);
4983
+ n.writeBigUInt64BE(seq, 4);
4984
+ return n;
4985
+ }
4986
+ function seal(d, type, payload) {
4987
+ const len = 1 + payload.length + TAG_LEN;
4988
+ const hdr = Buffer.alloc(4);
4989
+ hdr.writeUInt32BE(len);
4990
+ const c = createCipheriv("chacha20-poly1305", d.key, nonceOf(d.seq), { authTagLength: TAG_LEN });
4991
+ c.setAAD(hdr, { plaintextLength: len - TAG_LEN });
4992
+ const out = Buffer.concat([hdr, c.update(Buffer.from([type])), c.update(payload), c.final(), c.getAuthTag()]);
4993
+ d.seq++;
4994
+ return out;
4995
+ }
4996
+ function open(d, hdr, body2) {
4997
+ if (body2.length < TAG_LEN + 1) throw new Error("sealed message too short");
4998
+ const dc = createDecipheriv("chacha20-poly1305", d.key, nonceOf(d.seq), { authTagLength: TAG_LEN });
4999
+ dc.setAAD(hdr, { plaintextLength: body2.length - TAG_LEN });
5000
+ dc.setAuthTag(body2.subarray(body2.length - TAG_LEN));
5001
+ const pt = Buffer.concat([dc.update(body2.subarray(0, body2.length - TAG_LEN)), dc.final()]);
5002
+ d.seq++;
5003
+ return { type: pt[0], payload: pt.subarray(1) };
5004
+ }
5005
+ function spakeW(uid, code) {
5006
+ const h = createHash("sha256").update("KSv1 pake w").update(uid).update(":").update(code).digest();
5007
+ return scalarFrom(h) % N;
5008
+ }
5009
+ function le64(n) {
5010
+ const b = Buffer.alloc(8);
5011
+ b.writeBigUInt64LE(BigInt(n));
5012
+ return b;
5013
+ }
5014
+ function transcript(uid, X, Y, K, w) {
5015
+ const parts = [Buffer.from(ID_A), Buffer.from(uid), X, Y, K, scalarBytes(w)];
5016
+ return Buffer.concat(parts.flatMap((p) => [le64(p.length), p]));
5017
+ }
5018
+ function spakeKeys(tt) {
5019
+ const h = createHash("sha256").update(tt).digest();
5020
+ const kc = hkdf(h, Buffer.alloc(0), "KSv1 confirm", 64);
5021
+ return { key: hkdf(h, Buffer.alloc(0), "KSv1 pair key", 32), cA: hmac(kc.subarray(0, 32), tt), cB: hmac(kc.subarray(32), tt) };
5022
+ }
5023
+ var randomScalar = () => {
5024
+ for (; ; ) {
5025
+ const k = scalarFrom(randomBytes(32));
5026
+ if (k > 0n && k < N) return k;
5027
+ }
5028
+ };
5029
+ var SpakeA = class {
5030
+ X;
5031
+ x;
5032
+ w;
5033
+ uid;
5034
+ constructor(uid, code, x) {
5035
+ this.uid = uid;
5036
+ this.w = spakeW(uid, code);
5037
+ this.x = x ?? randomScalar();
5038
+ this.X = encodePoint(pointAdd(mul(this.x, G), mul(this.w, spakePoints().M)));
5039
+ }
5040
+ finish(Yb) {
5041
+ const Y = decodePoint(Yb);
5042
+ const K = mul(this.x, pointAdd(Y, pointNeg(mul(this.w, spakePoints().N))));
5043
+ if (!K) throw new Error("bad Y");
5044
+ const Kb = encodePoint(K);
5045
+ return { ...spakeKeys(transcript(this.uid, this.X, encodePoint(Y), Kb, this.w)), K: Kb };
5046
+ }
5047
+ };
5048
+
5049
+ // packages/core/src/remote/link.ts
5050
+ import { connect } from "node:net";
5051
+ import { randomBytes as randomBytes2 } from "node:crypto";
5052
+ var T = {
5053
+ HELLO: 1,
5054
+ INFO: 2,
5055
+ AUTH: 3,
5056
+ AUTH_OK: 4,
5057
+ ERROR: 5,
5058
+ PAIR_START: 6,
5059
+ PAIR_READY: 7,
5060
+ PAIR_X: 8,
5061
+ PAIR_Y: 9,
5062
+ PAIR_CONFIRM: 10,
5063
+ PAIR_OK: 11,
5064
+ FRAME: 16,
5065
+ ACK: 17,
5066
+ SET: 18,
5067
+ STATE: 19,
5068
+ LED: 20,
5069
+ PING: 21,
5070
+ PONG: 22,
5071
+ UNPAIR: 23,
5072
+ OTA_BEGIN: 24,
5073
+ OTA_ACK: 25,
5074
+ OTA_DATA: 26,
5075
+ OTA_END: 27,
5076
+ OTA_DONE: 28,
5077
+ LOGS: 29
5078
+ };
5079
+ var ScreenError = class extends Error {
5080
+ code;
5081
+ constructor(code, message) {
5082
+ super(message);
5083
+ this.code = code;
5084
+ this.name = "ScreenError";
5085
+ }
5086
+ };
5087
+ var MAX_MSG = 1 << 20;
5088
+ var Wire = class _Wire {
5089
+ buf = Buffer.alloc(0);
5090
+ waiting = null;
5091
+ queue = [];
5092
+ ended = null;
5093
+ sock;
5094
+ constructor(sock) {
5095
+ this.sock = sock;
5096
+ sock.setNoDelay(true);
5097
+ sock.on("data", (d) => this.onData(d));
5098
+ const end = (e) => this.fail(e ?? new Error("connection closed"));
5099
+ sock.on("error", end);
5100
+ sock.on("close", () => end());
5101
+ }
5102
+ static open(host, port = PORT, timeoutMs = 4e3) {
5103
+ return new Promise((resolve8, reject) => {
5104
+ const s = connect({ host, port });
5105
+ const t2 = setTimeout(() => {
5106
+ s.destroy();
5107
+ reject(Object.assign(new Error(`no answer from ${host}:${port}`), { code: "ETIMEDOUT" }));
5108
+ }, timeoutMs);
5109
+ s.once("connect", () => {
5110
+ clearTimeout(t2);
5111
+ s.setKeepAlive(true, 1e4);
5112
+ resolve8(new _Wire(s));
5113
+ });
5114
+ s.once("error", (e) => {
5115
+ clearTimeout(t2);
5116
+ reject(e);
5117
+ });
5118
+ });
5119
+ }
5120
+ onData(d) {
5121
+ this.buf = this.buf.length ? Buffer.concat([this.buf, d]) : d;
5122
+ while (this.buf.length >= 4) {
5123
+ const len = this.buf.readUInt32BE(0);
5124
+ if (len < 1 || len > MAX_MSG) return this.fail(new Error(`bad message length ${len}`));
5125
+ if (this.buf.length < 4 + len) break;
5126
+ const m = { hdr: Buffer.from(this.buf.subarray(0, 4)), body: Buffer.from(this.buf.subarray(4, 4 + len)) };
5127
+ this.buf = this.buf.subarray(4 + len);
5128
+ if (this.waiting) {
5129
+ const w = this.waiting;
5130
+ this.waiting = null;
5131
+ w.resolve(m);
5132
+ } else this.queue.push(m);
5133
+ }
5134
+ }
5135
+ fail(e) {
5136
+ if (this.ended) return;
5137
+ this.ended = e;
5138
+ this.sock.destroy();
5139
+ const w = this.waiting;
5140
+ this.waiting = null;
5141
+ w?.reject(e);
5142
+ }
5143
+ get closed() {
5144
+ return !!this.ended;
5145
+ }
5146
+ /** The next message, raw; rejects on close or after `timeoutMs`. */
5147
+ next(timeoutMs = 1e4) {
5148
+ const q3 = this.queue.shift();
5149
+ if (q3) return Promise.resolve(q3);
5150
+ if (this.ended) return Promise.reject(this.ended);
5151
+ return new Promise((resolve8, reject) => {
5152
+ const t2 = setTimeout(() => {
5153
+ this.waiting = null;
5154
+ reject(Object.assign(new Error("the screen stopped answering"), { code: "ETIMEDOUT" }));
5155
+ }, timeoutMs);
5156
+ this.waiting = {
5157
+ resolve: (m) => {
5158
+ clearTimeout(t2);
5159
+ resolve8(m);
5160
+ },
5161
+ reject: (e) => {
5162
+ clearTimeout(t2);
5163
+ reject(e);
5164
+ }
5165
+ };
5166
+ });
5167
+ }
5168
+ write(b) {
5169
+ if (!this.ended) this.sock.write(b);
5170
+ }
5171
+ sendPlain(type, obj) {
5172
+ const p = Buffer.from(JSON.stringify(obj));
5173
+ const h = Buffer.alloc(5);
5174
+ h.writeUInt32BE(p.length + 1);
5175
+ h[4] = type;
5176
+ this.write(Buffer.concat([h, p]));
5177
+ }
5178
+ /** A plain message of type `want` (JSON); an ERROR from the screen becomes a ScreenError. */
5179
+ async plain(want, timeoutMs = 1e4) {
5180
+ const { body: body2 } = await this.next(timeoutMs);
5181
+ let j;
5182
+ try {
5183
+ j = JSON.parse(body2.subarray(1).toString("utf8"));
5184
+ } catch {
5185
+ throw new Error("the screen sent something unreadable");
5186
+ }
5187
+ if (body2[0] === T.ERROR) throw new ScreenError(String(j.code ?? "error"), String(j.msg ?? "refused"));
5188
+ if (body2[0] !== want) throw new Error(`unexpected message 0x${body2[0].toString(16)} from the screen`);
5189
+ return j;
5190
+ }
5191
+ close() {
5192
+ this.fail(new Error("closed"));
5193
+ }
5194
+ };
5195
+ function toInfo(j) {
5196
+ const num = (v, d = 0) => typeof v === "number" && Number.isFinite(v) ? v : d;
5197
+ return { proto: num(j.proto), uid: String(j.uid ?? ""), id: String(j.id ?? ""), model: String(j.model ?? ""), w: num(j.w), h: num(j.h), rot: num(j.rot), fw: String(j.fw ?? ""), paired: j.paired === true, ...typeof j.pairing === "boolean" ? { pairing: j.pairing } : {}, max: num(j.max, 64 * 1024) };
5198
+ }
5199
+ async function hello(w, want) {
5200
+ const nk = randomBytes2(NONCE_LEN);
5201
+ w.sendPlain(T.HELLO, { proto: PROTO, nonce: nk.toString("hex"), want });
5202
+ const j = await w.plain(T.INFO);
5203
+ const nd = Buffer.from(String(j.nonce ?? ""), "hex");
5204
+ if (nd.length !== NONCE_LEN) throw new Error("the screen sent no nonce");
5205
+ const info = toInfo(j);
5206
+ if (info.proto !== PROTO) {
5207
+ throw new ScreenError("proto", `the screen speaks protocol ${info.proto}, this Kiosko ${PROTO}: update one of them`);
5208
+ }
5209
+ return { info, nk, nd };
5210
+ }
5211
+ async function probe(host, port = PORT) {
5212
+ const w = await Wire.open(host, port);
5213
+ try {
5214
+ return (await hello(w, "info")).info;
5215
+ } finally {
5216
+ w.close();
5217
+ }
5218
+ }
5219
+ async function openSession(host, port, key, expectUid) {
5220
+ if (key.length !== KEY_LEN) throw new ScreenError("notPaired", "no pairing key for this screen");
5221
+ const wire = await Wire.open(host, port);
5222
+ try {
5223
+ const { info, nk, nd } = await hello(wire, "session");
5224
+ if (expectUid && info.uid !== expectUid) throw new ScreenError("otherScreen", `another screen (${info.id}, ${info.uid}) answers at ${host}`);
5225
+ wire.sendPlain(T.AUTH, { mac: authMac(key, LABEL_AUTH_K, nk, nd, info.uid).toString("hex") });
5226
+ const ok = await wire.plain(T.AUTH_OK);
5227
+ const want = authMac(key, LABEL_AUTH_D, nk, nd, info.uid);
5228
+ if (!equal2(Buffer.from(String(ok.mac ?? ""), "hex"), want)) throw new ScreenError("badScreen", "the screen could not prove it has the key: not the paired one");
5229
+ return { wire, info, session: sessionKeys(key, nk, nd, "kiosko") };
5230
+ } catch (err) {
5231
+ wire.close();
5232
+ throw err;
5233
+ }
5234
+ }
5235
+ function sendSealed(wire, s, type, payload = {}) {
5236
+ wire.write(seal(s.tx, type, Buffer.isBuffer(payload) ? payload : Buffer.from(JSON.stringify(payload))));
5237
+ }
5238
+ async function nextSealed(wire, s, timeoutMs = 15e3) {
5239
+ const { hdr, body: body2 } = await wire.next(timeoutMs);
5240
+ const m = open(s.rx, hdr, body2);
5241
+ return { ...m, json: () => JSON.parse(m.payload.toString("utf8") || "{}") };
5242
+ }
5243
+ var Pairing = class _Pairing {
5244
+ info;
5245
+ ttl;
5246
+ wire;
5247
+ done = false;
5248
+ constructor(wire, info, ttl) {
5249
+ this.wire = wire;
5250
+ this.info = info;
5251
+ this.ttl = ttl;
5252
+ }
5253
+ static async start(host, port, name2) {
5254
+ const wire = await Wire.open(host, port);
5255
+ try {
5256
+ const { info } = await hello(wire, "pair");
5257
+ wire.sendPlain(T.PAIR_START, { name: name2.slice(0, 40) });
5258
+ const r = await wire.plain(T.PAIR_READY);
5259
+ return new _Pairing(wire, info, typeof r.ttl === "number" ? r.ttl : 120);
5260
+ } catch (err) {
5261
+ wire.close();
5262
+ throw err;
5263
+ }
5264
+ }
5265
+ async finish(code) {
5266
+ if (this.done) throw new ScreenError("pairingOver", "this pairing is over: start again");
5267
+ this.done = true;
5268
+ try {
5269
+ const clean = code.replace(/\D/g, "");
5270
+ if (clean.length !== 6) throw new ScreenError("badCode", "the code has 6 digits");
5271
+ const a = new SpakeA(this.info.uid, clean);
5272
+ this.wire.sendPlain(T.PAIR_X, { X: a.X.toString("hex") });
5273
+ const y = await this.wire.plain(T.PAIR_Y, 15e3);
5274
+ const k = a.finish(Buffer.from(String(y.Y ?? ""), "hex"));
5275
+ if (!equal2(Buffer.from(String(y.c ?? ""), "hex"), k.cB)) {
5276
+ this.wire.sendPlain(T.PAIR_CONFIRM, { c: "00".repeat(32) });
5277
+ throw new ScreenError("badCode", "the code does not match the one on the screen");
5278
+ }
5279
+ this.wire.sendPlain(T.PAIR_CONFIRM, { c: k.cA.toString("hex") });
5280
+ await this.wire.plain(T.PAIR_OK, 15e3);
5281
+ return k.key;
5282
+ } finally {
5283
+ this.wire.close();
5284
+ }
5285
+ }
5286
+ cancel() {
5287
+ this.done = true;
5288
+ this.wire.close();
5289
+ }
5290
+ };
5291
+
5292
+ // packages/core/src/remote/mdns.ts
5293
+ import { createSocket } from "node:dgram";
5294
+ import { EventEmitter } from "node:events";
5295
+ import { networkInterfaces } from "node:os";
5296
+ var SERVICE = "_kiosko-screen._tcp.local";
5297
+ var service = SERVICE;
5298
+ var GROUP = "224.0.0.251";
5299
+ var MDNS_PORT = 5353;
5300
+ var TYPE = { A: 1, PTR: 12, TXT: 16, SRV: 33, ANY: 255 };
5301
+ function encodeName(name2) {
5302
+ const parts = name2.replace(/\.$/, "").split(".");
5303
+ return Buffer.concat([...parts.map((p) => Buffer.concat([Buffer.from([Buffer.byteLength(p)]), Buffer.from(p)])), Buffer.from([0])]);
5304
+ }
5305
+ function buildQuery(name2, type, unicast = false) {
5306
+ const h = Buffer.alloc(12);
5307
+ h.writeUInt16BE(1, 4);
5308
+ const q3 = Buffer.alloc(4);
5309
+ q3.writeUInt16BE(type, 0);
5310
+ q3.writeUInt16BE(unicast ? 32769 : 1, 2);
5311
+ return Buffer.concat([h, encodeName(name2), q3]);
5312
+ }
5313
+ function readName(b, at) {
5314
+ const labels = [];
5315
+ let next = -1;
5316
+ for (let hops = 0; hops < 32; hops++) {
5317
+ if (at >= b.length) throw new Error("truncated name");
5318
+ const len = b[at];
5319
+ if (len === 0) {
5320
+ if (next < 0) next = at + 1;
5321
+ return { name: labels.join("."), next };
5322
+ }
5323
+ if ((len & 192) === 192) {
5324
+ if (next < 0) next = at + 2;
5325
+ at = (len & 63) << 8 | b[at + 1];
5326
+ continue;
5327
+ }
5328
+ labels.push(b.toString("utf8", at + 1, at + 1 + len));
5329
+ at += 1 + len;
5330
+ }
5331
+ throw new Error("name loop");
5332
+ }
5333
+ function parseResponse(b) {
5334
+ if (b.length < 12) return [];
5335
+ const flags = b.readUInt16BE(2);
5336
+ if (!(flags & 32768)) return [];
5337
+ const qd = b.readUInt16BE(4);
5338
+ const total = b.readUInt16BE(6) + b.readUInt16BE(8) + b.readUInt16BE(10);
5339
+ let at = 12;
5340
+ for (let i = 0; i < qd; i++) at = readName(b, at).next + 4;
5341
+ const out = [];
5342
+ for (let i = 0; i < total && at < b.length; i++) {
5343
+ const { name: name2, next } = readName(b, at);
5344
+ at = next;
5345
+ if (at + 10 > b.length) break;
5346
+ const type = b.readUInt16BE(at);
5347
+ const ttl = b.readUInt32BE(at + 4);
5348
+ const len = b.readUInt16BE(at + 8);
5349
+ const rd = at + 10;
5350
+ at = rd + len;
5351
+ if (at > b.length) break;
5352
+ const r = { name: name2.toLowerCase(), type, ttl, data: {} };
5353
+ if (type === TYPE.PTR) r.data.ptr = readName(b, rd).name;
5354
+ else if (type === TYPE.SRV) r.data.srv = { port: b.readUInt16BE(rd + 4), target: readName(b, rd + 6).name.toLowerCase() };
5355
+ else if (type === TYPE.A && len === 4) r.data.a = `${b[rd]}.${b[rd + 1]}.${b[rd + 2]}.${b[rd + 3]}`;
5356
+ else if (type === TYPE.TXT) {
5357
+ const txt = {};
5358
+ for (let p = rd; p < rd + len; ) {
5359
+ const l = b[p];
5360
+ const s = b.toString("utf8", p + 1, p + 1 + l);
5361
+ const eq = s.indexOf("=");
5362
+ if (eq > 0) txt[s.slice(0, eq).toLowerCase()] = s.slice(eq + 1);
5363
+ p += 1 + l;
5364
+ }
5365
+ r.data.txt = txt;
5366
+ } else continue;
5367
+ out.push(r);
5368
+ }
5369
+ return out;
5370
+ }
5371
+ var ScreenBrowser = class extends EventEmitter {
5372
+ sock = null;
5373
+ starting = null;
5374
+ instances = /* @__PURE__ */ new Map();
5375
+ hosts = /* @__PURE__ */ new Map();
5376
+ found = /* @__PURE__ */ new Map();
5377
+ timer = null;
5378
+ users = 0;
5379
+ shared = true;
5380
+ /** Starts listening (idempotent). */
5381
+ start() {
5382
+ this.starting ??= new Promise((resolve8) => {
5383
+ const s = createSocket({ type: "udp4", reuseAddr: true });
5384
+ let bound = false;
5385
+ s.on("message", (m) => this.onMessage(m));
5386
+ s.on("error", () => void 0);
5387
+ s.once("error", () => {
5388
+ if (bound) return;
5389
+ s.close();
5390
+ this.shared = false;
5391
+ const e = createSocket({ type: "udp4" });
5392
+ e.on("message", (m) => this.onMessage(m));
5393
+ e.on("error", () => void 0);
5394
+ e.bind(0, () => {
5395
+ e.unref();
5396
+ this.sock = e;
5397
+ resolve8();
5398
+ });
5399
+ });
5400
+ s.bind(MDNS_PORT, () => {
5401
+ bound = true;
5402
+ s.unref();
5403
+ try {
5404
+ let joined = false;
5405
+ for (const list2 of Object.values(networkInterfaces())) {
5406
+ for (const i of list2 ?? []) {
5407
+ if (i.family !== "IPv4" || i.internal) continue;
5408
+ try {
5409
+ s.addMembership(GROUP, i.address);
5410
+ joined = true;
5411
+ } catch {
5412
+ }
5413
+ }
5414
+ }
5415
+ if (!joined) s.addMembership(GROUP);
5416
+ s.setMulticastTTL(255);
5417
+ } catch {
5418
+ }
5419
+ this.sock = s;
5420
+ resolve8();
5421
+ });
5422
+ });
5423
+ return this.starting;
5424
+ }
5425
+ send(name2, type) {
5426
+ if (!this.sock) return;
5427
+ try {
5428
+ this.sock.send(buildQuery(name2, type, !this.shared), MDNS_PORT, GROUP);
5429
+ } catch {
5430
+ }
5431
+ }
5432
+ /** Asks the LAN for screens now; answers come as `found`. */
5433
+ query() {
5434
+ this.send(service, TYPE.PTR);
5435
+ }
5436
+ onMessage(m) {
5437
+ let recs;
5438
+ try {
5439
+ recs = parseResponse(m);
5440
+ } catch {
5441
+ return;
5442
+ }
5443
+ if (!recs.length) return;
5444
+ const now = Date.now();
5445
+ const touched = /* @__PURE__ */ new Set();
5446
+ for (const r of recs) {
5447
+ if (r.type === TYPE.PTR && r.name === service && r.data.ptr) {
5448
+ const inst = r.data.ptr.toLowerCase();
5449
+ if (!this.instances.has(inst)) this.instances.set(inst, { instance: inst });
5450
+ touched.add(inst);
5451
+ } else if (r.type === TYPE.SRV && r.name.endsWith(`.${service}`)) {
5452
+ const p = this.instances.get(r.name) ?? { instance: r.name };
5453
+ p.srv = r.data.srv;
5454
+ this.instances.set(r.name, p);
5455
+ touched.add(r.name);
5456
+ } else if (r.type === TYPE.TXT && r.name.endsWith(`.${service}`)) {
5457
+ const p = this.instances.get(r.name) ?? { instance: r.name };
5458
+ p.txt = r.data.txt;
5459
+ this.instances.set(r.name, p);
5460
+ touched.add(r.name);
5461
+ } else if (r.type === TYPE.A && r.data.a) {
5462
+ this.hosts.set(r.name, { a: r.data.a, at: now });
5463
+ for (const [k, p] of this.instances) if (p.srv?.target === r.name) touched.add(k);
5464
+ }
5465
+ }
5466
+ for (const k of touched) {
5467
+ const p = this.instances.get(k);
5468
+ if (!p) continue;
5469
+ if (!p.srv || !p.txt) this.send(k, TYPE.ANY);
5470
+ else if (!this.hosts.has(p.srv.target)) this.send(p.srv.target, TYPE.A);
5471
+ const s = this.complete(p, now);
5472
+ if (!s) continue;
5473
+ const before = this.found.get(s.uid);
5474
+ this.found.set(s.uid, s);
5475
+ this.emit("found", s, before);
5476
+ }
5477
+ }
5478
+ complete(p, now) {
5479
+ const t2 = p.txt;
5480
+ if (!t2?.uid || !p.srv) return null;
5481
+ const host = this.hosts.get(p.srv.target);
5482
+ if (!host) return null;
5483
+ const n = (v) => v && /^\d+$/.test(v) ? Number(v) : 0;
5484
+ return { uid: t2.uid, id: t2.id ?? "", model: t2.model ?? "", w: n(t2.w), h: n(t2.h), rot: n(t2.rot), fw: t2.fw ?? "", proto: n(t2.proto), paired: t2.paired === "1", address: host.a, port: p.srv.port, hostname: p.srv.target, seenAt: now };
5485
+ }
5486
+ /** The screen with this uid, if heard of in the last `maxAgeMs`. */
5487
+ get(uid, maxAgeMs = 30 * 6e4) {
5488
+ const s = this.found.get(uid);
5489
+ return s && Date.now() - s.seenAt <= maxAgeMs ? s : void 0;
5490
+ }
5491
+ /** Screens heard of recently. */
5492
+ list(maxAgeMs = 10 * 6e4) {
5493
+ const now = Date.now();
5494
+ return [...this.found.values()].filter((s) => now - s.seenAt <= maxAgeMs).sort((a, b) => a.id.localeCompare(b.id));
5495
+ }
5496
+ /** Asks, waits `ms` for answers, and gives what it heard in that time (and before). */
5497
+ async browse(ms = 1500) {
5498
+ await this.start();
5499
+ const since = Date.now();
5500
+ this.query();
5501
+ await new Promise((r) => setTimeout(r, ms / 2));
5502
+ this.query();
5503
+ await new Promise((r) => setTimeout(r, ms / 2));
5504
+ return this.list().filter((s) => s.seenAt >= since - 6e4);
5505
+ }
5506
+ /** A remote screen holds it: asks again every minute while someone does. */
5507
+ retain() {
5508
+ this.users++;
5509
+ void this.start().then(() => this.query());
5510
+ if (!this.timer) {
5511
+ this.timer = setInterval(() => this.query(), 6e4);
5512
+ this.timer.unref();
5513
+ }
5514
+ }
5515
+ release() {
5516
+ if (--this.users > 0) return;
5517
+ this.users = 0;
5518
+ if (this.timer) clearInterval(this.timer);
5519
+ this.timer = null;
5520
+ }
5521
+ close() {
5522
+ this.release();
5523
+ this.sock?.close();
5524
+ this.sock = null;
5525
+ this.starting = null;
5526
+ }
5527
+ };
5528
+ var shared = null;
5529
+ function browser() {
5530
+ shared ??= new ScreenBrowser();
5531
+ shared.setMaxListeners(64);
5532
+ return shared;
5533
+ }
5534
+
5535
+ // packages/core/src/remote/device.ts
5536
+ var ROTATIONS = [0, 90, 180, 270];
5537
+ var RemoteDevice = class {
5538
+ status;
5539
+ cfg;
5540
+ log;
5541
+ rotate;
5542
+ rotDirty = false;
5543
+ deps;
5544
+ key;
5545
+ mdns;
5546
+ latest = null;
5547
+ latestNum = 0;
5548
+ fresh = false;
5549
+ led = null;
5550
+ ledDirty = false;
5551
+ closed = false;
5552
+ paused = 0;
5553
+ wire = null;
5554
+ failures = 0;
5555
+ lastSay = "";
5556
+ frameTimes = [];
5557
+ running = null;
5558
+ idle = [];
5559
+ connected = false;
5560
+ waiters = /* @__PURE__ */ new Set();
5561
+ onFound = (s) => {
5562
+ if (s.uid === this.cfg.uid) this.notify("found");
5563
+ };
5564
+ constructor(cfg, log, rotate = 0, deps = {}) {
5565
+ this.cfg = cfg;
5566
+ this.log = log;
5567
+ this.rotate = ROTATIONS.includes(rotate) ? rotate : 0;
5568
+ this.deps = { retryMs: 1e3, maxRetryMs: 3e4, pingMs: 5e3, ...deps };
5569
+ this.key = /^[0-9a-f]{64}$/i.test(cfg.key ?? "") ? Buffer.from(cfg.key, "hex") : null;
5570
+ this.mdns = deps.browser ?? browser();
5571
+ this.status = {
5572
+ driver: "remote",
5573
+ ok: false,
5574
+ message: "connecting\u2026",
5575
+ code: "connecting",
5576
+ framesSent: 0,
5577
+ lastSentAt: null,
5578
+ remote: { online: false, id: cfg.id ?? cfg.uid, host: cfg.host ?? null, fw: "", model: "", w: 0, h: 0, rot: this.rotate, fps: 0, rttMs: null, decodeMs: null, lastFrameAt: null, dropped: 0, since: null }
5579
+ };
5580
+ this.mdns.retain();
5581
+ this.mdns.on("found", this.onFound);
5582
+ if (!this.key) this.say(`${this.name()}: not paired yet (pair it in the editor: Screens \u2192 Detect panels)`, false, "remoteNotPaired", { id: this.name() });
5583
+ else this.running = this.run();
5584
+ }
5585
+ name() {
5586
+ return this.status?.remote.id || this.cfg.id || this.cfg.uid;
5587
+ }
5588
+ say(message, ok, code, params) {
5589
+ Object.assign(this.status, { ok, message, code, params });
5590
+ if (code !== this.lastSay) {
5591
+ this.lastSay = code;
5592
+ this.log(message);
5593
+ }
5594
+ }
5595
+ notify(why2) {
5596
+ for (const w of [...this.waiters]) w(why2);
5597
+ }
5598
+ /** Waits up to `ms` for one of `on` (or close). */
5599
+ wait(ms, on) {
5600
+ return new Promise((resolve8) => {
5601
+ const done2 = (why2) => {
5602
+ clearTimeout(t2);
5603
+ this.waiters.delete(hook);
5604
+ resolve8(why2);
5605
+ };
5606
+ const hook = (why2) => {
5607
+ if (why2 === "close" || on.includes(why2)) done2(why2);
5608
+ };
5609
+ const t2 = setTimeout(() => done2("time"), Math.max(0, ms));
5610
+ this.waiters.add(hook);
5611
+ if (this.closed) done2("close");
5612
+ });
5613
+ }
5614
+ /** JPEG of the logical (unrotated) picture: the screen turns it. Returns at once. */
5615
+ async send(frame) {
5616
+ if (this.latest && this.fresh) this.status.remote.dropped++;
5617
+ this.latest = frame;
5618
+ this.latestNum = this.latestNum + 1 >>> 0;
5619
+ this.fresh = true;
5620
+ this.notify("frame");
5621
+ }
5622
+ /** The screen's rotation changed in Kiosko's config: the screen turns at once (and on every reconnection). */
5623
+ setRotation(rotate) {
5624
+ const r = ROTATIONS.includes(rotate) ? rotate : 0;
5625
+ if (r === this.rotate) return;
5626
+ this.rotate = r;
5627
+ this.rotDirty = true;
5628
+ this.notify("frame");
5629
+ }
5630
+ /** Lights the screen's LED (`rgb` "rrggbb", "000000" off), e.g. for a full-screen alert. */
5631
+ setLed(rgb, blinkMs = 0) {
5632
+ const next = { rgb: /^[0-9a-f]{6}$/i.test(rgb) ? rgb.toLowerCase() : "000000", blink: Math.max(0, Math.round(blinkMs)) };
5633
+ if (this.led && this.led.rgb === next.rgb && this.led.blink === next.blink) return;
5634
+ this.led = next;
5635
+ this.ledDirty = true;
5636
+ this.notify("frame");
5637
+ }
5638
+ close() {
5639
+ if (this.closed) return;
5640
+ this.closed = true;
5641
+ this.mdns.off("found", this.onFound);
5642
+ this.mdns.release();
5643
+ this.wire?.close();
5644
+ this.notify("close");
5645
+ }
5646
+ /** Resolves when the loop is done (tests). */
5647
+ async closed_() {
5648
+ await this.running;
5649
+ }
5650
+ where() {
5651
+ if (this.cfg.host) return { host: this.cfg.host, port: this.cfg.port ?? PORT };
5652
+ const f = this.mdns.get(this.cfg.uid);
5653
+ return f ? { host: f.address, port: f.port || PORT } : null;
5654
+ }
5655
+ async run() {
5656
+ while (!this.closed) {
5657
+ if (this.paused) {
5658
+ for (const f of this.idle.splice(0)) f();
5659
+ await this.wait(6e4, ["resume"]);
5660
+ continue;
5661
+ }
5662
+ const at = this.where();
5663
+ if (!at) {
5664
+ this.offline(`${this.name()} is not on the network (no mDNS announcement yet)`, "remoteOffline");
5665
+ this.mdns.query();
5666
+ await this.backoff();
5667
+ continue;
5668
+ }
5669
+ let conn;
5670
+ try {
5671
+ conn = await (this.deps.open ?? openSession)(at.host, at.port, this.key, this.cfg.uid);
5672
+ } catch (err) {
5673
+ this.failed(err, at.host);
5674
+ await this.backoff(err);
5675
+ continue;
5676
+ }
5677
+ this.failures = 0;
5678
+ this.connected = true;
5679
+ try {
5680
+ await this.serve(conn, at.host);
5681
+ } catch (err) {
5682
+ if (!this.closed && !this.paused) this.failed(err, at.host);
5683
+ } finally {
5684
+ conn.wire.close();
5685
+ this.wire = null;
5686
+ this.connected = false;
5687
+ this.status.remote.online = false;
5688
+ this.status.remote.fps = 0;
5689
+ }
5690
+ if (!this.closed && !this.paused) await this.backoff();
5691
+ }
5692
+ for (const f of this.idle.splice(0)) f();
5693
+ }
5694
+ failed(err, host) {
5695
+ const e = err;
5696
+ const why2 = e?.message ?? String(err);
5697
+ if (err instanceof ScreenError && (e.code === "badKey" || e.code === "notPaired")) this.offline(`${this.name()} refuses this Kiosko's key: pair it again`, "remoteBadKey");
5698
+ else if (err instanceof ScreenError && e.code === "otherScreen") this.offline(`${host}: ${why2}`, "remoteOtherScreen", { host });
5699
+ else if (err instanceof ScreenError && e.code === "busy") this.offline(`${this.name()} is busy (updating?)`, "remoteBusy");
5700
+ else if (err instanceof ScreenError && e.code === "proto") this.offline(why2, "remoteProto", { why: why2 });
5701
+ else this.offline(`${this.name()} is offline (${why2})`, "remoteOffline");
5702
+ }
5703
+ offline(message, code, params = {}) {
5704
+ this.status.remote.online = false;
5705
+ this.status.remote.since = null;
5706
+ this.say(message, false, code, { id: this.name(), ...params });
5707
+ }
5708
+ /** A growing pause (with a little jitter); the screen announcing itself cuts it short. */
5709
+ async backoff(err) {
5710
+ this.failures++;
5711
+ const hopeless = err instanceof ScreenError && ["badKey", "notPaired", "proto"].includes(err.code);
5712
+ const base3 = hopeless ? 6e4 : Math.min(this.deps.maxRetryMs, this.deps.retryMs * 2 ** Math.min(this.failures - 1, 8));
5713
+ await this.wait(Math.round(base3 * (0.85 + Math.random() * 0.3)), ["found", "resume", "pause"]);
5714
+ }
5715
+ async serve(conn, host) {
5716
+ const { wire, info, session: session2 } = conn;
5717
+ this.wire = wire;
5718
+ const r = this.status.remote;
5719
+ Object.assign(r, { id: info.id || r.id, fw: info.fw, model: info.model, w: info.w, h: info.h, rot: info.rot, host, since: Date.now() });
5720
+ const st = await nextSealed(wire, session2);
5721
+ if (st.type !== T.STATE) throw new Error("the screen did not say its state");
5722
+ this.applyState(st.json());
5723
+ const extra = this.deps.settings?.() ?? {};
5724
+ sendSealed(wire, session2, T.SET, { rot: this.rotate, ...extra });
5725
+ this.rotDirty = false;
5726
+ this.ledDirty = !!this.led;
5727
+ this.fresh = !!this.latest;
5728
+ r.online = true;
5729
+ this.say(`${r.id}: online at ${host} (${info.model} ${info.fw})`, true, "remoteOnline", { id: r.id, host });
5730
+ let inflight = null;
5731
+ let lastTx = Date.now();
5732
+ let lastRx = Date.now();
5733
+ let reply = null;
5734
+ while (!this.closed && !wire.closed && !this.paused) {
5735
+ if (this.rotDirty) {
5736
+ this.rotDirty = false;
5737
+ sendSealed(wire, session2, T.SET, { rot: this.rotate });
5738
+ lastTx = Date.now();
5739
+ }
5740
+ if (this.ledDirty && this.led) {
5741
+ this.ledDirty = false;
5742
+ sendSealed(wire, session2, T.LED, this.led);
5743
+ lastTx = Date.now();
5744
+ }
5745
+ if (!inflight && this.fresh && this.latest) {
5746
+ const frame = this.latest;
5747
+ if (frame.length + 64 > info.max) {
5748
+ this.fresh = false;
5749
+ this.say(`${r.id}: a ${Math.round(frame.length / 1024)} KB frame is over the screen's ${Math.round(info.max / 1024)} KB: lower the JPEG quality`, true, "remoteTooBig", { id: r.id, kb: Math.round(frame.length / 1024), max: Math.round(info.max / 1024) });
5750
+ } else {
5751
+ this.fresh = false;
5752
+ const num = this.latestNum;
5753
+ const head = Buffer.alloc(4);
5754
+ head.writeUInt32BE(num);
5755
+ sendSealed(wire, session2, T.FRAME, Buffer.concat([head, frame]));
5756
+ inflight = { num, at: Date.now() };
5757
+ lastTx = inflight.at;
5758
+ }
5759
+ }
5760
+ if (Date.now() - lastTx >= this.deps.pingMs) {
5761
+ sendSealed(wire, session2, T.PING, {});
5762
+ lastTx = Date.now();
5763
+ }
5764
+ if (Date.now() - lastRx > 3 * this.deps.pingMs + 1e3) throw Object.assign(new Error("the screen stopped answering"), { code: "ETIMEDOUT" });
5765
+ reply ??= nextSealed(wire, session2, 3 * this.deps.pingMs + 1e3);
5766
+ const waitMs = Math.max(10, this.deps.pingMs - (Date.now() - lastTx));
5767
+ const got = await Promise.race([reply.then((m2) => ({ m: m2 })), this.wait(waitMs, inflight ? ["pause"] : ["frame", "pause"]).then(() => null)]);
5768
+ if (this.paused) return;
5769
+ if (!got) continue;
5770
+ reply = null;
5771
+ lastRx = Date.now();
5772
+ const { m } = got;
5773
+ if (m.type === T.ACK) {
5774
+ const a = m.json();
5775
+ if (inflight && a.n === inflight.num) {
5776
+ const now = Date.now();
5777
+ r.rttMs = now - inflight.at;
5778
+ r.decodeMs = typeof a.dec === "number" ? a.dec : null;
5779
+ if (a.ok !== false) {
5780
+ this.status.framesSent++;
5781
+ this.status.lastSentAt = now;
5782
+ r.lastFrameAt = now;
5783
+ this.frameTimes.push(now);
5784
+ while (this.frameTimes.length && now - this.frameTimes[0] > 5e3) this.frameTimes.shift();
5785
+ r.fps = this.frameTimes.length > 1 ? Math.round((this.frameTimes.length - 1) * 1e4 / (now - this.frameTimes[0])) / 10 : 0;
5786
+ } else this.log(`${r.id}: the screen could not show frame ${a.n}`);
5787
+ inflight = null;
5788
+ }
5789
+ } else if (m.type === T.STATE) {
5790
+ const j = m.json();
5791
+ this.applyState(j);
5792
+ if (j.resend === true && this.latest) this.fresh = true;
5793
+ } else if (m.type === T.PING) {
5794
+ sendSealed(wire, session2, T.PONG, {});
5795
+ }
5796
+ }
5797
+ }
5798
+ applyState(j) {
5799
+ const r = this.status.remote;
5800
+ if (typeof j.id === "string" && j.id) r.id = j.id;
5801
+ if (typeof j.rot === "number") r.rot = j.rot;
5802
+ if (typeof j.fw === "string") r.fw = j.fw;
5803
+ if (typeof j.w === "number") r.w = j.w;
5804
+ if (typeof j.h === "number") r.h = j.h;
5805
+ }
5806
+ /**
5807
+ * Runs `fn` while this driver stands aside: its session is closed and it
5808
+ * doesn't reconnect until `fn` is done (an update, the logs, unpairing open
5809
+ * their own session; the screen takes one at a time).
5810
+ */
5811
+ async exclusive(fn) {
5812
+ const at = this.where();
5813
+ if (!at) throw new ScreenError("offline", `${this.name()} is not on the network`);
5814
+ this.paused++;
5815
+ try {
5816
+ if (this.running) {
5817
+ const idle2 = new Promise((r) => this.idle.push(r));
5818
+ this.wire?.close();
5819
+ this.notify("pause");
5820
+ await idle2;
5821
+ }
5822
+ return await fn(at.host, at.port);
5823
+ } finally {
5824
+ this.paused--;
5825
+ this.notify("resume");
5826
+ }
5827
+ }
5828
+ get isConnected() {
5829
+ return this.connected;
5830
+ }
5831
+ };
5832
+
4746
5833
  // packages/core/src/devices.ts
4747
5834
  function coded(message, code, params) {
4748
5835
  return Object.assign(new Error(message), { code, params });
@@ -4758,7 +5845,7 @@ function statusOfError(err) {
4758
5845
  }
4759
5846
  function encodeFor(device, jpegQuality) {
4760
5847
  if (device.driver === "file") return device.format ?? "jpeg";
4761
- if (device.driver === "usb") return "jpeg";
5848
+ if (device.driver === "usb" || device.driver === "remote") return "jpeg";
4762
5849
  return jpegQuality > 0 ? "jpeg" : "png";
4763
5850
  }
4764
5851
  var VirtualDevice = class {
@@ -4916,10 +6003,10 @@ var UsbDevice = class {
4916
6003
  void p?.close().catch(() => void 0);
4917
6004
  this.failures++;
4918
6005
  this.retryAt = Date.now() + Math.min(30 * this.retryMs, this.retryMs * 2 ** Math.min(this.failures, 5));
4919
- const why = err instanceof Error ? err.message : String(err);
4920
- const serial = this.cfg.serial && !why.includes(this.cfg.serial) ? ` (serial ${this.cfg.serial})` : "";
6006
+ const why2 = err instanceof Error ? err.message : String(err);
6007
+ const serial = this.cfg.serial && !why2.includes(this.cfg.serial) ? ` (serial ${this.cfg.serial})` : "";
4921
6008
  const known = statusOfError(err);
4922
- this.say(`${why}${serial}; retrying`, false, "usbRetrying", { why, reason: known.code && known.code !== "error" ? known.code : "", serial: this.cfg.serial ?? "" });
6009
+ this.say(`${why2}${serial}; retrying`, false, "usbRetrying", { why: why2, reason: known.code && known.code !== "error" ? known.code : "", serial: this.cfg.serial ?? "" });
4923
6010
  }
4924
6011
  }
4925
6012
  };
@@ -4984,8 +6071,10 @@ async function discoverUsb() {
4984
6071
  return [];
4985
6072
  }
4986
6073
  }
4987
- function openDevice(cfg, log, rotate) {
6074
+ function openDevice(cfg, log, rotate, remote) {
4988
6075
  switch (cfg.driver) {
6076
+ case "remote":
6077
+ return new RemoteDevice(cfg, log, rotate ?? 0, remote);
4989
6078
  case "trcc":
4990
6079
  return new TrccDevice(cfg, log);
4991
6080
  case "usb":
@@ -5006,6 +6095,73 @@ async function discoverTrcc(url2 = "http://127.0.0.1:8099", tokenFile) {
5006
6095
  return [];
5007
6096
  }
5008
6097
  }
6098
+ async function discoverRemote(ms = 1500) {
6099
+ try {
6100
+ const found = await browser().browse(ms);
6101
+ return found.map((f) => ({ uid: f.uid, id: f.id, model: f.model, width: f.w, height: f.h, rotate: f.rot, fw: f.fw, paired: f.paired, address: f.address, port: f.port, hostname: f.hostname }));
6102
+ } catch {
6103
+ return [];
6104
+ }
6105
+ }
6106
+ function ledFor(level) {
6107
+ if (level === "critical") return ["ff0000", 400];
6108
+ if (level === "warn") return ["ffa000", 1e3];
6109
+ if (level === "info") return ["0060ff", 0];
6110
+ return ["000000", 0];
6111
+ }
6112
+
6113
+ // packages/core/src/remote/tz.ts
6114
+ var formats = /* @__PURE__ */ new Map();
6115
+ function offsetMinutes(tz, at) {
6116
+ let f = formats.get(tz);
6117
+ if (!f) formats.set(tz, f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric" }));
6118
+ const p = Object.fromEntries(f.formatToParts(new Date(at)).map((x) => [x.type, x.value]));
6119
+ const local = Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour), Number(p.minute));
6120
+ return Math.round((local - Math.floor(at / 6e4) * 6e4) / 6e4);
6121
+ }
6122
+ var name = (min) => {
6123
+ const s = min < 0 ? "-" : "+";
6124
+ const a = Math.abs(min);
6125
+ return `<${s}${String(Math.floor(a / 60)).padStart(2, "0")}${a % 60 ? String(a % 60).padStart(2, "0") : ""}>`;
6126
+ };
6127
+ var off = (min) => {
6128
+ const a = Math.abs(min);
6129
+ return `${min > 0 ? "-" : ""}${Math.floor(a / 60)}${a % 60 ? `:${String(a % 60).padStart(2, "0")}` : ""}`;
6130
+ };
6131
+ function rule(localMs) {
6132
+ const d = new Date(localMs);
6133
+ const day = d.getUTCDate();
6134
+ const days = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0)).getUTCDate();
6135
+ const week = day + 7 > days ? 5 : Math.ceil(day / 7);
6136
+ const mins = d.getUTCHours() * 60 + d.getUTCMinutes();
6137
+ return `M${d.getUTCMonth() + 1}.${week}.${d.getUTCDay()}${mins === 120 ? "" : `/${Math.floor(mins / 60)}${mins % 60 ? `:${String(mins % 60).padStart(2, "0")}` : ""}`}`;
6138
+ }
6139
+ function posixTz(tz = Intl.DateTimeFormat().resolvedOptions().timeZone, year = (/* @__PURE__ */ new Date()).getUTCFullYear()) {
6140
+ try {
6141
+ const start = Date.UTC(year, 0, 1);
6142
+ const changes = [];
6143
+ let prev = offsetMinutes(tz, start);
6144
+ const DAY = 864e5;
6145
+ for (let t2 = start + DAY; t2 <= Date.UTC(year + 1, 0, 1); t2 += DAY) {
6146
+ const o = offsetMinutes(tz, t2);
6147
+ if (o === prev) continue;
6148
+ let lo = t2 - DAY, hi = t2;
6149
+ while (hi - lo > 6e4) {
6150
+ const mid = Math.floor((lo + hi) / 12e4) * 6e4;
6151
+ if (offsetMinutes(tz, mid) === prev) lo = mid;
6152
+ else hi = mid;
6153
+ }
6154
+ changes.push({ at: hi, from: prev, to: o });
6155
+ prev = o;
6156
+ }
6157
+ if (changes.length !== 2) return `${name(prev)}${off(prev)}`;
6158
+ const on = changes.find((c) => c.to > c.from), offc = changes.find((c) => c.to < c.from);
6159
+ const std = on.from, dst = on.to;
6160
+ return `${name(std)}${off(std)}${name(dst)}${dst - std === 60 ? "" : off(dst)},${rule(on.at + std * 6e4)},${rule(offc.at + dst * 6e4)}`;
6161
+ } catch {
6162
+ return "UTC0";
6163
+ }
6164
+ }
5009
6165
 
5010
6166
  // packages/core/src/screen-runner.ts
5011
6167
  init_src();
@@ -5062,11 +6218,11 @@ var ALERT_ICONS = {
5062
6218
  mail: ["m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7", "M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"]
5063
6219
  };
5064
6220
  var paths2 = /* @__PURE__ */ new Map();
5065
- function iconPaths(name) {
5066
- const d = ALERT_ICONS[name];
6221
+ function iconPaths(name2) {
6222
+ const d = ALERT_ICONS[name2];
5067
6223
  if (!d) return null;
5068
- let p = paths2.get(name);
5069
- if (!p) paths2.set(name, p = d.map((x) => new Path2D(x)));
6224
+ let p = paths2.get(name2);
6225
+ if (!p) paths2.set(name2, p = d.map((x) => new Path2D(x)));
5070
6226
  return p;
5071
6227
  }
5072
6228
  function iconFor(a) {
@@ -5193,6 +6349,247 @@ function paintAlert(g, w, h, shown, o) {
5193
6349
  g.restore();
5194
6350
  }
5195
6351
 
6352
+ // packages/core/src/welcome.ts
6353
+ init_src();
6354
+ init_i18n();
6355
+ var BOOT_MS = 2400;
6356
+ var BOOT_WINDOW_MS = 6e4;
6357
+ var CARD_EVERY_MS = 10 * 6e4;
6358
+ var CARD_MS = 15e3;
6359
+ var FIRST_CARD_MS = 3e4;
6360
+ var BOOT_FPS = 15;
6361
+ function welcomeDue(cfg, s) {
6362
+ const pending2 = offersSetup(cfg);
6363
+ if (!s.booted) {
6364
+ if (s.sinceStartMs < BOOT_WINDOW_MS && (cfg.bootAnimation !== false || pending2)) return "boot";
6365
+ return pending2 ? "card" : null;
6366
+ }
6367
+ if (!pending2) return null;
6368
+ const slot = Math.floor(s.now / CARD_EVERY_MS);
6369
+ return slot !== s.cardSlot && s.now - slot * CARD_EVERY_MS < 6e4 ? "card" : null;
6370
+ }
6371
+ var TEXTS = {
6372
+ running: { en: "Kiosko is running", es: "Kiosko est\xE1 en marcha", de: "Kiosko l\xE4uft", "zh-Hant": "Kiosko \u5DF2\u5728\u57F7\u884C", "zh-Hans": "Kiosko \u5DF2\u5728\u8FD0\u884C" },
6373
+ open: { en: "Open the editor to set up this panel:", es: "Abre el editor para configurar este panel:", de: "\xD6ffne den Editor, um dieses Panel einzurichten:", "zh-Hant": "\u958B\u555F\u7DE8\u8F2F\u5668\u4F86\u8A2D\u5B9A\u9019\u584A\u9762\u677F\uFF1A", "zh-Hans": "\u6253\u5F00\u7F16\u8F91\u5668\u6765\u8BBE\u7F6E\u8FD9\u5757\u526F\u5C4F\uFF1A" },
6374
+ or: { en: "or go to", es: "o entra en", de: "oder \xF6ffne", "zh-Hant": "\u6216\u524D\u5F80", "zh-Hans": "\u6216\u8BBF\u95EE" },
6375
+ hint: { en: "This card goes away once the setup is done.", es: "Esta tarjeta se va cuando termines la configuraci\xF3n.", de: "Diese Karte verschwindet, sobald die Einrichtung fertig ist.", "zh-Hant": "\u5B8C\u6210\u8A2D\u5B9A\u5F8C\uFF0C\u9019\u5F35\u5361\u7247\u5C31\u6703\u6D88\u5931\u3002", "zh-Hans": "\u5B8C\u6210\u8BBE\u7F6E\u540E\uFF0C\u8FD9\u5F20\u5361\u7247\u5C31\u4F1A\u6D88\u5931\u3002" }
6376
+ };
6377
+ function welcomeTexts(locale) {
6378
+ return Object.fromEntries(Object.entries(TEXTS).map(([k, v]) => [k, localize(v, locale)]));
6379
+ }
6380
+ function editorUrl(cfg) {
6381
+ const host = !cfg.server.host || cfg.server.host === "0.0.0.0" || cfg.server.host === "::" ? "127.0.0.1" : cfg.server.host;
6382
+ return `http://${host.includes(":") ? `[${host}]` : host}:${cfg.server.port}`;
6383
+ }
6384
+ function cardUrl(listening, cfg) {
6385
+ return listening ?? editorUrl(cfg);
6386
+ }
6387
+ var clamp01 = (x) => Math.max(0, Math.min(1, x));
6388
+ var easeOut = (x) => 1 - (1 - clamp01(x)) ** 3;
6389
+ var easeBack = (x) => {
6390
+ const t2 = clamp01(x) - 1;
6391
+ return 1 + 2.2 * t2 ** 3 + 1.2 * t2 ** 2;
6392
+ };
6393
+ var TILES = [
6394
+ { x: 6, y: 6, w: 30, h: 22, grad: true, alpha: 1 },
6395
+ { x: 40, y: 6, w: 18, h: 22, grad: false, tone: 1, alpha: 0.55 },
6396
+ { x: 6, y: 32, w: 18, h: 26, grad: false, tone: 0, alpha: 0.55 },
6397
+ { x: 28, y: 32, w: 30, h: 26, grad: true, alpha: 0.85 }
6398
+ ];
6399
+ function brand(theme) {
6400
+ return [theme.colors.accent, theme.colors.info];
6401
+ }
6402
+ function paintMark(g, x, y, size, theme, t2 = 1, glint = -1) {
6403
+ const k = size / 64;
6404
+ const [c1, c2] = brand(theme);
6405
+ TILES.forEach((tile, i) => {
6406
+ const p = clamp01((t2 - i * 0.12) / 0.52);
6407
+ if (p <= 0) return;
6408
+ const s = 0.55 + 0.45 * easeBack(p);
6409
+ const cx = x + (tile.x + tile.w / 2) * k;
6410
+ const cy = y + (tile.y + tile.h / 2) * k;
6411
+ const dx = (tile.x + tile.w / 2 - 32) * k * 0.6 * (1 - easeOut(p));
6412
+ const dy = (tile.y + tile.h / 2 - 32) * k * 0.6 * (1 - easeOut(p));
6413
+ const w = tile.w * k * s;
6414
+ const h = tile.h * k * s;
6415
+ g.save();
6416
+ g.globalAlpha = tile.alpha * easeOut(p);
6417
+ if (tile.grad) {
6418
+ const gr = g.createLinearGradient(x, y, x + size, y + size);
6419
+ gr.addColorStop(0, c1);
6420
+ gr.addColorStop(1, c2);
6421
+ g.fillStyle = gr;
6422
+ } else g.fillStyle = "tone" in tile && tile.tone ? c2 : c1;
6423
+ g.beginPath();
6424
+ g.roundRect(cx + dx - w / 2, cy + dy - h / 2, w, h, 5 * k * s);
6425
+ g.fill();
6426
+ g.restore();
6427
+ });
6428
+ if (glint >= 0 && glint <= 1) {
6429
+ g.save();
6430
+ g.beginPath();
6431
+ for (const tile of TILES) g.roundRect(x + tile.x * k, y + tile.y * k, tile.w * k, tile.h * k, 5 * k);
6432
+ g.clip();
6433
+ const bx = x - size * 0.6 + glint * size * 2.2;
6434
+ const gr = g.createLinearGradient(bx, y, bx + size * 0.5, y + size);
6435
+ gr.addColorStop(0, "rgba(255,255,255,0)");
6436
+ gr.addColorStop(0.5, "rgba(255,255,255,0.45)");
6437
+ gr.addColorStop(1, "rgba(255,255,255,0)");
6438
+ g.fillStyle = gr;
6439
+ g.fillRect(x, y, size, size);
6440
+ g.restore();
6441
+ }
6442
+ }
6443
+ function paintBackground(g, w, h, theme, cx, cy, glow) {
6444
+ g.fillStyle = theme.colors.bg;
6445
+ g.fillRect(0, 0, w, h);
6446
+ if (glow <= 0) return;
6447
+ const r = Math.max(w, h) * 0.55;
6448
+ const gr = g.createRadialGradient(cx, cy, 0, cx, cy, r);
6449
+ const [c1] = brand(theme);
6450
+ gr.addColorStop(0, css(hex(c1), 0.16 * glow));
6451
+ gr.addColorStop(1, css(hex(c1), 0));
6452
+ g.fillStyle = gr;
6453
+ g.fillRect(0, 0, w, h);
6454
+ }
6455
+ function shapeOf(w, h) {
6456
+ const r = w / h;
6457
+ return r >= 1.6 ? "wide" : r <= 0.7 ? "tall" : "square";
6458
+ }
6459
+ function paintBoot(g, w, h, ms, look) {
6460
+ const { theme } = look;
6461
+ const shape = shapeOf(w, h);
6462
+ const bold2 = theme.fonts.sansBold;
6463
+ const word = "Kiosko";
6464
+ const mark = shape === "wide" ? Math.round(h * 0.5) : Math.round(Math.min(w * (shape === "tall" ? 0.62 : 0.42), h * 0.42));
6465
+ let size = Math.round(mark * (shape === "wide" ? 0.62 : 0.4));
6466
+ size = fitSize(g, word, shape === "wide" ? w * 0.5 : w * 0.86, { size, family: bold2 }, 10);
6467
+ const wordW = measureTracked(g, word, { size, family: bold2 });
6468
+ const gap = Math.round(mark * 0.22);
6469
+ const groupW = shape === "wide" ? mark + gap + wordW : Math.max(mark, wordW);
6470
+ const groupH = shape === "wide" ? mark : mark + gap + size;
6471
+ const gx = Math.round((w - groupW) / 2);
6472
+ const gy = Math.round((h - groupH) / 2);
6473
+ const mx = shape === "wide" ? gx : Math.round((w - mark) / 2);
6474
+ const fade = 1 - clamp01((ms - (BOOT_MS - 380)) / 380);
6475
+ paintBackground(g, w, h, theme, mx + mark / 2, gy + mark / 2, easeOut(ms / 900) * fade);
6476
+ g.save();
6477
+ g.globalAlpha = fade;
6478
+ paintMark(g, mx, gy, mark, theme, ms / 1e3, (ms - 1350) / 650);
6479
+ const p = easeOut((ms - 650) / 700);
6480
+ if (p > 0) {
6481
+ const wx = shape === "wide" ? gx + mark + gap : Math.round((w - wordW) / 2);
6482
+ const base3 = shape === "wide" ? gy + mark / 2 + size * 0.36 : gy + mark + gap + size * 0.82;
6483
+ g.save();
6484
+ g.beginPath();
6485
+ if (shape === "wide") g.rect(wx - 2, 0, (wordW + 4) * p, h);
6486
+ else g.rect(0, 0, w, h);
6487
+ g.clip();
6488
+ g.globalAlpha = fade * (shape === "wide" ? 1 : p);
6489
+ drawTracked(g, word, wx, base3 + (1 - p) * size * 0.25, { size, family: bold2, color: theme.colors.ink });
6490
+ g.restore();
6491
+ const u = easeOut((ms - 1150) / 600);
6492
+ if (u > 0) {
6493
+ const [c1, c2] = brand(theme);
6494
+ const gr = g.createLinearGradient(wx, 0, wx + wordW, 0);
6495
+ gr.addColorStop(0, c1);
6496
+ gr.addColorStop(1, c2);
6497
+ g.fillStyle = gr;
6498
+ const uh = Math.max(2, Math.round(size * 0.07));
6499
+ g.beginPath();
6500
+ g.roundRect(wx, base3 + size * 0.16, wordW * u, uh, uh / 2);
6501
+ g.fill();
6502
+ }
6503
+ }
6504
+ g.restore();
6505
+ }
6506
+ function paintCard(g, w, h, look) {
6507
+ const { theme } = look;
6508
+ const tx = welcomeTexts(look.locale);
6509
+ const shape = shapeOf(w, h);
6510
+ const pad = Math.round(Math.min(w, h) * 0.08);
6511
+ const mark = shape === "wide" ? Math.round(h * 0.42) : shape === "tall" ? Math.round(w * 0.5) : Math.round(Math.min(w * 0.3, h * 0.28));
6512
+ const gap = Math.round(pad * 0.8);
6513
+ const mx = shape === "wide" ? pad + Math.round(mark * 0.1) : Math.round((w - mark) / 2);
6514
+ const bx = shape === "wide" ? mx + mark + Math.round(mark * 0.35) : pad;
6515
+ const bw = w - bx - pad;
6516
+ const bh = shape === "wide" ? h - 2 * pad : h - 2 * pad - mark - gap;
6517
+ const bold2 = theme.fonts.sansBold;
6518
+ const sans = theme.fonts.sans;
6519
+ const mono = theme.fonts.monoBold;
6520
+ const center = shape !== "wide";
6521
+ const layout = (k2) => {
6522
+ const body2 = Math.max(9, Math.round(k2 * 0.5));
6523
+ const chip = Math.max(9, Math.round(k2 * 0.5));
6524
+ const hint = Math.max(8, Math.round(k2 * 0.34));
6525
+ const title = wrapLines(g, tx.running, bw, 2, { size: k2, family: bold2 });
6526
+ const open2 = wrapLines(g, tx.open, bw, 3, { size: body2, family: sans });
6527
+ const cmd2 = "kiosko editor";
6528
+ const cmdW = measureTracked(g, cmd2, { size: chip, family: mono }) + chip * 1.1;
6529
+ const orW = measureTracked(g, tx.or, { size: body2, family: sans });
6530
+ const urlW = measureTracked(g, look.url, { size: chip, family: mono });
6531
+ const oneLine2 = cmdW + body2 * 0.6 + orW + body2 * 0.6 + urlW <= bw;
6532
+ const hints = hint >= 10 ? wrapLines(g, tx.hint, bw, 2, { size: hint, family: sans }) : [];
6533
+ const lineH = (s) => Math.round(s * 1.3);
6534
+ const height = title.length * lineH(k2) + k2 * 0.25 + open2.length * lineH(body2) + body2 * 0.35 + (oneLine2 ? chip * 1.9 : chip * 1.9 * 2 + lineH(body2)) + hint * 0.6 + hints.length * lineH(hint);
6535
+ const fits = urlW <= bw && cmdW <= bw && title.length === 1;
6536
+ return { k: k2, body: body2, chip, hint, title, open: open2, cmd: cmd2, cmdW, orW, urlW, oneLine: oneLine2, hints, height, fits, lineH };
6537
+ };
6538
+ let k = Math.round(shape === "wide" ? h * 0.17 : shape === "tall" ? w * 0.12 : Math.min(w * 0.085, h * 0.11));
6539
+ let L = layout(k);
6540
+ while (k > 12 && (L.height > bh || !L.fits)) L = layout(--k);
6541
+ const my = shape === "wide" ? Math.round((h - mark) / 2) : Math.max(pad, Math.round((h - mark - gap - L.height) / 2));
6542
+ paintBackground(g, w, h, theme, mx + mark / 2, my + mark / 2, 1);
6543
+ paintMark(g, mx, my, mark, theme);
6544
+ let y = shape === "wide" ? pad + Math.max(0, Math.round((bh - L.height) / 2)) : my + mark + gap;
6545
+ const ax = center ? w / 2 : bx;
6546
+ const align = center ? "center" : "left";
6547
+ for (const line of L.title) {
6548
+ drawTracked(g, line, ax, y + L.k * 0.95, { size: L.k, family: bold2, color: theme.colors.ink, align });
6549
+ y += L.lineH(L.k);
6550
+ }
6551
+ y += L.k * 0.25;
6552
+ for (const line of L.open) {
6553
+ drawTracked(g, line, ax, y + L.body * 0.95, { size: L.body, family: sans, color: theme.colors.inkDim, align });
6554
+ y += L.lineH(L.body);
6555
+ }
6556
+ y += L.body * 0.35;
6557
+ const chipH = Math.round(L.chip * 1.6);
6558
+ const drawChip = (x, text3, cw) => {
6559
+ g.fillStyle = theme.colors.surface;
6560
+ g.strokeStyle = theme.colors.surfaceEdge;
6561
+ g.lineWidth = 1;
6562
+ g.beginPath();
6563
+ g.roundRect(x, y, cw, chipH, chipH / 3);
6564
+ g.fill();
6565
+ g.stroke();
6566
+ drawTracked(g, text3, x + cw / 2, y + chipH / 2 + L.chip * 0.36, { size: L.chip, family: mono, color: theme.colors.ink, align: "center" });
6567
+ };
6568
+ const drawUrl = (x) => drawTracked(g, look.url, x, y + chipH / 2 + L.chip * 0.36, { size: L.chip, family: mono, color: theme.colors.accent });
6569
+ if (L.oneLine) {
6570
+ const total = L.cmdW + L.body * 0.6 + L.orW + L.body * 0.6 + L.urlW;
6571
+ let x = center ? Math.round((w - total) / 2) : bx;
6572
+ drawChip(x, L.cmd, L.cmdW);
6573
+ x += L.cmdW + L.body * 0.6;
6574
+ drawTracked(g, tx.or, x, y + chipH / 2 + L.body * 0.36, { size: L.body, family: sans, color: theme.colors.inkDim });
6575
+ x += L.orW + L.body * 0.6;
6576
+ drawUrl(x);
6577
+ y += L.chip * 1.9;
6578
+ } else {
6579
+ drawChip(center ? Math.round((w - L.cmdW) / 2) : bx, L.cmd, L.cmdW);
6580
+ y += L.chip * 1.9;
6581
+ drawTracked(g, tx.or, ax, y + L.body * 0.95, { size: L.body, family: sans, color: theme.colors.inkDim, align });
6582
+ y += L.lineH(L.body);
6583
+ drawUrl(center ? Math.round((w - L.urlW) / 2) : bx);
6584
+ y += L.chip * 1.9;
6585
+ }
6586
+ y += L.hint * 0.6;
6587
+ for (const line of L.hints) {
6588
+ drawTracked(g, line, ax, y + L.hint * 0.95, { size: L.hint, family: sans, color: theme.colors.inkFaint, align });
6589
+ y += L.lineH(L.hint);
6590
+ }
6591
+ }
6592
+
5196
6593
  // packages/core/src/frame-stats.ts
5197
6594
  var FPS_WINDOW_MS = 5e3;
5198
6595
  var round = (ms) => Math.round(ms * 10) / 10;
@@ -5286,6 +6683,12 @@ var ScreenRunner = class {
5286
6683
  alertKey = null;
5287
6684
  /** Real fps, paint and encode times (see frame-stats.ts). */
5288
6685
  stats = new FrameStats();
6686
+ /** The start went by (the boot animation played, or wasn't due). */
6687
+ booted = false;
6688
+ /** The first run's card: the last slot it was shown in, and until when it stays. */
6689
+ cardSlot = -1;
6690
+ cardUntil = 0;
6691
+ cardKey = null;
5289
6692
  screen;
5290
6693
  rt;
5291
6694
  /** `device`: one already open for this screen (handed over by a thread that stopped). */
@@ -5295,7 +6698,7 @@ var ScreenRunner = class {
5295
6698
  this.deviceKey = JSON.stringify(screen.device);
5296
6699
  this.device = device ?? rt.openDevice(screen, (m) => rt.log(`screen:${screen.name}`, m));
5297
6700
  this.pinned = screen.pinnedPage ?? null;
5298
- this.scheduler = new AnimationScheduler(() => rt.rnd(), (type, why) => rt.log(type, `animation ignored: ${why}`));
6701
+ this.scheduler = new AnimationScheduler(() => rt.rnd(), (type, why2) => rt.log(type, `animation ignored: ${why2}`));
5299
6702
  }
5300
6703
  /** Encodes a frame within the screen's `maxBytes`, saying so in the log (at most every 10 min) when it had to shrink it. */
5301
6704
  async fit(c, kind, quality, screen, paintMs = 0) {
@@ -5368,6 +6771,7 @@ var ScreenRunner = class {
5368
6771
  const play = this.wantedPlay;
5369
6772
  this.wanted = null;
5370
6773
  this.wantedPlay = false;
6774
+ if (!this.off && !asked && await this.maybeWelcome(now)) return;
5371
6775
  if (!this.off && await this.maybeInterlude(now, asked ?? void 0, play)) return;
5372
6776
  const page = this.currentPage(now);
5373
6777
  if (page?.id !== this.page?.id) {
@@ -5413,7 +6817,7 @@ var ScreenRunner = class {
5413
6817
  log: this.rt.log,
5414
6818
  demo: this.rt.demoMode,
5415
6819
  cache: this.tiles,
5416
- rotate: screen.rotate
6820
+ rotate: paintTurn(screen)
5417
6821
  });
5418
6822
  canvas = result.canvas;
5419
6823
  this.animatable = result.animatable;
@@ -5424,7 +6828,8 @@ var ScreenRunner = class {
5424
6828
  this.rt.paintTime(t2.shown, type, t2.renderMs, now);
5425
6829
  }
5426
6830
  } else {
5427
- const swap = screen.rotate === 90 || screen.rotate === 270;
6831
+ const turn = paintTurn(screen);
6832
+ const swap = turn === 90 || turn === 270;
5428
6833
  canvas = CANVAS.createCanvas(swap ? screen.height : screen.width, swap ? screen.width : screen.height);
5429
6834
  this.animatable = [];
5430
6835
  this.nextAt = now + 6e4;
@@ -5440,7 +6845,7 @@ var ScreenRunner = class {
5440
6845
  }
5441
6846
  const kind = encodeFor(screen.device, screen.jpegQuality);
5442
6847
  const out = await this.fit(canvas, kind, screen.jpegQuality, screen, performance.now() - t0);
5443
- this.lastInfo = { screenId: screen.id, pageId: page?.id ?? null, at: now, image: lazyJpeg(canvas, screen.rotate), tiles: result?.tiles ?? [], interlude: null, sleeping };
6848
+ this.lastInfo = { screenId: screen.id, pageId: page?.id ?? null, at: now, image: lazyJpeg(canvas, paintTurn(screen)), tiles: result?.tiles ?? [], interlude: null, sleeping };
5444
6849
  this.rt.frame(this.lastInfo);
5445
6850
  if (this.last?.equals(out)) return;
5446
6851
  this.last = out;
@@ -5464,16 +6869,105 @@ var ScreenRunner = class {
5464
6869
  this.alertKey = key;
5465
6870
  const t0 = performance.now();
5466
6871
  registerFonts();
5467
- setFontLocale(resolveLocale(cfg));
5468
- src_exports.setMinCjkPx(minPx);
6872
+ setFontLocale(resolveLocale(cfg));
6873
+ src_exports.setMinCjkPx(minPx);
6874
+ const canvas = CANVAS.createCanvas(screen.width, screen.height);
6875
+ paintAlert(canvas.getContext("2d"), screen.width, screen.height, shown, { intensity, fonts: this.rt.theme().fonts, minPx, sinceText, shift });
6876
+ const kind = encodeFor(screen.device, screen.jpegQuality || 85);
6877
+ const turned = rotateCanvas(canvas, paintTurn(screen));
6878
+ const out = await this.fit(turned, kind, screen.jpegQuality || 85, screen, performance.now() - t0);
6879
+ this.lastInfo = { screenId: screen.id, pageId: this.page?.id ?? null, at: now, image: lazyJpeg(canvas), tiles: [], interlude: null, alert: a.id, sleeping: false };
6880
+ this.rt.frame(this.lastInfo);
6881
+ if (this.last?.equals(out)) return;
6882
+ this.last = out;
6883
+ await this.send(out);
6884
+ }
6885
+ /**
6886
+ * The boot animation and the first run's card (welcome.ts), before
6887
+ * anything else but an alert. True while one has the screen.
6888
+ */
6889
+ async maybeWelcome(now) {
6890
+ if (!this.rt.welcome || this.rt.demoMode) return false;
6891
+ const cfg = this.rt.config;
6892
+ if (this.cardUntil) {
6893
+ if (now < this.cardUntil && offersSetup(cfg)) {
6894
+ await this.paintWelcomeCard(now);
6895
+ return true;
6896
+ }
6897
+ this.cardUntil = 0;
6898
+ this.cardKey = null;
6899
+ this.last = null;
6900
+ this.dirty = true;
6901
+ return false;
6902
+ }
6903
+ const due = welcomeDue(cfg, { sinceStartMs: now - this.rt.startedAt, now, booted: this.booted, cardSlot: this.cardSlot });
6904
+ const first = !this.booted;
6905
+ this.booted = true;
6906
+ if (!due) return false;
6907
+ if (due === "boot") {
6908
+ await this.playBoot();
6909
+ if (!offersSetup(cfg)) {
6910
+ this.last = null;
6911
+ this.dirty = true;
6912
+ return true;
6913
+ }
6914
+ }
6915
+ this.cardSlot = Math.floor(Date.now() / CARD_EVERY_MS);
6916
+ this.cardUntil = Date.now() + (first ? FIRST_CARD_MS : CARD_MS);
6917
+ await this.paintWelcomeCard(Date.now());
6918
+ return true;
6919
+ }
6920
+ welcomeLook() {
6921
+ const cfg = this.rt.config;
6922
+ return { theme: this.rt.theme(), locale: resolveLocale(cfg), url: cardUrl(this.rt.editorUrl, cfg) };
6923
+ }
6924
+ /** The boot animation, at the screen's fps (at most BOOT_FPS): a slower panel plays fewer frames, never longer. */
6925
+ async playBoot() {
6926
+ const { screen } = this;
6927
+ const look = this.welcomeLook();
6928
+ registerFonts();
6929
+ setFontLocale(look.locale);
6930
+ const fps = Math.max(1, Math.min(BOOT_FPS, screen.maxFps));
6931
+ const frames = Math.max(1, Math.round(BOOT_MS / 1e3 * fps));
6932
+ const kind = encodeFor(screen.device, screen.jpegQuality || 85);
6933
+ const canvas = CANVAS.createCanvas(screen.width, screen.height);
6934
+ const g = canvas.getContext("2d");
6935
+ const start = Date.now();
6936
+ for (let i = 0; i < frames && !this.alert && !this.closed; i++) {
6937
+ const ms = Math.min(BOOT_MS, Date.now() - start);
6938
+ if (ms >= BOOT_MS) break;
6939
+ const t0 = performance.now();
6940
+ g.save();
6941
+ paintBoot(g, screen.width, screen.height, ms, look);
6942
+ g.restore();
6943
+ const out = await this.fit(rotateCanvas(canvas, paintTurn(screen)), kind, screen.jpegQuality || 85, screen, performance.now() - t0);
6944
+ await this.send(out);
6945
+ if (i % 4 === 0) {
6946
+ const snap = CANVAS.createCanvas(canvas.width, canvas.height);
6947
+ snap.getContext("2d").drawImage(canvas, 0, 0);
6948
+ this.lastInfo = { screenId: screen.id, pageId: this.page?.id ?? null, at: Date.now(), image: lazyJpeg(snap), tiles: [], interlude: "kiosko/boot", sleeping: false };
6949
+ this.rt.frame(this.lastInfo);
6950
+ }
6951
+ const wait = start + (i + 1) * 1e3 / fps - Date.now();
6952
+ await new Promise((r) => wait > 0 ? setTimeout(r, wait) : setImmediate(r));
6953
+ }
6954
+ }
6955
+ /** The first run's card: a still frame, sent again only when it changes (the theme, the language, the address). */
6956
+ async paintWelcomeCard(now) {
6957
+ const { screen } = this;
6958
+ const look = this.welcomeLook();
6959
+ const key = JSON.stringify([look.theme.id, look.locale, look.url, screen.width, screen.height, screen.rotate]);
6960
+ if (key === this.cardKey) return;
6961
+ this.cardKey = key;
6962
+ const t0 = performance.now();
6963
+ registerFonts();
6964
+ setFontLocale(look.locale);
5469
6965
  const canvas = CANVAS.createCanvas(screen.width, screen.height);
5470
- paintAlert(canvas.getContext("2d"), screen.width, screen.height, shown, { intensity, fonts: this.rt.theme().fonts, minPx, sinceText, shift });
6966
+ paintCard(canvas.getContext("2d"), screen.width, screen.height, look);
5471
6967
  const kind = encodeFor(screen.device, screen.jpegQuality || 85);
5472
- const turned = rotateCanvas(canvas, screen.rotate);
5473
- const out = await this.fit(turned, kind, screen.jpegQuality || 85, screen, performance.now() - t0);
5474
- this.lastInfo = { screenId: screen.id, pageId: this.page?.id ?? null, at: now, image: lazyJpeg(canvas), tiles: [], interlude: null, alert: a.id, sleeping: false };
6968
+ const out = await this.fit(rotateCanvas(canvas, paintTurn(screen)), kind, screen.jpegQuality || 85, screen, performance.now() - t0);
6969
+ this.lastInfo = { screenId: screen.id, pageId: this.page?.id ?? null, at: now, image: lazyJpeg(canvas), tiles: [], interlude: "kiosko/welcome", sleeping: false };
5475
6970
  this.rt.frame(this.lastInfo);
5476
- if (this.last?.equals(out)) return;
5477
6971
  this.last = out;
5478
6972
  await this.send(out);
5479
6973
  }
@@ -5547,7 +7041,7 @@ var ScreenRunner = class {
5547
7041
  } finally {
5548
7042
  g.restore();
5549
7043
  }
5550
- const turned = rotateCanvas(canvas, this.screen.rotate);
7044
+ const turned = rotateCanvas(canvas, paintTurn(this.screen));
5551
7045
  const out = await this.fit(turned, kind, this.screen.jpegQuality || 85, this.screen, performance.now() - t0);
5552
7046
  await this.send(out);
5553
7047
  if (i % 3 === 0) {
@@ -5645,7 +7139,7 @@ var ScreenRunner = class {
5645
7139
  demo: this.rt.demoMode,
5646
7140
  cache: this.tiles,
5647
7141
  animate,
5648
- rotate: screen.rotate
7142
+ rotate: paintTurn(screen)
5649
7143
  });
5650
7144
  sent.push({ out: this.fit(result.canvas, kind, screen.jpegQuality || 85, screen, performance.now() - t02), snap: s % 3 === 1 ? result.canvas : null });
5651
7145
  await new Promise((r) => setImmediate(r));
@@ -5662,7 +7156,7 @@ var ScreenRunner = class {
5662
7156
  await this.send(outs[k]);
5663
7157
  const snap = sent[k].snap;
5664
7158
  if (snap) {
5665
- this.lastInfo = { screenId: screen.id, pageId: page.id, at: Date.now(), image: lazyJpeg(snap, screen.rotate), tiles: [], interlude: null, animation: items.map((x) => x.animatable.type).join(", "), sleeping: false };
7159
+ this.lastInfo = { screenId: screen.id, pageId: page.id, at: Date.now(), image: lazyJpeg(snap, paintTurn(screen)), tiles: [], interlude: null, animation: items.map((x) => x.animatable.type).join(", "), sleeping: false };
5666
7160
  this.rt.frame(this.lastInfo);
5667
7161
  }
5668
7162
  if (hold && k === holdAt) {
@@ -5706,9 +7200,9 @@ var ScreenRunner = class {
5706
7200
  this.pinned = pageId;
5707
7201
  this.dirty = true;
5708
7202
  }
5709
- setOff(off) {
5710
- this.off = off;
5711
- if (off) this.stopInterlude();
7203
+ setOff(off2) {
7204
+ this.off = off2;
7205
+ if (off2) this.stopInterlude();
5712
7206
  this.dirty = true;
5713
7207
  }
5714
7208
  /** A button from the Play page, for the interlude being played; false when none is. */
@@ -5763,8 +7257,8 @@ var Unclonable = class extends Error {
5763
7257
  };
5764
7258
  function what(v) {
5765
7259
  if (typeof v === "function") return "a function";
5766
- const name = Object.getPrototypeOf(v)?.constructor?.name;
5767
- return name ? `a ${name} (an object of a class)` : "an object of a class";
7260
+ const name2 = Object.getPrototypeOf(v)?.constructor?.name;
7261
+ return name2 ? `a ${name2} (an object of a class)` : "an object of a class";
5768
7262
  }
5769
7263
  var CLONED_AS_IS = [Date, RegExp, ArrayBuffer, Error, DataView];
5770
7264
  function isCanvas(v) {
@@ -5894,6 +7388,9 @@ var ThreadRunner = class {
5894
7388
  demo: this.owner.demoMode,
5895
7389
  maxConcurrent: this.owner.maxConcurrent,
5896
7390
  playIdleMs: this.owner.playIdleMs,
7391
+ welcome: this.owner.welcome,
7392
+ startedAt: this.owner.startedAt,
7393
+ ...this.owner.editorUrl ? { editorUrl: this.owner.editorUrl } : {},
5897
7394
  pinned: this.pinned,
5898
7395
  off: this.off
5899
7396
  };
@@ -6058,10 +7555,10 @@ var ThreadRunner = class {
6058
7555
  this.pinned = pageId;
6059
7556
  this.post({ t: "pin", page: pageId });
6060
7557
  }
6061
- setOff(off) {
6062
- this.off = off;
6063
- if (off) this.state = { ...this.state, interlude: null };
6064
- this.post({ t: "off", off });
7558
+ setOff(off2) {
7559
+ this.off = off2;
7560
+ if (off2) this.state = { ...this.state, interlude: null };
7561
+ this.post({ t: "off", off: off2 });
6065
7562
  }
6066
7563
  async playNow(slotId, play = false) {
6067
7564
  if (this.off || this.alert) return;
@@ -6121,7 +7618,7 @@ var TEST_ALERT_TEXT = {
6121
7618
  "zh-Hant": "\u9019\u662F\u8B66\u5831\u5728\u300C{screen}\u300D\u4E0A\u7684\u6A23\u5B50\u3002\u5F9E\u4F60\u7684\u5EA7\u4F4D\u770B\u5F97\u6E05\u695A\u55CE\uFF1F",
6122
7619
  "zh-Hans": "\u8FD9\u662F\u8B66\u62A5\u5728\u201C{screen}\u201D\u4E0A\u7684\u6837\u5B50\u3002\u4ECE\u4F60\u7684\u5EA7\u4F4D\u770B\u5F97\u6E05\u5417\uFF1F"
6123
7620
  };
6124
- var Runtime = class extends EventEmitter {
7621
+ var Runtime = class extends EventEmitter2 {
6125
7622
  config;
6126
7623
  hub;
6127
7624
  fetches;
@@ -6159,10 +7656,18 @@ var Runtime = class extends EventEmitter {
6159
7656
  * For trying Kiosko without any setup, screenshots and kiosks at fairs.
6160
7657
  */
6161
7658
  demoMode;
7659
+ /** The boot animation and the first run's card on the panels (welcome.ts): the server's `start` asks for them; tests and the browser demo don't. */
7660
+ welcome;
7661
+ /** Where the editor really listens (`kiosko start` with its --host/--port), for the first run's card; else the config's. */
7662
+ editorUrl;
7663
+ /** When this runtime was made: the boot animation plays only soon after. */
7664
+ startedAt = Date.now();
6162
7665
  constructor(registry2, config2, o = {}) {
6163
7666
  super();
6164
7667
  this.registry = registry2;
6165
7668
  this.demoMode = !!o.demo;
7669
+ this.welcome = !!o.welcome && !o.demo;
7670
+ this.editorUrl = o.editorUrl;
6166
7671
  this.threadEntry = o.threadEntry;
6167
7672
  this.setMaxListeners(100);
6168
7673
  this.config = config2;
@@ -6202,7 +7707,7 @@ var Runtime = class extends EventEmitter {
6202
7707
  this.refreshWanted();
6203
7708
  }
6204
7709
  openDevice(screen, log) {
6205
- return openDevice(screen.device, log, screen.rotate);
7710
+ return openDevice(screen.device, log, screen.rotate, { settings: () => ({ lang: resolveLocale(this.config).slice(0, 5), tz: posixTz() }) });
6206
7711
  }
6207
7712
  onData(change) {
6208
7713
  this.alertsDirty = true;
@@ -6276,6 +7781,7 @@ var Runtime = class extends EventEmitter {
6276
7781
  this.runners.get(s.id)?.reconfigure(s);
6277
7782
  }
6278
7783
  this.placeRunners();
7784
+ for (const s of config2.screens) this.runners.get(s.id)?.device.setRotation?.(s.rotate);
6279
7785
  this.refreshWanted();
6280
7786
  this.emit("config", config2);
6281
7787
  }
@@ -6312,6 +7818,10 @@ var Runtime = class extends EventEmitter {
6312
7818
  }
6313
7819
  return r;
6314
7820
  }
7821
+ /** The device a screen sends to now (its remote screen, for pairing, updates, logs). */
7822
+ deviceOf(screenId) {
7823
+ return this.runners.get(screenId)?.device;
7824
+ }
6315
7825
  threadFailed(screenId, reason) {
6316
7826
  const s = this.config.screens.find((x) => x.id === screenId);
6317
7827
  const r = this.runners.get(screenId);
@@ -6360,11 +7870,11 @@ var Runtime = class extends EventEmitter {
6360
7870
  this.runners.get(screenId)?.stopInterlude();
6361
7871
  }
6362
7872
  /** Switches a screen's picture off (black) or back on, until the next restart. */
6363
- setOff(screenId, off) {
7873
+ setOff(screenId, off2) {
6364
7874
  const r = this.runners.get(screenId);
6365
- if (!r || r.off === off) return;
6366
- r.setOff(off);
6367
- this.emit("screen", { screenId, off });
7875
+ if (!r || r.off === off2) return;
7876
+ r.setOff(off2);
7877
+ this.emit("screen", { screenId, off: off2 });
6368
7878
  }
6369
7879
  refreshWidget(instanceId) {
6370
7880
  this.fetches.refresh(instanceId);
@@ -6414,7 +7924,11 @@ var Runtime = class extends EventEmitter {
6414
7924
  refreshAlerts(now = Date.now()) {
6415
7925
  this.alerts.prune(now);
6416
7926
  const list2 = this.alerts.list(now);
6417
- for (const r of this.runners.values()) r.setAlert(r.screen.enabled ? this.alerts.forScreen(r.screen, now, r.off) : null, now);
7927
+ for (const r of this.runners.values()) {
7928
+ const shown = r.screen.enabled ? this.alerts.forScreen(r.screen, now, r.off) : null;
7929
+ r.setAlert(shown, now);
7930
+ r.device.setLed?.(...ledFor(shown?.top.level ?? null));
7931
+ }
6418
7932
  const sig = JSON.stringify(list2);
6419
7933
  if (sig === this.alertsSig) return;
6420
7934
  this.alertsSig = sig;
@@ -6425,9 +7939,9 @@ var Runtime = class extends EventEmitter {
6425
7939
  return this.alerts.list(now);
6426
7940
  }
6427
7941
  /** An alert from outside (`POST /api/alerts`); throws `AlertError` if it is not one. */
6428
- postAlert(raw) {
7942
+ postAlert(raw2) {
6429
7943
  const now = Date.now();
6430
- const a = this.alerts.post(raw, now, resolveLocale(this.config), this.config.screens.map((s) => s.id));
7944
+ const a = this.alerts.post(raw2, now, resolveLocale(this.config), this.config.screens.map((s) => s.id));
6431
7945
  this.log("alerts", `${a.level}: ${a.title} (${a.id})`);
6432
7946
  this.refreshAlerts(now);
6433
7947
  return a;
@@ -6742,14 +8256,14 @@ function installSdkResolver() {
6742
8256
  if (installed) return;
6743
8257
  installed = true;
6744
8258
  const urls = /* @__PURE__ */ new Map();
6745
- for (const name of SHARED) {
6746
- const local = BUNDLED[name] ? join5(import.meta.dirname, BUNDLED[name]) : null;
8259
+ for (const name2 of SHARED) {
8260
+ const local = BUNDLED[name2] ? join5(import.meta.dirname, BUNDLED[name2]) : null;
6747
8261
  if (local && existsSync5(local)) {
6748
- urls.set(name, pathToFileURL(local).href);
8262
+ urls.set(name2, pathToFileURL(local).href);
6749
8263
  continue;
6750
8264
  }
6751
8265
  try {
6752
- urls.set(name, import.meta.resolve(name));
8266
+ urls.set(name2, import.meta.resolve(name2));
6753
8267
  } catch {
6754
8268
  }
6755
8269
  }
@@ -6791,8 +8305,8 @@ var Registry = class {
6791
8305
  this.problems.push({ origin, message: `invalid plugin id ${JSON.stringify(def?.id)}` });
6792
8306
  return;
6793
8307
  }
6794
- const why = incompatibility(def);
6795
- if (why) return this.refuse({ id: def.id, version: def.version, origin, reason: why });
8308
+ const why2 = incompatibility(def);
8309
+ if (why2) return this.refuse({ id: def.id, version: def.version, origin, reason: why2 });
6796
8310
  if (this.plugins.has(def.id)) {
6797
8311
  this.problems.push({ origin, message: `plugin "${def.id}" already loaded from ${this.plugins.get(def.id).origin}` });
6798
8312
  return;
@@ -6915,16 +8429,16 @@ var Registry = class {
6915
8429
  }
6916
8430
  }
6917
8431
  const candidates = [];
6918
- for (const name of readdirSync3(dir)) {
6919
- if (name === "node_modules" || name.startsWith(".")) continue;
6920
- candidates.push(join6(dir, name));
8432
+ for (const name2 of readdirSync3(dir)) {
8433
+ if (name2 === "node_modules" || name2.startsWith(".")) continue;
8434
+ candidates.push(join6(dir, name2));
6921
8435
  }
6922
8436
  const nm = join6(dir, "node_modules");
6923
8437
  if (existsSync6(nm)) {
6924
- for (const name of readdirSync3(nm)) {
6925
- if (name.startsWith("@")) {
6926
- for (const sub of readdirSync3(join6(nm, name))) if (sub.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name, sub));
6927
- } else if (name.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name));
8438
+ for (const name2 of readdirSync3(nm)) {
8439
+ if (name2.startsWith("@")) {
8440
+ for (const sub of readdirSync3(join6(nm, name2))) if (sub.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name2, sub));
8441
+ } else if (name2.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name2));
6928
8442
  }
6929
8443
  }
6930
8444
  for (const folder of candidates) await this.loadFolder(folder);
@@ -6940,8 +8454,8 @@ var Registry = class {
6940
8454
  if (existsSync6(pkgPath)) {
6941
8455
  const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
6942
8456
  const meta = packageMeta(pkg);
6943
- const why = incompatibility(meta);
6944
- if (why) return this.refuse({ id: meta.id, version: meta.version, origin: folder, reason: why });
8457
+ const why2 = incompatibility(meta);
8458
+ if (why2) return this.refuse({ id: meta.id, version: meta.version, origin: folder, reason: why2 });
6945
8459
  const rel = pkg.kiosko?.plugin ?? pkg.main;
6946
8460
  if (rel) entry = join6(folder, rel);
6947
8461
  }
@@ -6956,15 +8470,15 @@ var Registry = class {
6956
8470
  }
6957
8471
  async loadEntry(entry, origin, version) {
6958
8472
  const url2 = pathToFileURL2(entry).href + (version ? `?v=${version}` : "");
6959
- const mod = await import(url2);
6960
- if (!mod.default) {
8473
+ const mod2 = await import(url2);
8474
+ if (!mod2.default) {
6961
8475
  this.problems.push({ origin, message: "the module has no default export (use `export default definePlugin({...})`)" });
6962
8476
  return void 0;
6963
8477
  }
6964
8478
  const before = this.plugins.size;
6965
- this.add(mod.default, origin, url2);
6966
- if (this.plugins.size > before) this.entries.set(mod.default.id, { entry, origin });
6967
- return mod.default;
8479
+ this.add(mod2.default, origin, url2);
8480
+ if (this.plugins.size > before) this.entries.set(mod2.default.id, { entry, origin });
8481
+ return mod2.default;
6968
8482
  }
6969
8483
  /**
6970
8484
  * The values a source offers for an option (see `SourceDefinition.choices`),
@@ -7142,34 +8656,34 @@ function* fieldsOf(f, prefix = "") {
7142
8656
  }
7143
8657
  }
7144
8658
  var last = (path) => path.split(/[.[\]]+/).filter(Boolean).pop() ?? path;
7145
- function lintOptions(where, f, kind) {
8659
+ function lintOptions(where2, f, kind) {
7146
8660
  const out = [];
7147
- const warn = (path, message) => out.push({ level: "warn", where: `${where} options.${path}`, message });
7148
- const err = (path, message) => out.push({ level: "error", where: `${where} options.${path}`, message });
8661
+ const warn = (path, message) => out.push({ level: "warn", where: `${where2} options.${path}`, message });
8662
+ const err = (path, message) => out.push({ level: "error", where: `${where2} options.${path}`, message });
7149
8663
  const names = new Set([...fieldsOf(f)].map(([p]) => p));
7150
8664
  for (const [path, x] of fieldsOf(f)) {
7151
- const name = last(path);
7152
- if (x.kind === "number" && x.unit === "ms" && !/Ms$/.test(name)) warn(path, "a duration: name it \u2026Ms (rotateMs, maxAgeMs)");
7153
- if (x.kind === "number" && /Ms$/.test(name) && x.unit !== "ms") warn(path, "named \u2026Ms but not a duration: use t.duration()");
7154
- if (x.kind === "number" && (/(Minutes|Hours|Secs|Seconds)$/.test(name) || /Mins?$/.test(name) && (!x.unit || x.unit === "min"))) warn(path, "durations are milliseconds with t.duration() and a name ending in Ms");
7155
- if (/(Crit|Critical)$/.test(name)) warn(path, "thresholds are \u2026Warn (amber) and \u2026Alert (red), never \u2026Crit");
7156
- if (/Warn$/.test(name) && !names.has(path.replace(/Warn$/, "Alert"))) warn(path, `thresholds come in pairs: add ${name.replace(/Warn$/, "Alert")}`);
7157
- if (/Alert$/.test(name) && !names.has(path.replace(/Alert$/, "Warn"))) warn(path, `thresholds come in pairs: add ${name.replace(/Alert$/, "Warn")}`);
8665
+ const name2 = last(path);
8666
+ if (x.kind === "number" && x.unit === "ms" && !/Ms$/.test(name2)) warn(path, "a duration: name it \u2026Ms (rotateMs, maxAgeMs)");
8667
+ if (x.kind === "number" && /Ms$/.test(name2) && x.unit !== "ms") warn(path, "named \u2026Ms but not a duration: use t.duration()");
8668
+ if (x.kind === "number" && (/(Minutes|Hours|Secs|Seconds)$/.test(name2) || /Mins?$/.test(name2) && (!x.unit || x.unit === "min"))) warn(path, "durations are milliseconds with t.duration() and a name ending in Ms");
8669
+ if (/(Crit|Critical)$/.test(name2)) warn(path, "thresholds are \u2026Warn (amber) and \u2026Alert (red), never \u2026Crit");
8670
+ if (/Warn$/.test(name2) && !names.has(path.replace(/Warn$/, "Alert"))) warn(path, `thresholds come in pairs: add ${name2.replace(/Warn$/, "Alert")}`);
8671
+ if (/Alert$/.test(name2) && !names.has(path.replace(/Alert$/, "Warn"))) warn(path, `thresholds come in pairs: add ${name2.replace(/Alert$/, "Warn")}`);
7158
8672
  if (x.kind === "number" && x.unit === "%" && (!x.integer || x.max !== void 0 && x.max > 100 || x.max !== void 0 && x.max <= 1)) warn(path, 'percentages are integers 0\u2013100: t.integer({ min: 0, max: 100, unit: "%" })');
7159
8673
  if (x.kind === "number" && x.unit === "\xB0C" && !x.integer) warn(path, "temperatures are integer \xB0C");
7160
- if (x.kind === "boolean" && /Only$/.test(name)) warn(path, "no \u2026Only suffix: only<Condition> (onlyLatest)");
7161
- if (x.kind === "boolean" && ["seconds", "moon", "cores", "date", "title"].includes(name)) warn(path, `a part shown or hidden is show<Part>: show${name[0].toUpperCase()}${name.slice(1)}`);
7162
- if (name === "takeOver") err(path, "takeOver is the instance's switch, not an option: declare `takeOver` on the definition");
7163
- if (name === "hideWhenEmpty") err(path, "hideWhenEmpty is the instance's switch: declare `empty(ctx)` (and `hideWhenEmpty` on the definition)");
7164
- if (kind === "source" && (name === "intervalMs" || name === "timeoutMs") && !path.includes(".")) err(path, "refresh and timeout are not options: declare intervalMs / timeoutMs on the source");
7165
- if (kind === "source" && name === "background" && !path.includes(".")) err(path, "running with no widget is not an option: declare `background: true` on the source, and Kiosko gives the user the switch");
7166
- if (name === "max" || name === "count") warn(path, "a cap is max<Things> (maxProcesses); a list length is `rows` through listOptions()");
7167
- if ((name === "latitude" || name === "longitude") && !(x.kind === "number" && x.advanced)) warn(path, "use ctx.location, with locationOptions() as an advanced override");
8674
+ if (x.kind === "boolean" && /Only$/.test(name2)) warn(path, "no \u2026Only suffix: only<Condition> (onlyLatest)");
8675
+ if (x.kind === "boolean" && ["seconds", "moon", "cores", "date", "title"].includes(name2)) warn(path, `a part shown or hidden is show<Part>: show${name2[0].toUpperCase()}${name2.slice(1)}`);
8676
+ if (name2 === "takeOver") err(path, "takeOver is the instance's switch, not an option: declare `takeOver` on the definition");
8677
+ if (name2 === "hideWhenEmpty") err(path, "hideWhenEmpty is the instance's switch: declare `empty(ctx)` (and `hideWhenEmpty` on the definition)");
8678
+ if (kind === "source" && (name2 === "intervalMs" || name2 === "timeoutMs") && !path.includes(".")) err(path, "refresh and timeout are not options: declare intervalMs / timeoutMs on the source");
8679
+ if (kind === "source" && name2 === "background" && !path.includes(".")) err(path, "running with no widget is not an option: declare `background: true` on the source, and Kiosko gives the user the switch");
8680
+ if (name2 === "max" || name2 === "count") warn(path, "a cap is max<Things> (maxProcesses); a list length is `rows` through listOptions()");
8681
+ if ((name2 === "latitude" || name2 === "longitude") && !(x.kind === "number" && x.advanced)) warn(path, "use ctx.location, with locationOptions() as an advanced override");
7168
8682
  if (x.kind === "string") {
7169
- const looks = x.format === "url" || x.format === "path" || /^(url|host|endpoint|command|cmd|bin|path|dir|file|ssh)$/i.test(name) || /(Url|Host|Path|Dir|Command)$/.test(name);
8683
+ const looks = x.format === "url" || x.format === "path" || /^(url|host|endpoint|command|cmd|bin|path|dir|file|ssh)$/i.test(name2) || /(Url|Host|Path|Dir|Command)$/.test(name2);
7170
8684
  if (looks && !x.risk && !x.secret) warn(path, "its value contacts a host, runs a program or reads a path: mark it with `risk`");
7171
8685
  }
7172
- if (kind === "widget" && x.kind === "list" && x.item.kind === "string" && !x.filter && /^(repos|projects|calendars|servers|people|outlets|entities|gpus|branches|users)$/.test(name)) warn(path, "a list of names to show is a filter: t.filter() with matchFilter");
8686
+ if (kind === "widget" && x.kind === "list" && x.item.kind === "string" && !x.filter && /^(repos|projects|calendars|servers|people|outlets|entities|gpus|branches|users)$/.test(name2)) warn(path, "a list of names to show is a filter: t.filter() with matchFilter");
7173
8687
  }
7174
8688
  return out;
7175
8689
  }
@@ -7189,53 +8703,53 @@ function knownLanguage(tag) {
7189
8703
  var bare = (x) => ({ ...x, options: void 0 });
7190
8704
  function lintPlugin(def) {
7191
8705
  const out = [];
7192
- const add = (level, where, message) => out.push({ level, where, message });
7193
- if (!ID2.test(def.id ?? "")) add("error", "plugin", `id ${JSON.stringify(def.id)}: lowercase letters, digits and dashes`);
7194
- if (!/^\d+\.\d+\.\d+/.test(def.version ?? "")) add("error", "plugin", `version ${JSON.stringify(def.version)} is not semver`);
7195
- if (!def.sdk) add("warn", "plugin", 'say which plugin API it is written for: `sdk: "^0.2.0"` (and `kiosko.sdk` in package.json, so an incompatible Kiosko never runs it)');
8706
+ const add2 = (level, where2, message) => out.push({ level, where: where2, message });
8707
+ if (!ID2.test(def.id ?? "")) add2("error", "plugin", `id ${JSON.stringify(def.id)}: lowercase letters, digits and dashes`);
8708
+ if (!/^\d+\.\d+\.\d+/.test(def.version ?? "")) add2("error", "plugin", `version ${JSON.stringify(def.version)} is not semver`);
8709
+ if (!def.sdk) add2("warn", "plugin", 'say which plugin API it is written for: `sdk: "^0.2.0"` (and `kiosko.sdk` in package.json, so an incompatible Kiosko never runs it)');
7196
8710
  const reaches = (def.sources ?? []).length > 0 || (def.widgets ?? []).some((w) => w.fetch);
7197
- if (reaches && !def.permissions) add("warn", "plugin", "it reads data: declare `permissions` (hosts, programs, files, devices) so people know before installing");
7198
- if (!def.description) add("warn", "plugin", "a description, for the Plugins page and the store");
8711
+ if (reaches && !def.permissions) add2("warn", "plugin", "it reads data: declare `permissions` (hosts, programs, files, devices) so people know before installing");
8712
+ if (!def.description) add2("warn", "plugin", "a description, for the Plugins page and the store");
7199
8713
  if (def.license) {
7200
8714
  try {
7201
8715
  const lic = parseLicense(def.license);
7202
- for (const f of lic.fix) add("warn", "plugin", `license: write "${f.from}" as "${f.to}" (SPDX identifiers are case-sensitive)`);
7203
- for (const u of lic.unknown) add("warn", "plugin", `license: "${u}" is not an SPDX identifier Kiosko knows (https://spdx.org/licenses/); the store lists it as "other"`);
8716
+ for (const f of lic.fix) add2("warn", "plugin", `license: write "${f.from}" as "${f.to}" (SPDX identifiers are case-sensitive)`);
8717
+ for (const u of lic.unknown) add2("warn", "plugin", `license: "${u}" is not an SPDX identifier Kiosko knows (https://spdx.org/licenses/); the store lists it as "other"`);
7204
8718
  } catch (err) {
7205
- add("error", "plugin", `license ${JSON.stringify(def.license)}: ${err.message}`);
8719
+ add2("error", "plugin", `license ${JSON.stringify(def.license)}: ${err.message}`);
7206
8720
  }
7207
8721
  }
7208
8722
  for (const k of ["only", "without"]) {
7209
- for (const code of def.markets?.[k] ?? []) if (!isRegion(code)) add("error", "plugin", `markets.${k}: "${code}" is not an ISO 3166-1 alpha-2 country code (ES, TW\u2026) nor EU`);
8723
+ for (const code of def.markets?.[k] ?? []) if (!isRegion(code)) add2("error", "plugin", `markets.${k}: "${code}" is not an ISO 3166-1 alpha-2 country code (ES, TW\u2026) nor EU`);
7210
8724
  }
7211
- if (def.markets?.only?.length && def.markets.without?.length) add("warn", "plugin", "markets: `only` and `without` together; `only` alone says it");
7212
- if (def.pricing && def.pricing.model !== "free") add("error", "plugin", `pricing.model ${JSON.stringify(def.pricing.model)}: only "free" for now (paid plugins are not supported yet)`);
7213
- if (def.category && (def.widgets ?? []).length) add("warn", "plugin", "`category` is for plugins without widgets: the store takes the widgets' own");
7214
- for (const [k, url2] of [...Object.entries(def.support ?? {}), ["funding", def.funding]]) if (url2 && !/^https:\/\//.test(url2)) add("warn", "plugin", `${k === "funding" ? "funding" : `support.${k}`}: an https:// address`);
7215
- for (const r of [...def.requires ?? [], ...def.optional ?? []]) if (!/^[a-z0-9][a-z0-9-]*\/[a-zA-Z0-9-]+$/.test(r)) add("error", "plugin", `requires/optional ${JSON.stringify(r)}: a type, plugin/thing`);
8725
+ if (def.markets?.only?.length && def.markets.without?.length) add2("warn", "plugin", "markets: `only` and `without` together; `only` alone says it");
8726
+ if (def.pricing && def.pricing.model !== "free") add2("error", "plugin", `pricing.model ${JSON.stringify(def.pricing.model)}: only "free" for now (paid plugins are not supported yet)`);
8727
+ if (def.category && (def.widgets ?? []).length) add2("warn", "plugin", "`category` is for plugins without widgets: the store takes the widgets' own");
8728
+ for (const [k, url2] of [...Object.entries(def.support ?? {}), ["funding", def.funding]]) if (url2 && !/^https:\/\//.test(url2)) add2("warn", "plugin", `${k === "funding" ? "funding" : `support.${k}`}: an https:// address`);
8729
+ for (const r of [...def.requires ?? [], ...def.optional ?? []]) if (!/^[a-z0-9][a-z0-9-]*\/[a-zA-Z0-9-]+$/.test(r)) add2("error", "plugin", `requires/optional ${JSON.stringify(r)}: a type, plugin/thing`);
7216
8730
  const used = languagesOf(def);
7217
8731
  const declared = def.languages;
7218
- if (!declared?.length) add("warn", "plugin", `declare the languages its texts come in: \`languages: [${used.map((l) => `'${l}'`).join(", ")}]\` (and "kiosko": { "languages": [...] } in package.json)`);
8732
+ if (!declared?.length) add2("warn", "plugin", `declare the languages its texts come in: \`languages: [${used.map((l) => `'${l}'`).join(", ")}]\` (and "kiosko": { "languages": [...] } in package.json)`);
7219
8733
  else {
7220
8734
  for (const tag of declared) {
7221
8735
  let canon;
7222
8736
  try {
7223
8737
  canon = Intl.getCanonicalLocales(tag)[0];
7224
8738
  } catch {
7225
- add("error", "plugin", `languages: "${tag}" is not a language tag (en, es, zh-Hant\u2026)`);
8739
+ add2("error", "plugin", `languages: "${tag}" is not a language tag (en, es, zh-Hant\u2026)`);
7226
8740
  continue;
7227
8741
  }
7228
- if (canon !== tag) add("warn", "plugin", `languages: write "${tag}" as "${canon}"`);
7229
- else if (!knownLanguage(tag)) add("warn", "plugin", `languages: "${tag}" is not a language Intl knows`);
8742
+ if (canon !== tag) add2("warn", "plugin", `languages: write "${tag}" as "${canon}"`);
8743
+ else if (!knownLanguage(tag)) add2("warn", "plugin", `languages: "${tag}" is not a language Intl knows`);
7230
8744
  }
7231
- if (!declared.includes("en")) add("error", "plugin", "languages: English (`en`) is the one every text falls back to: list it, and write every text in it");
7232
- if (new Set(declared).size !== declared.length) add("warn", "plugin", "languages: a language is listed twice");
8745
+ if (!declared.includes("en")) add2("error", "plugin", "languages: English (`en`) is the one every text falls back to: list it, and write every text in it");
8746
+ if (new Set(declared).size !== declared.length) add2("warn", "plugin", "languages: a language is listed twice");
7233
8747
  const own = languagesOf({ ...def, widgets: def.widgets?.map(bare), sources: def.sources?.map(bare), interludes: def.interludes?.map(bare) });
7234
8748
  const unlisted = own.filter((l) => !declared.includes(l));
7235
- if (unlisted.length) add("warn", "plugin", `its texts come in ${unlisted.join(", ")} too, which \`languages\` doesn't list`);
8749
+ if (unlisted.length) add2("warn", "plugin", `its texts come in ${unlisted.join(", ")} too, which \`languages\` doesn't list`);
7236
8750
  }
7237
8751
  const langs = declared?.length ? declared : used;
7238
- if (langs.includes("zh") || used.includes("zh")) add("warn", "plugin", "a bare `zh` is read as Simplified and never shown in Taiwan or Hong Kong: write `zh-Hans` (mainland China) and `zh-Hant` (Taiwan, Hong Kong)");
8752
+ if (langs.includes("zh") || used.includes("zh")) add2("warn", "plugin", "a bare `zh` is read as Simplified and never shown in Taiwan or Hong Kong: write `zh-Hans` (mainland China) and `zh-Hant` (Taiwan, Hong Kong)");
7239
8753
  const valid = langs.filter((l) => {
7240
8754
  try {
7241
8755
  return Intl.getCanonicalLocales(l)[0] === l && knownLanguage(l);
@@ -7243,60 +8757,60 @@ function lintPlugin(def) {
7243
8757
  return false;
7244
8758
  }
7245
8759
  });
7246
- const texts = (where, ...ts) => {
8760
+ const texts = (where2, ...ts) => {
7247
8761
  for (const tx of ts) {
7248
8762
  const miss = missingLanguages(tx, valid);
7249
- if (miss.length) add("warn", where, `"${typeof tx === "string" ? tx : tx?.en}" has no ${miss.join(", ")} (the plugin speaks ${langs.join(", ")})`);
8763
+ if (miss.length) add2("warn", where2, `"${typeof tx === "string" ? tx : tx?.en}" has no ${miss.join(", ")} (the plugin speaks ${langs.join(", ")})`);
7250
8764
  }
7251
8765
  };
7252
8766
  texts("plugin", def.name, def.description);
7253
8767
  const ids2 = /* @__PURE__ */ new Set();
7254
8768
  const part = (kind, x) => {
7255
- const where = `${def.id}/${x.id}`;
7256
- if (!PART_ID.test(x.id ?? "")) add("error", where, `${kind} id ${JSON.stringify(x.id)}`);
7257
- if (ids2.has(`${kind}:${x.id}`)) add("error", where, `two ${kind}s with the id "${x.id}"`);
8769
+ const where2 = `${def.id}/${x.id}`;
8770
+ if (!PART_ID.test(x.id ?? "")) add2("error", where2, `${kind} id ${JSON.stringify(x.id)}`);
8771
+ if (ids2.has(`${kind}:${x.id}`)) add2("error", where2, `two ${kind}s with the id "${x.id}"`);
7258
8772
  ids2.add(`${kind}:${x.id}`);
7259
- texts(where, x.name, x.description);
7260
- if (!x.description) add("warn", where, "a description, for the library and the store");
7261
- return where;
8773
+ texts(where2, x.name, x.description);
8774
+ if (!x.description) add2("warn", where2, "a description, for the library and the store");
8775
+ return where2;
7262
8776
  };
7263
- const optionTexts = (where, f) => {
8777
+ const optionTexts = (where2, f) => {
7264
8778
  for (const [path, x] of fieldsOf(f)) {
7265
8779
  const o = x;
7266
- texts(`${where} options.${path}`, ...[o.label, o.help, ...Object.values(o.labels ?? {})].filter((x2) => typeof x2 !== "string"));
8780
+ texts(`${where2} options.${path}`, ...[o.label, o.help, ...Object.values(o.labels ?? {})].filter((x2) => typeof x2 !== "string"));
7267
8781
  }
7268
8782
  };
7269
8783
  for (const w of def.widgets ?? []) optionTexts(`${def.id}/${w.id}`, w.options);
7270
8784
  for (const s of def.sources ?? []) optionTexts(`${def.id}/${s.id}`, s.options);
7271
8785
  for (const i of def.interludes ?? []) optionTexts(`${def.id}/${i.id}`, i.options);
7272
8786
  for (const w of def.widgets ?? []) {
7273
- const where = part("widget", w);
7274
- out.push(...lintOptions(where, w.options, "widget"));
7275
- if (!w.demo) add("warn", where, "no `demo`: the gallery, the editor and the store show it empty");
7276
- if (!w.icon) add("warn", where, "an icon (a Lucide name)");
8787
+ const where2 = part("widget", w);
8788
+ out.push(...lintOptions(where2, w.options, "widget"));
8789
+ if (!w.demo) add2("warn", where2, "no `demo`: the gallery, the editor and the store show it empty");
8790
+ if (!w.icon) add2("warn", where2, "an icon (a Lucide name)");
7277
8791
  const min = w.size?.min, pref = w.size?.preferred;
7278
- if (min && pref && (min.w > pref.w || min.h > pref.h)) add("error", where, `size.min ${min.w}\xD7${min.h} is bigger than size.preferred ${pref.w}\xD7${pref.h}`);
7279
- if (!pref) add("warn", where, "a size.preferred, what it is dropped at");
8792
+ if (min && pref && (min.w > pref.w || min.h > pref.h)) add2("error", where2, `size.min ${min.w}\xD7${min.h} is bigger than size.preferred ${pref.w}\xD7${pref.h}`);
8793
+ if (!pref) add2("warn", where2, "a size.preferred, what it is dropped at");
7280
8794
  for (const s of w.sources ?? []) {
7281
8795
  const [pid] = s.split("/");
7282
- if (pid !== def.id && !(def.requires ?? []).includes(s) && !(def.optional ?? []).includes(s)) add("warn", where, `uses ${s} from another plugin: list it in \`requires\` (or \`optional\`, if it does without)`);
8796
+ if (pid !== def.id && !(def.requires ?? []).includes(s) && !(def.optional ?? []).includes(s)) add2("warn", where2, `uses ${s} from another plugin: list it in \`requires\` (or \`optional\`, if it does without)`);
7283
8797
  }
7284
8798
  }
7285
8799
  for (const s of def.sources ?? []) {
7286
- const where = part("source", s);
7287
- out.push(...lintOptions(where, s.options, "source"));
7288
- if (!s.read && !s.watch) add("error", where, "a source needs `read` or `watch`");
7289
- if (!s.demo) add("warn", where, "no `demo`: widgets using it show nothing in the gallery");
7290
- if (s.background && !s.alerts) add("warn", where, "`background` without `alerts`: it would run for nothing, so Kiosko offers no switch");
8800
+ const where2 = part("source", s);
8801
+ out.push(...lintOptions(where2, s.options, "source"));
8802
+ if (!s.read && !s.watch) add2("error", where2, "a source needs `read` or `watch`");
8803
+ if (!s.demo) add2("warn", where2, "no `demo`: widgets using it show nothing in the gallery");
8804
+ if (s.background && !s.alerts) add2("warn", where2, "`background` without `alerts`: it would run for nothing, so Kiosko offers no switch");
7291
8805
  }
7292
8806
  for (const i of def.interludes ?? []) {
7293
- const where = part("interlude", i);
7294
- out.push(...lintOptions(where, i.options, "interlude"));
8807
+ const where2 = part("interlude", i);
8808
+ out.push(...lintOptions(where2, i.options, "interlude"));
7295
8809
  }
7296
8810
  for (const tp of def.templates ?? []) {
7297
- const where = `${def.id}/${tp.id} template`;
8811
+ const where2 = `${def.id}/${tp.id} template`;
7298
8812
  for (const tile of [...tp.wide, ...tp.square ?? [], ...tp.tall ?? []]) {
7299
- if ([tile.x, tile.y, tile.w, tile.h].some((v) => v < 0 || v > 1) || tile.x + tile.w > 1.0001 || tile.y + tile.h > 1.0001) add("error", where, "tiles are fractions of the page (0..1) and stay inside it");
8813
+ if ([tile.x, tile.y, tile.w, tile.h].some((v) => v < 0 || v > 1) || tile.x + tile.w > 1.0001 || tile.y + tile.h > 1.0001) add2("error", where2, "tiles are fractions of the page (0..1) and stay inside it");
7300
8814
  }
7301
8815
  }
7302
8816
  return out;
@@ -7306,6 +8820,65 @@ function lintPlugin(def) {
7306
8820
  import { readFileSync as readFileSync4 } from "node:fs";
7307
8821
  import { homedir as homedir3 } from "node:os";
7308
8822
  import { join as join7 } from "node:path";
8823
+
8824
+ // packages/core/src/kiosko-release.ts
8825
+ var GITHUB_REPO = "kiosko-lcd/kiosko";
8826
+ var GITHUB_API = "https://api.github.com";
8827
+ var releasePage = (version) => `https://github.com/${GITHUB_REPO}/releases/tag/v${version}`;
8828
+ var windowsInstallerName = (version) => `Kiosko-Setup-${version}-x64.exe`;
8829
+ var releaseAsset = (version, name2) => `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${name2}`;
8830
+ var NOTES_MAX_CHARS = 3e3;
8831
+ var NOTES_MAX_RELEASES = 10;
8832
+ var stable = (v) => {
8833
+ const x = parseVersion(v);
8834
+ return !!x && !x[3];
8835
+ };
8836
+ var tagVersion = (tag) => {
8837
+ const v = (tag ?? "").replace(/^v/, "");
8838
+ return parseVersion(v) ? v : null;
8839
+ };
8840
+ function trimNotes(body2, max = NOTES_MAX_CHARS) {
8841
+ const clean = body2.replace(/<!--[\s\S]*?-->/g, "").replace(/\r\n?/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
8842
+ if (clean.length <= max) return { body: clean, truncated: false };
8843
+ const cut = clean.lastIndexOf("\n", max);
8844
+ return { body: clean.slice(0, cut > max / 2 ? cut : max).trimEnd(), truncated: true };
8845
+ }
8846
+ function versionsBetween(all, current, latest) {
8847
+ return all.filter((v) => stable(v) && compareVersions(v, current) > 0 && compareVersions(v, latest) <= 0).sort((a, b) => compareVersions(b, a));
8848
+ }
8849
+ async function kioskoReleaseNotes(current, latest, o) {
8850
+ const fromNpm = versionsBetween(o.npmVersions ?? [latest], current, latest).slice(0, NOTES_MAX_RELEASES).map((version) => ({ version, url: releasePage(version) }));
8851
+ let list2;
8852
+ try {
8853
+ const r = await o.http.json(`${o.api ?? GITHUB_API}/repos/${GITHUB_REPO}/releases?per_page=30`, { headers: { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" }, ...o.signal ? { signal: o.signal } : {} });
8854
+ if (!Array.isArray(r.data)) throw new Error("GitHub did not answer with a list of releases");
8855
+ list2 = r.data;
8856
+ } catch (err) {
8857
+ return { from: "npm", releases: fromNpm, error: err instanceof Error ? err.message : String(err) };
8858
+ }
8859
+ const byVersion = /* @__PURE__ */ new Map();
8860
+ for (const g of list2) {
8861
+ const v = tagVersion(g.tag_name);
8862
+ if (v && !g.draft && !g.prerelease && stable(v)) byVersion.set(v, g);
8863
+ }
8864
+ const versions = [.../* @__PURE__ */ new Set([...fromNpm.map((r) => r.version), ...versionsBetween([...byVersion.keys()], current, latest)])].sort((a, b) => compareVersions(b, a)).slice(0, NOTES_MAX_RELEASES);
8865
+ const releases2 = versions.map((version) => {
8866
+ const g = byVersion.get(version);
8867
+ if (!g) return { version, url: releasePage(version) };
8868
+ const notes = g.body ? trimNotes(g.body) : null;
8869
+ const url2 = g.html_url?.startsWith(`https://github.com/${GITHUB_REPO}/`) ? g.html_url : releasePage(version);
8870
+ return { version, ...g.name ? { name: g.name } : {}, ...notes?.body ? { body: notes.body, ...notes.truncated ? { truncated: true } : {} } : {}, url: url2, ...g.published_at ? { date: g.published_at } : {} };
8871
+ });
8872
+ const newest = byVersion.get(latest);
8873
+ const name2 = windowsInstallerName(latest);
8874
+ const asset = (n) => newest?.assets?.find((a) => a.name === n)?.browser_download_url;
8875
+ const exe = asset(name2);
8876
+ const sha = asset(`${name2}.sha256`);
8877
+ const ours = (u) => !!u && u.startsWith(`https://github.com/${GITHUB_REPO}/releases/download/`);
8878
+ return { from: "github", releases: releases2, ...ours(exe) && ours(sha) ? { windows: { name: name2, exe, sha256: sha } } : {} };
8879
+ }
8880
+
8881
+ // packages/core/src/plugin-updates.ts
7309
8882
  var REGISTRY = "https://registry.npmjs.org";
7310
8883
  function npmRegistry(env = process.env, home = homedir3()) {
7311
8884
  const fromEnv = env.npm_config_registry ?? env.NPM_CONFIG_REGISTRY;
@@ -7326,10 +8899,12 @@ var releases = (p) => Object.keys(p.versions ?? {}).filter((v) => {
7326
8899
  function pickUpdate(installed2, p, env) {
7327
8900
  const latest = p["dist-tags"]?.latest;
7328
8901
  if (!latest || compareVersions(latest, installed2.version) <= 0) return null;
7329
- const why = (v) => incompatibility(packageMeta(p.versions?.[v] ?? {}), env);
7330
- const blocked = p.versions?.[latest] ? why(latest) : null;
7331
- const version = releases(p).find((v) => compareVersions(v, installed2.version) > 0 && compareVersions(v, latest) <= 0 && !why(v));
7332
- return { id: installed2.id, package: installed2.package, current: installed2.version, latest, ...version ? { version } : {}, ...blocked ? { blocked } : {} };
8902
+ const meta = (v) => packageMeta(p.versions?.[v] ?? {});
8903
+ const why2 = (v) => incompatibility(meta(v), env);
8904
+ const blocked = p.versions?.[latest] ? why2(latest) : null;
8905
+ const version = releases(p).find((v) => compareVersions(v, installed2.version) > 0 && compareVersions(v, latest) <= 0 && !why2(v));
8906
+ const unlocks = blocked && env.kioskoLatest && compareVersions(env.kioskoLatest, env.sdk) > 0 && !incompatibility(meta(latest), { sdk: env.kioskoLatest, platform: env.platform });
8907
+ return { id: installed2.id, package: installed2.package, current: installed2.version, latest, ...version ? { version } : {}, ...blocked ? { blocked } : {}, ...unlocks ? { unlockedBy: env.kioskoLatest } : {} };
7333
8908
  }
7334
8909
  async function checkUpdates(plugins, o = {}) {
7335
8910
  const http = o.http ?? createHttp({ agent: "kiosko-updates" });
@@ -7345,17 +8920,17 @@ async function checkUpdates(plugins, o = {}) {
7345
8920
  return null;
7346
8921
  }
7347
8922
  };
7348
- const found = await Promise.all(plugins.map(async (pl) => {
7349
- const p = await read(pl.package);
7350
- return p ? pickUpdate(pl, p, env) : null;
7351
- }));
8923
+ const [k, ...found] = await Promise.all([o.kioskoVersion ? read("kiosko") : Promise.resolve(null), ...plugins.map((pl) => read(pl.package))]);
7352
8924
  let kiosko;
7353
- if (o.kioskoVersion) {
7354
- const p = await read("kiosko");
7355
- const latest = p?.["dist-tags"]?.latest;
7356
- if (latest && compareVersions(latest, o.kioskoVersion) > 0) kiosko = { current: o.kioskoVersion, latest };
8925
+ const latest = k?.["dist-tags"]?.latest;
8926
+ if (o.kioskoVersion && latest && compareVersions(latest, o.kioskoVersion) > 0) {
8927
+ const all = Object.keys(k?.versions ?? {});
8928
+ const versions = versionsBetween(all.length ? all : [latest], o.kioskoVersion, latest);
8929
+ const notes = o.github === false ? void 0 : await kioskoReleaseNotes(o.kioskoVersion, latest, { http, npmVersions: versions, ...o.github ? { api: o.github } : {}, ...o.signal ? { signal: o.signal } : {} });
8930
+ kiosko = { current: o.kioskoVersion, latest, versions, ...notes ? { notes } : {} };
7357
8931
  }
7358
- return { checkedAt: o.now ?? Date.now(), plugins: found.filter((x) => !!x), ...kiosko ? { kiosko } : {}, errors };
8932
+ const picked = plugins.map((pl, i) => found[i] ? pickUpdate(pl, found[i], { ...env, ...kiosko ? { kioskoLatest: kiosko.latest } : {} }) : null);
8933
+ return { checkedAt: o.now ?? Date.now(), plugins: picked.filter((x) => !!x), ...kiosko ? { kiosko } : {}, errors };
7359
8934
  }
7360
8935
 
7361
8936
  // packages/core/src/store/client.ts
@@ -7382,6 +8957,71 @@ function addedPermissions(before, after) {
7382
8957
  // packages/core/src/store/tar.ts
7383
8958
  var MAX_TARBALL_BYTES = 20 * 1024 * 1024;
7384
8959
 
8960
+ // packages/core/src/remote/ops.ts
8961
+ import { createHash as createHash2 } from "node:crypto";
8962
+ var CHUNK = 16 * 1024;
8963
+ async function session(host, port, key, uid) {
8964
+ const s = await openSession(host, port, key, uid);
8965
+ const st = await nextSealed(s.wire, s.session);
8966
+ if (st.type !== T.STATE) throw new Error("the screen did not say its state");
8967
+ return s;
8968
+ }
8969
+ async function otaUpdate(host, port, key, uid, image2, progress) {
8970
+ if (image2[0] !== 233) throw new ScreenError("notFirmware", "not an ESP32 firmware image (.bin)");
8971
+ const { wire, session: s } = await session(host, port, key, uid);
8972
+ try {
8973
+ sendSealed(wire, s, T.OTA_BEGIN, { size: image2.length, sha256: createHash2("sha256").update(image2).digest("hex") });
8974
+ const next = async () => {
8975
+ for (; ; ) {
8976
+ const m = await nextSealed(wire, s, 3e4);
8977
+ if (m.type === T.OTA_ACK) return m.json().off;
8978
+ if (m.type === T.OTA_DONE) {
8979
+ const j = m.json();
8980
+ if (!j.ok) throw new ScreenError("otaFailed", `the screen refused the update: ${j.err ?? "error"}`);
8981
+ return -1;
8982
+ }
8983
+ if (m.type === T.PING) sendSealed(wire, s, T.PONG, {});
8984
+ }
8985
+ };
8986
+ let off2 = await next();
8987
+ while (off2 >= 0 && off2 < image2.length) {
8988
+ sendSealed(wire, s, T.OTA_DATA, image2.subarray(off2, off2 + CHUNK));
8989
+ const got = await next();
8990
+ if (got !== Math.min(image2.length, off2 + CHUNK)) throw new ScreenError("otaFailed", `the screen lost the update at ${off2}`);
8991
+ off2 = got;
8992
+ progress?.(off2, image2.length);
8993
+ }
8994
+ sendSealed(wire, s, T.OTA_END, {});
8995
+ if (await next() !== -1) throw new ScreenError("otaFailed", "the screen did not confirm the update");
8996
+ } finally {
8997
+ wire.close();
8998
+ }
8999
+ }
9000
+ async function screenLogs(host, port, key, uid) {
9001
+ const { wire, session: s } = await session(host, port, key, uid);
9002
+ try {
9003
+ sendSealed(wire, s, T.LOGS, {});
9004
+ for (; ; ) {
9005
+ const m = await nextSealed(wire, s);
9006
+ if (m.type === T.LOGS) return String(m.json().text ?? "");
9007
+ }
9008
+ } finally {
9009
+ wire.close();
9010
+ }
9011
+ }
9012
+ async function unpairScreen(host, port, key, uid) {
9013
+ const { wire, session: s } = await session(host, port, key, uid);
9014
+ try {
9015
+ sendSealed(wire, s, T.UNPAIR, {});
9016
+ for (; ; ) {
9017
+ const m = await nextSealed(wire, s).catch(() => null);
9018
+ if (!m || m.type === T.UNPAIR) return;
9019
+ }
9020
+ } finally {
9021
+ wire.close();
9022
+ }
9023
+ }
9024
+
7385
9025
  // plugins/core/src/index.ts
7386
9026
  import { readdir, readFile, stat } from "node:fs/promises";
7387
9027
  import { join as join8 } from "node:path";
@@ -7746,7 +9386,7 @@ var image = defineWidget({
7746
9386
  var src_default = definePlugin({
7747
9387
  id: "core",
7748
9388
  name: { en: "Essentials", es: "B\xE1sicos", de: "Grundlagen", "zh-Hant": "\u57FA\u672C\u5DE5\u5177", "zh-Hans": "\u57FA\u7840\u7EC4\u4EF6" },
7749
- version: "0.2.8",
9389
+ version: "0.2.10",
7750
9390
  languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
7751
9391
  sdk: "^0.2.0",
7752
9392
  // The picture widget reads the image (or folder, or URL) you give it.
@@ -7763,8 +9403,8 @@ import { existsSync as existsSync7, statSync as statSync2 } from "node:fs";
7763
9403
  import { isAbsolute, join as join9 } from "node:path";
7764
9404
  import { pathToFileURL as pathToFileURL3 } from "node:url";
7765
9405
  var loaded = /* @__PURE__ */ new Map();
7766
- function resolveModule(name, dir) {
7767
- const expanded = expandPath(name);
9406
+ function resolveModule(name2, dir) {
9407
+ const expanded = expandPath(name2);
7768
9408
  const base3 = isAbsolute(expanded) ? expanded : join9(expandPath(dir), expanded);
7769
9409
  for (const p of [base3, `${base3}.mjs`, `${base3}.js`, join9(base3, "index.mjs"), join9(base3, "index.js")]) {
7770
9410
  if (existsSync7(p) && statSync2(p).isFile()) return p;
@@ -7791,14 +9431,14 @@ var optionsSchema = t.object({
7791
9431
  config: t.map({ label: { en: "Module config (key \u2192 value)", es: "Config del m\xF3dulo (clave \u2192 valor)", de: "Modulkonfiguration (Schl\xFCssel \u2192 Wert)", "zh-Hant": "\u6A21\u7D44\u8A2D\u5B9A\uFF08\u9375 \u2192 \u503C\uFF09", "zh-Hans": "\u6A21\u5757\u914D\u7F6E\uFF08\u952E \u2192 \u503C\uFF09" }, help: { en: "Simple values only; numbers and true/false are converted.", es: "S\xF3lo valores simples; n\xFAmeros y true/false se convierten.", de: "Nur einfache Werte; Zahlen und true/false werden umgewandelt.", "zh-Hant": "\u50C5\u9650\u7C21\u55AE\u503C\uFF1B\u6578\u5B57\u548C true/false \u6703\u81EA\u52D5\u8F49\u63DB\u3002", "zh-Hans": "\u4EC5\u9650\u7B80\u5355\u503C\uFF1B\u6570\u5B57\u548C true/false \u4F1A\u81EA\u52A8\u8F6C\u6362\u3002" } }),
7792
9432
  json: t.string({ multiline: true, label: { en: "Module config as JSON", es: "Config del m\xF3dulo en JSON", de: "Modulkonfiguration als JSON", "zh-Hant": "JSON \u683C\u5F0F\u7684\u6A21\u7D44\u8A2D\u5B9A", "zh-Hans": "JSON \u683C\u5F0F\u7684\u6A21\u5757\u914D\u7F6E" }, help: { en: "For lists and nested values. Wins over the table above.", es: "Para listas y valores anidados. Manda sobre la tabla de arriba.", de: "F\xFCr Listen und verschachtelte Werte. Hat Vorrang vor der Tabelle oben.", "zh-Hant": "\u7528\u65BC\u6E05\u55AE\u548C\u5DE2\u72C0\u503C\uFF0C\u512A\u5148\u65BC\u4E0A\u65B9\u7684\u8868\u683C\u3002", "zh-Hans": "\u7528\u4E8E\u5217\u8868\u548C\u5D4C\u5957\u503C\uFF0C\u4F18\u5148\u4E8E\u4E0A\u65B9\u7684\u8868\u683C\u3002" }, advanced: true })
7793
9433
  });
7794
- function moduleConfig(mod, o) {
9434
+ function moduleConfig(mod2, o) {
7795
9435
  const kv = Object.fromEntries(Object.entries(o.config).map(([k, v]) => [k, v === "true" ? true : v === "false" ? false : v.trim() !== "" && !Number.isNaN(Number(v)) ? Number(v) : v]));
7796
9436
  let js = {};
7797
9437
  try {
7798
9438
  js = o.json.trim() ? JSON.parse(o.json) : {};
7799
9439
  } catch {
7800
9440
  }
7801
- return { ...mod?.defaults ?? {}, ...kv, ...js };
9441
+ return { ...mod2?.defaults ?? {}, ...kv, ...js };
7802
9442
  }
7803
9443
  var module2 = defineWidget({
7804
9444
  id: "module",
@@ -7813,36 +9453,36 @@ var module2 = defineWidget({
7813
9453
  if (!options2.module) throw new Error("no module set");
7814
9454
  const path = resolveModule(options2.module, options2.dir);
7815
9455
  if (!path) throw new Error(`module "${options2.module}" not found in ${options2.dir}`);
7816
- const mod = await load2(path);
9456
+ const mod2 = await load2(path);
7817
9457
  if (options2.json.trim()) JSON.parse(options2.json);
7818
- const data = mod.fetch ? await mod.fetch({ config: moduleConfig(mod, options2), now, log, canvas }) : void 0;
9458
+ const data = mod2.fetch ? await mod2.fetch({ config: moduleConfig(mod2, options2), now, log, canvas }) : void 0;
7819
9459
  return { path, data };
7820
9460
  },
7821
9461
  // The module's own `updateMs`, as in aimonitor.
7822
9462
  intervalOf: ({ data }) => data ? loaded.get(data.path)?.updateMs : void 0,
7823
9463
  render(g, ctx) {
7824
- const mod = ctx.data ? loaded.get(ctx.data.path) : void 0;
7825
- if (!mod) {
9464
+ const mod2 = ctx.data ? loaded.get(ctx.data.path) : void 0;
9465
+ if (!mod2) {
7826
9466
  ctx.kit.drawTracked(g, ctx.options.module ? "\u2026" : ctx.t({ en: "Pick a module in the options", es: "Elige un m\xF3dulo en las opciones", de: "W\xE4hle ein Modul in den Optionen", "zh-Hant": "\u8ACB\u5728\u9078\u9805\u4E2D\u9078\u64C7\u6A21\u7D44", "zh-Hans": "\u8BF7\u5728\u9009\u9879\u4E2D\u9009\u62E9\u6A21\u5757" }), ctx.box.x, ctx.box.y + 30, { size: 22, family: ctx.theme.fonts.sans, color: ctx.theme.colors.inkDim });
7827
9467
  return;
7828
9468
  }
7829
9469
  const box = ctx.box;
7830
- mod.draw(g, { config: moduleConfig(mod, ctx.options), data: ctx.data?.data, now: ctx.now, box, ...legacyLook(ctx.theme), kit: ctx.kit, canvas: ctx.canvas });
9470
+ mod2.draw(g, { config: moduleConfig(mod2, ctx.options), data: ctx.data?.data, now: ctx.now, box, ...legacyLook(ctx.theme), kit: ctx.kit, canvas: ctx.canvas });
7831
9471
  },
7832
9472
  redraw: "minute",
7833
9473
  visible({ options: options2, data, now }) {
7834
- const mod = data ? loaded.get(data.path) : void 0;
7835
- return mod?.visible?.({ config: moduleConfig(mod, options2), data: data?.data, now }) ?? true;
9474
+ const mod2 = data ? loaded.get(data.path) : void 0;
9475
+ return mod2?.visible?.({ config: moduleConfig(mod2, options2), data: data?.data, now }) ?? true;
7836
9476
  },
7837
9477
  urgent({ options: options2, data, now }) {
7838
- const mod = data ? loaded.get(data.path) : void 0;
7839
- return mod?.urgent?.({ config: moduleConfig(mod, options2), data: data?.data, now }) ?? false;
9478
+ const mod2 = data ? loaded.get(data.path) : void 0;
9479
+ return mod2?.urgent?.({ config: moduleConfig(mod2, options2), data: data?.data, now }) ?? false;
7840
9480
  }
7841
9481
  });
7842
9482
  var src_default2 = definePlugin({
7843
9483
  id: "legacy",
7844
9484
  name: { en: "aimonitor compatibility", es: "Compatibilidad aimonitor", de: "aimonitor-Kompatibilit\xE4t", "zh-Hant": "aimonitor \u76F8\u5BB9\u6027", "zh-Hans": "aimonitor \u517C\u5BB9" },
7845
- version: "0.2.8",
9485
+ version: "0.2.10",
7846
9486
  languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
7847
9487
  sdk: "^0.2.0",
7848
9488
  // Runs the aimonitor modules you point it at, and reads their folder.
@@ -7856,7 +9496,7 @@ var src_default2 = definePlugin({
7856
9496
 
7857
9497
  // packages/server/src/official.ts
7858
9498
  var BUNDLED_PLUGIN_IDS = ["agents", "cats", "system", "vitals", "usage", "weather", "calendar", "news", "mirror", "gitlab", "github", "calls", "timesheet", "llm", "gpu", "homeassistant"];
7859
- var OPTIONAL_PLUGIN_IDS = ["doom", "video", "fractals", "gaming", "logs", "hazards"];
9499
+ var OPTIONAL_PLUGIN_IDS = ["doom", "video", "fractals", "gaming", "logs", "hazards", "batteries"];
7860
9500
  var OFFICIAL_PLUGINS = [
7861
9501
  ...BUNDLED_PLUGIN_IDS.map((id) => ({ id, npm: `kiosko-plugin-${id}`, bundled: true })),
7862
9502
  ...OPTIONAL_PLUGIN_IDS.map((id) => ({ id, npm: `kiosko-plugin-${id}`, bundled: false }))
@@ -7947,9 +9587,9 @@ function readConfigText(text3) {
7947
9587
  }
7948
9588
  }
7949
9589
  function readInput(file) {
7950
- const name = file === "-" ? "(stdin)" : file;
7951
- if (file !== "-" && !existsSync9(file)) return { error: `not found: ${file}`, notes: [], name };
7952
- return { ...readConfigText(readFileSync5(file === "-" ? 0 : file, "utf8")), name };
9590
+ const name2 = file === "-" ? "(stdin)" : file;
9591
+ if (file !== "-" && !existsSync9(file)) return { error: `not found: ${file}`, notes: [], name: name2 };
9592
+ return { ...readConfigText(readFileSync5(file === "-" ? 0 : file, "utf8")), name: name2 };
7953
9593
  }
7954
9594
  var pluginDefs = (r) => r.list().map((p) => p.def);
7955
9595
  async function findRunning(cfg, configPath, o) {
@@ -8139,9 +9779,9 @@ ${dim("Dry run: nothing was written.")} Run again with --apply to back up the cu
8139
9779
  signal: AbortSignal.timeout(15e3)
8140
9780
  }).catch((err) => err);
8141
9781
  if (r instanceof Error || !r.ok) {
8142
- const why = r instanceof Error ? r.message : r.status === 409 ? "the configuration changed in the editor meanwhile" : `HTTP ${r.status}`;
9782
+ const why2 = r instanceof Error ? r.message : r.status === 409 ? "the configuration changed in the editor meanwhile" : `HTTP ${r.status}`;
8143
9783
  console.log(red(`
8144
- Not applied: ${why}. Run the import again${saved}.`));
9784
+ Not applied: ${why2}. Run the import again${saved}.`));
8145
9785
  return 1;
8146
9786
  }
8147
9787
  console.log(`
@@ -8175,7 +9815,7 @@ async function configCommand(argv2, ctx) {
8175
9815
  }
8176
9816
 
8177
9817
  // packages/server/src/editor-cli.ts
8178
- function editorUrl(server, over = {}) {
9818
+ function editorUrl2(server, over = {}) {
8179
9819
  let host = over.host ?? server.host;
8180
9820
  if (host === "0.0.0.0" || host === "") host = "127.0.0.1";
8181
9821
  if (host === "::") host = "::1";
@@ -8192,8 +9832,8 @@ async function runningAt(url2, timeoutMs = 1500) {
8192
9832
  return null;
8193
9833
  }
8194
9834
  }
8195
- async function editorCommand({ server, flags, open, log }) {
8196
- const url2 = editorUrl(server, flags);
9835
+ async function editorCommand({ server, flags, open: open2, log }) {
9836
+ const url2 = editorUrl2(server, flags);
8197
9837
  const version = await runningAt(url2);
8198
9838
  if (!version) {
8199
9839
  log(`Kiosko isn't running at ${url2}`);
@@ -8202,7 +9842,7 @@ async function editorCommand({ server, flags, open, log }) {
8202
9842
  return 1;
8203
9843
  }
8204
9844
  log(`Kiosko ${version} \u2014 editor at ${url2}`);
8205
- if (!flags.print) open(url2);
9845
+ if (!flags.print) open2(url2);
8206
9846
  return 0;
8207
9847
  }
8208
9848
 
@@ -8232,12 +9872,12 @@ async function loadPluginDir(dir, o = {}) {
8232
9872
  const entry = (o.src || !built) && existsSync10(src) ? src : built;
8233
9873
  if (!entry) throw new Error(`no plugin in ${root}: no package.json "kiosko.plugin", index.js or src/index.ts`);
8234
9874
  installSdkResolver();
8235
- const mod = await import(`${pathToFileURL4(entry).href}?v=${Date.now()}`);
8236
- if (!mod.default) throw new Error(`${entry} has no default export (export default definePlugin({...}))`);
8237
- return { def: mod.default, pkg, entry };
9875
+ const mod2 = await import(`${pathToFileURL4(entry).href}?v=${Date.now()}`);
9876
+ if (!mod2.default) throw new Error(`${entry} has no default export (export default definePlugin({...}))`);
9877
+ return { def: mod2.default, pkg, entry };
8238
9878
  }
8239
- var flagOf = (argv2, name) => argv2.includes(name);
8240
- var optOf = (argv2, name) => argv2.includes(name) ? argv2[argv2.indexOf(name) + 1] : void 0;
9879
+ var flagOf = (argv2, name2) => argv2.includes(name2);
9880
+ var optOf = (argv2, name2) => argv2.includes(name2) ? argv2[argv2.indexOf(name2) + 1] : void 0;
8241
9881
  var positional = (argv2) => argv2.filter((a, i) => !a.startsWith("--") && !["--out", "--port"].includes(argv2[i - 1] ?? ""));
8242
9882
  function lookList(looks) {
8243
9883
  const parts = looks.map((l) => l.split(" "));
@@ -8254,8 +9894,8 @@ async function check2(dir, argv2) {
8254
9894
  else if (def.sdk && meta.sdk !== def.sdk) issues.push({ level: "warn", where: "package.json", message: `kiosko.sdk ${meta.sdk} differs from the definition's sdk ${def.sdk}` });
8255
9895
  if (def.languages?.length && !meta.languages) issues.push({ level: "warn", where: "package.json", message: `add "kiosko": { "languages": ${JSON.stringify(def.languages)} } so a catalogue knows them without running it` });
8256
9896
  else if (def.languages && meta.languages && def.languages.join() !== meta.languages.join()) issues.push({ level: "warn", where: "package.json", message: `kiosko.languages ${JSON.stringify(meta.languages)} differs from the definition's ${JSON.stringify(def.languages)}` });
8257
- const why = incompatibility({ sdk: def.sdk ?? meta.sdk, platforms: def.platforms ?? meta.platforms });
8258
- if (why) issues.push({ level: "warn", where: "plugin", message: `this Kiosko can't run it: ${why}` });
9897
+ const why2 = incompatibility({ sdk: def.sdk ?? meta.sdk, platforms: def.platforms ?? meta.platforms });
9898
+ if (why2) issues.push({ level: "warn", where: "plugin", message: `this Kiosko can't run it: ${why2}` });
8259
9899
  if (pkg.version && pkg.version !== def.version) issues.push({ level: "warn", where: "package.json", message: `version ${pkg.version} differs from the definition's ${def.version}` });
8260
9900
  const { checkPlugin: checkPlugin2 } = await Promise.resolve().then(() => (init_testing(), testing_exports));
8261
9901
  const painted = /* @__PURE__ */ new Map();
@@ -8309,11 +9949,11 @@ async function dev(dir, argv2) {
8309
9949
  }
8310
9950
  function newPluginFiles(id) {
8311
9951
  const sdk = `^${SDK_VERSION.split(".").slice(0, 2).join(".")}.0`;
8312
- const name = id.replace(/(^|-)(\w)/g, (_m, _d, c) => ` ${c.toUpperCase()}`).trim();
9952
+ const name2 = id.replace(/(^|-)(\w)/g, (_m, _d, c) => ` ${c.toUpperCase()}`).trim();
8313
9953
  const pkg = {
8314
9954
  name: `kiosko-plugin-${id}`,
8315
9955
  version: "0.1.0",
8316
- description: `${name} for Kiosko.`,
9956
+ description: `${name2} for Kiosko.`,
8317
9957
  type: "module",
8318
9958
  license: "MIT",
8319
9959
  keywords: ["kiosko", "kiosko-plugin", "lcd", "widgets"],
@@ -8338,7 +9978,7 @@ function newPluginFiles(id) {
8338
9978
  devDependencies: { "@kiosko/sdk": sdk, "@loksly/lcd-canvas-kit": "^0.2.0", "@napi-rs/canvas": "^1.0.10", "@types/node": "^24.0.0", esbuild: "^0.25.0", typescript: "^5.9.3" }
8339
9979
  };
8340
9980
  const index = `/**
8341
- * ${name}: a widget fed by a shared source. Rename, then fill in \`read\` and \`render\`.
9981
+ * ${name2}: a widget fed by a shared source. Rename, then fill in \`read\` and \`render\`.
8342
9982
  * The guide: https://github.com/kiosko-lcd/kiosko/blob/main/docs/plugins.md
8343
9983
  */
8344
9984
  import { createHttp, definePlugin, defineSource, defineWidget, t } from '@kiosko/sdk';
@@ -8352,7 +9992,7 @@ export interface Reading {
8352
9992
 
8353
9993
  export const reading = defineSource({
8354
9994
  id: 'reading',
8355
- name: { en: '${name}', es: '${name}' },
9995
+ name: { en: '${name2}', es: '${name2}' },
8356
9996
  description: { en: 'What the widgets show, read once for all of them.', es: 'Lo que muestran los widgets, le\xEDdo una vez para todos.' },
8357
9997
  options: t.object({
8358
9998
  url: t.string({ format: 'url', risk: 'network', placeholder: 'https://api.example.com/value', label: { en: 'Address', es: 'Direcci\xF3n' } }),
@@ -8368,14 +10008,14 @@ export const reading = defineSource({
8368
10008
 
8369
10009
  export const card = defineWidget({
8370
10010
  id: 'card',
8371
- name: { en: '${name}', es: '${name}' },
10011
+ name: { en: '${name2}', es: '${name2}' },
8372
10012
  description: { en: 'The latest value, in big.', es: 'El \xFAltimo valor, en grande.' },
8373
10013
  icon: 'gauge',
8374
10014
  category: 'info',
8375
10015
  size: { min: { w: 160, h: 80 }, preferred: { w: 320, h: 160 } },
8376
10016
  sources: ['${id}/reading'],
8377
10017
  options: t.object({
8378
- label: t.string({ default: '${name}', label: { en: 'Label', es: 'Etiqueta' } }),
10018
+ label: t.string({ default: '${name2}', label: { en: 'Label', es: 'Etiqueta' } }),
8379
10019
  }),
8380
10020
  redraw: 'minute',
8381
10021
  render(g, { box, options, sources, theme, kit, fmt }) {
@@ -8396,9 +10036,9 @@ export const card = defineWidget({
8396
10036
 
8397
10037
  export default definePlugin({
8398
10038
  id: '${id}',
8399
- name: { en: '${name}', es: '${name}' },
10039
+ name: { en: '${name2}', es: '${name2}' },
8400
10040
  version: '0.1.0',
8401
- description: { en: '${name} for Kiosko.', es: '${name} para Kiosko.' },
10041
+ description: { en: '${name2} for Kiosko.', es: '${name2} para Kiosko.' },
8402
10042
  sdk: '${sdk}',
8403
10043
  // The languages its texts come in (Chinese by script: 'zh-Hant', 'zh-Hans').
8404
10044
  languages: ['en', 'es'],
@@ -8415,7 +10055,7 @@ import plugin, { card } from './index.ts';
8415
10055
 
8416
10056
  test('the card shows the label and the value', () => {
8417
10057
  const r = renderWidget(card, { size: { w: 320, h: 160 } });
8418
- assert.deepEqual(r.texts.slice(0, 2), ['${name}', '42']);
10058
+ assert.deepEqual(r.texts.slice(0, 2), ['${name2}', '42']);
8419
10059
  assert.equal(r.outside, 0);
8420
10060
  });
8421
10061
 
@@ -8442,7 +10082,7 @@ console.log('dist/index.js');
8442
10082
  const tsconfig = { compilerOptions: { target: "ES2023", module: "nodenext", moduleResolution: "nodenext", lib: ["ES2023"], strict: true, noEmit: true, allowImportingTsExtensions: true, skipLibCheck: true, types: ["node"], customConditions: ["source"] }, include: ["src/**/*.ts"] };
8443
10083
  const readme = `# kiosko-plugin-${id}
8444
10084
 
8445
- ${name} for [Kiosko](https://github.com/kiosko-lcd/kiosko).
10085
+ ${name2} for [Kiosko](https://github.com/kiosko-lcd/kiosko).
8446
10086
 
8447
10087
  \`\`\`sh
8448
10088
  npm install
@@ -8512,9 +10152,9 @@ async function pluginsCommand(argv2, registry2) {
8512
10152
  case "dev":
8513
10153
  return dev(positional(names)[0] ?? ".", names);
8514
10154
  case "new": {
8515
- const [id, where] = positional(names);
10155
+ const [id, where2] = positional(names);
8516
10156
  if (!id || !/^[a-z0-9][a-z0-9-]*$/.test(id)) throw new Error("usage: kiosko plugins new <id> [folder] (id: lowercase letters, digits and dashes)");
8517
- const dir = resolve4(where ?? `kiosko-plugin-${id}`);
10157
+ const dir = resolve4(where2 ?? `kiosko-plugin-${id}`);
8518
10158
  if (existsSync10(dir) && readdirSync4(dir).length) throw new Error(`${dir} is not empty`);
8519
10159
  for (const [file, body2] of Object.entries(newPluginFiles(id))) {
8520
10160
  mkdirSync6(join12(dir, file, ".."), { recursive: true });
@@ -8522,7 +10162,7 @@ async function pluginsCommand(argv2, registry2) {
8522
10162
  }
8523
10163
  console.log(`${dir}
8524
10164
 
8525
- cd ${where ?? `kiosko-plugin-${id}`} && npm install && npm test
10165
+ cd ${where2 ?? `kiosko-plugin-${id}`} && npm install && npm test
8526
10166
  npm run kiosko:check then: npm run build && npm run dev`);
8527
10167
  return;
8528
10168
  }
@@ -8598,13 +10238,266 @@ plugins folder: ${paths.plugins}`);
8598
10238
  }
8599
10239
  }
8600
10240
 
10241
+ // packages/server/src/remote-cli.ts
10242
+ import { readFileSync as readFileSync7 } from "node:fs";
10243
+ import { hostname as hostname2 } from "node:os";
10244
+ import { createInterface } from "node:readline/promises";
10245
+
10246
+ // packages/server/src/remote-api.ts
10247
+ import { randomBytes as randomBytes3 } from "node:crypto";
10248
+ import { hostname } from "node:os";
10249
+ var PAIR_TTL_MS = 3 * 6e4;
10250
+ async function raw(req, limit) {
10251
+ const chunks = [];
10252
+ let size = 0;
10253
+ for await (const c of req) {
10254
+ size += c.length;
10255
+ if (size > limit) throw new ScreenError("tooBig", "body too large");
10256
+ chunks.push(c);
10257
+ }
10258
+ return Buffer.concat(chunks);
10259
+ }
10260
+ function remoteScreen(registry2, info, key, locale, host) {
10261
+ const rot = [0, 90, 180, 270].includes(info.rot) ? info.rot : 0;
10262
+ const quarter = rot === 90 || rot === 270;
10263
+ const width = (quarter ? info.h : info.w) || 320, height = (quarter ? info.w : info.h) || 172;
10264
+ const s = newScreen(info.id || "Remote screen", width, height, { driver: "remote", uid: info.uid, ...info.id ? { id: info.id } : {}, key, ...host ? { host } : {} });
10265
+ s.rotate = rot;
10266
+ s.jpegQuality = 85;
10267
+ s.maxBytes = Math.max(16 * 1024, Math.min(info.max - 1024, 90 * 1024));
10268
+ s.pages = [starterPage((t2) => !!registry2.widget(t2), { width, height, locale, agents: false })];
10269
+ return s;
10270
+ }
10271
+ function remoteApi(ctx) {
10272
+ const pending2 = /* @__PURE__ */ new Map();
10273
+ const locate = async (uid, host, port) => {
10274
+ if (host) return { host, port: port ?? 7428 };
10275
+ const t2 = ctx.locate?.(uid);
10276
+ if (t2) return t2;
10277
+ const b = browser();
10278
+ const f = b.get(uid) ?? (uid ? (await b.browse(2500)).find((x) => x.uid === uid) : void 0);
10279
+ return f ? { host: f.address, port: f.port } : void 0;
10280
+ };
10281
+ const fail = (res, err) => {
10282
+ if (err instanceof ScreenError) return ctx.json(res, err.code === "offline" ? 404 : 409, { error: err.message, code: `remote.${err.code}` });
10283
+ const e = err;
10284
+ return ctx.json(res, 502, { error: e?.message ?? String(err), code: "remote.unreachable" });
10285
+ };
10286
+ const screenOf = (id) => ctx.runtime.config.screens.find((s) => s.id === id);
10287
+ const remoteOf = (id) => {
10288
+ const s = screenOf(id);
10289
+ if (!s || s.device.driver !== "remote") return null;
10290
+ const d = ctx.runtime.deviceOf(id);
10291
+ return { screen: s, device: s.device, driver: d instanceof RemoteDevice ? d : null };
10292
+ };
10293
+ return async function handle(req, res, p, m) {
10294
+ if (p === "/api/remote/pair" && m === "POST") {
10295
+ const b = await ctx.body(req, 4096);
10296
+ const uid = String(b.uid ?? "");
10297
+ const at = await locate(uid, b.host, b.port);
10298
+ if (!at) return ctx.json(res, 404, { error: "that screen is not on the network", code: "remote.offline" }), true;
10299
+ try {
10300
+ const pairing = await Pairing.start(at.host, at.port, `Kiosko on ${hostname()}`.slice(0, 40));
10301
+ if (uid && pairing.info.uid !== uid) {
10302
+ pairing.cancel();
10303
+ return ctx.json(res, 409, { error: "another screen answers there", code: "remote.otherScreen" }), true;
10304
+ }
10305
+ const pairId = randomBytes3(12).toString("hex");
10306
+ const timer = setTimeout(() => {
10307
+ pending2.get(pairId)?.pairing.cancel();
10308
+ pending2.delete(pairId);
10309
+ }, PAIR_TTL_MS);
10310
+ timer.unref();
10311
+ pending2.set(pairId, { pairing, uid: pairing.info.uid, host: at.host, port: at.port, timer });
10312
+ ctx.json(res, 200, { pairId, ttl: pairing.ttl, screen: pairing.info });
10313
+ } catch (err) {
10314
+ fail(res, err);
10315
+ }
10316
+ return true;
10317
+ }
10318
+ let mm = /^\/api\/remote\/pair\/([0-9a-f]{24})$/.exec(p);
10319
+ if (mm && (m === "POST" || m === "DELETE")) {
10320
+ const job = pending2.get(mm[1]);
10321
+ if (!job) return ctx.json(res, 404, { error: "no such pairing (it expired?)", code: "remote.pairingOver" }), true;
10322
+ pending2.delete(mm[1]);
10323
+ clearTimeout(job.timer);
10324
+ if (m === "DELETE") {
10325
+ job.pairing.cancel();
10326
+ return ctx.json(res, 200, { ok: true }), true;
10327
+ }
10328
+ const b = await ctx.body(req, 4096);
10329
+ let key;
10330
+ try {
10331
+ key = await job.pairing.finish(String(b.code ?? ""));
10332
+ } catch (err) {
10333
+ return fail(res, err), true;
10334
+ }
10335
+ const info = job.pairing.info;
10336
+ const cfg = structuredClone(ctx.runtime.config);
10337
+ let s = b.screenId && cfg.screens.find((x) => x.id === b.screenId) || cfg.screens.find((x) => x.device.driver === "remote" && x.device.uid === info.uid);
10338
+ const hex2 = key.toString("hex");
10339
+ if (s) {
10340
+ const keepHost = s.device.driver === "remote" ? s.device.host : void 0;
10341
+ const keepPort = s.device.driver === "remote" ? s.device.port : void 0;
10342
+ s.device = { driver: "remote", uid: info.uid, id: info.id, key: hex2, ...keepHost ? { host: keepHost } : {}, ...keepPort ? { port: keepPort } : {} };
10343
+ } else {
10344
+ s = remoteScreen(ctx.runtime.registry, info, hex2, ctx.runtime.config.locale === "auto" ? "en" : ctx.runtime.config.locale);
10345
+ cfg.screens.push(s);
10346
+ }
10347
+ ctx.commit(cfg);
10348
+ return ctx.json(res, 200, { ok: true, screenId: s.id }), true;
10349
+ }
10350
+ mm = /^\/api\/screens\/([^/]+)\/remote\/(unpair|ota|logs)$/.exec(p);
10351
+ if (mm) {
10352
+ const id = decodeURIComponent(mm[1]);
10353
+ const r = remoteOf(id);
10354
+ if (!r) return ctx.json(res, 404, { error: "not a remote screen", code: "unknownScreen" }), true;
10355
+ const key = /^[0-9a-f]{64}$/.test(r.device.key ?? "") ? Buffer.from(r.device.key, "hex") : null;
10356
+ const run = async (fn) => {
10357
+ if (r.driver) return r.driver.exclusive(fn);
10358
+ const at = await locate(r.device.uid, r.device.host, r.device.port);
10359
+ if (!at) throw new ScreenError("offline", "that screen is not on the network");
10360
+ return fn(at.host, at.port);
10361
+ };
10362
+ try {
10363
+ if (mm[2] === "unpair" && m === "POST") {
10364
+ let told = false;
10365
+ if (key) {
10366
+ try {
10367
+ await run((h, port) => unpairScreen(h, port, key, r.device.uid));
10368
+ told = true;
10369
+ } catch {
10370
+ }
10371
+ }
10372
+ const cfg = structuredClone(ctx.runtime.config);
10373
+ const s = cfg.screens.find((x) => x.id === id);
10374
+ if (s.device.driver === "remote") delete s.device.key;
10375
+ ctx.commit(cfg);
10376
+ return ctx.json(res, 200, { ok: true, told }), true;
10377
+ }
10378
+ if (!key) return ctx.json(res, 409, { error: "not paired", code: "remote.notPaired" }), true;
10379
+ if (mm[2] === "logs" && m === "GET") return ctx.json(res, 200, { text: await run((h, port) => screenLogs(h, port, key, r.device.uid)) }), true;
10380
+ if (mm[2] === "ota" && m === "POST") {
10381
+ const image2 = await raw(req, 4 * 1024 * 1024);
10382
+ await run((h, port) => otaUpdate(h, port, key, r.device.uid, image2));
10383
+ return ctx.json(res, 200, { ok: true }), true;
10384
+ }
10385
+ } catch (err) {
10386
+ return fail(res, err), true;
10387
+ }
10388
+ }
10389
+ return false;
10390
+ };
10391
+ }
10392
+
10393
+ // packages/server/src/remote-cli.ts
10394
+ var say = (s) => console.log(s);
10395
+ function screenArg(cfg, q3) {
10396
+ const s = cfg.screens.find((x) => x.id === q3 || x.name === q3 || x.device.driver === "remote" && (x.device.uid === q3 || x.device.id === q3));
10397
+ if (!s || s.device.driver !== "remote") throw new Error(`no remote screen "${q3 ?? ""}" in the config (kiosko remote list)`);
10398
+ return s;
10399
+ }
10400
+ async function where(d) {
10401
+ if (d.host) return { host: d.host, port: d.port ?? PORT };
10402
+ const b = browser();
10403
+ const f = b.get(d.uid) ?? (await b.browse(2500)).find((x) => x.uid === d.uid);
10404
+ if (!f) throw new Error(`screen ${d.uid} is not on the network (no mDNS answer)`);
10405
+ return { host: f.address, port: f.port };
10406
+ }
10407
+ async function viaServer(port, path, init) {
10408
+ try {
10409
+ return await fetch(`http://127.0.0.1:${port}${path}`, { ...init, headers: { "x-kiosko": "1", ...init.headers ?? {} } });
10410
+ } catch {
10411
+ return null;
10412
+ }
10413
+ }
10414
+ async function remoteCommand(args, o) {
10415
+ const [sub = "list", a, b] = args.filter((x, i, all) => !x.startsWith("--") && !(i > 0 && all[i - 1].startsWith("--")));
10416
+ const opt2 = (n) => {
10417
+ const i = args.indexOf(n);
10418
+ return i >= 0 ? args[i + 1] : void 0;
10419
+ };
10420
+ const { config: cfg } = loadConfig(o.configPath);
10421
+ try {
10422
+ if (sub === "list") {
10423
+ const found = await browser().browse(2500);
10424
+ if (!found.length) say("no Kiosko remote screen answered on this network (mDNS _kiosko-screen._tcp)");
10425
+ for (const f of found) {
10426
+ const used = cfg.screens.find((s) => s.device.driver === "remote" && s.device.uid === f.uid);
10427
+ say(`${f.id.padEnd(16)} uid ${f.uid} ${f.model} ${f.w}\xD7${f.h} at ${f.rot}\xB0 fw ${f.fw} ${f.paired ? "paired" : "not paired"} ${f.address}:${f.port} (${f.hostname})${used ? ` \u2192 screen "${used.name}"` : ""}`);
10428
+ }
10429
+ for (const s of cfg.screens) if (s.device.driver === "remote" && !found.some((f) => f.uid === s.device.uid)) say(`(screen "${s.name}": ${s.device.id ?? s.device.uid} did not answer)`);
10430
+ return 0;
10431
+ }
10432
+ if (sub === "pair") {
10433
+ if (!a) throw new Error("usage: kiosko remote pair <uid|host> [--screen id]");
10434
+ const isUid = /^[0-9a-f]{12}$/i.test(a);
10435
+ const at = isUid ? await where({ uid: a.toLowerCase() }) : { host: a, port: Number(opt2("--port-screen")) || PORT };
10436
+ const info = await probe(at.host, at.port);
10437
+ say(`${info.id} (${info.model}, uid ${info.uid}) at ${at.host}`);
10438
+ const p = await Pairing.start(at.host, at.port, `Kiosko on ${hostname2()}`.slice(0, 40));
10439
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
10440
+ const code = await rl.question("Code shown on the screen: ");
10441
+ rl.close();
10442
+ const key = (await p.finish(code)).toString("hex");
10443
+ const next = structuredClone(cfg);
10444
+ const target = opt2("--screen") && next.screens.find((s) => s.id === opt2("--screen")) || next.screens.find((s) => s.device.driver === "remote" && s.device.uid === info.uid);
10445
+ if (target) target.device = { driver: "remote", uid: info.uid, id: info.id, key, ...isUid ? {} : { host: at.host } };
10446
+ else next.screens.push(remoteScreen(await o.registry(), info, key, "en", isUid ? void 0 : at.host));
10447
+ saveConfig(normalize(next), o.configPath);
10448
+ say(`paired; saved in ${o.configPath}${target ? ` (screen "${target.name}")` : " as a new screen"}. A Kiosko running here picks it up when it restarts.`);
10449
+ return 0;
10450
+ }
10451
+ if (sub === "ota" || sub === "logs" || sub === "unpair") {
10452
+ const s = screenArg(cfg, a);
10453
+ const id = encodeURIComponent(s.id);
10454
+ const image2 = sub === "ota" ? readFileSync7(b ?? "") : null;
10455
+ if (sub === "ota" && !b) throw new Error("usage: kiosko remote ota <screen> <firmware.bin>");
10456
+ const r = await viaServer(o.port, `/api/screens/${id}/remote/${sub}`, sub === "logs" ? {} : { method: "POST", ...image2 ? { body: new Uint8Array(image2) } : {} });
10457
+ if (r && r.status !== 404) {
10458
+ const j = await r.json();
10459
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
10460
+ say(sub === "logs" ? j.text ?? "" : sub === "ota" ? "updated: the screen restarts into it (and goes back by itself if this Kiosko cannot talk to it)" : "unpaired");
10461
+ return 0;
10462
+ }
10463
+ const key = /^[0-9a-f]{64}$/.test(s.device.key ?? "") ? Buffer.from(s.device.key, "hex") : null;
10464
+ if (!key) throw new Error(`screen "${s.name}" is not paired`);
10465
+ const at = await where(s.device);
10466
+ if (sub === "logs") say(await screenLogs(at.host, at.port, key, s.device.uid));
10467
+ else if (sub === "ota") {
10468
+ let last2 = -1;
10469
+ await otaUpdate(at.host, at.port, key, s.device.uid, image2, (sent, total) => {
10470
+ const pct = Math.floor(sent * 100 / total);
10471
+ if (pct >= last2 + 10) process.stdout.write(`${last2 = pct}% `);
10472
+ });
10473
+ say("\nupdated: the screen restarts into it (and goes back by itself if this Kiosko cannot talk to it)");
10474
+ } else {
10475
+ await unpairScreen(at.host, at.port, key, s.device.uid);
10476
+ const next = structuredClone(cfg);
10477
+ const t2 = next.screens.find((x) => x.id === s.id);
10478
+ if (t2.device.driver === "remote") delete t2.device.key;
10479
+ saveConfig(normalize(next), o.configPath);
10480
+ say("unpaired");
10481
+ }
10482
+ return 0;
10483
+ }
10484
+ say("usage: kiosko remote [list] | pair <uid|host> [--screen id] | ota <screen> <file.bin> | logs <screen> | unpair <screen>");
10485
+ return 2;
10486
+ } catch (err) {
10487
+ console.error(`\u2717 ${err instanceof Error ? err.message : String(err)}`);
10488
+ return 1;
10489
+ } finally {
10490
+ browser().close();
10491
+ }
10492
+ }
10493
+
8601
10494
  // packages/server/src/gallery.ts
8602
10495
  import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync8 } from "node:fs";
8603
10496
  import { join as join13 } from "node:path";
8604
10497
  var HOME_URL = "https://kioskolcd.dev/";
8605
10498
  var RELEASES_URL = "https://github.com/kiosko-lcd/kiosko/releases/latest";
8606
10499
  var MADRID = { latitude: 40.4168, longitude: -3.7038, name: "Madrid" };
8607
- var T = {
10500
+ var T2 = {
8608
10501
  title: { en: "Kiosko widget gallery", es: "Galer\xEDa de widgets de Kiosko", de: "Kiosko-Widget-Galerie", "zh-Hant": "Kiosko \u5C0F\u5DE5\u5177\u5C55\u793A", "zh-Hans": "Kiosko \u5C0F\u7EC4\u4EF6\u5C55\u793A" },
8609
10502
  lede: { en: "{n} widgets, painted with their demo data by the same code that drives the panels.", es: "{n} widgets, pintados con sus datos de muestra por el mismo c\xF3digo que mueve los paneles.", de: "{n} Widgets, mit ihren Demodaten gezeichnet, vom selben Code, der die Panels steuert.", "zh-Hant": "{n} \u500B\u5C0F\u5DE5\u5177\uFF0C\u4EE5\u7BC4\u4F8B\u8CC7\u6599\u7E6A\u88FD\uFF0C\u7528\u7684\u6B63\u662F\u9A45\u52D5\u9762\u677F\u7684\u540C\u4E00\u5957\u7A0B\u5F0F\u78BC\u3002", "zh-Hans": "{n} \u4E2A\u5C0F\u7EC4\u4EF6\uFF0C\u7528\u793A\u4F8B\u6570\u636E\u7ED8\u5236\uFF0C\u7528\u7684\u6B63\u662F\u9A71\u52A8\u526F\u5C4F\u7684\u540C\u4E00\u5957\u4EE3\u7801\u3002" },
8610
10503
  github: { en: "Kiosko on GitHub", es: "Kiosko en GitHub", de: "Kiosko auf GitHub", "zh-Hant": "GitHub \u4E0A\u7684 Kiosko", "zh-Hans": "GitHub \u4E0A\u7684 Kiosko" },
@@ -8664,7 +10557,7 @@ function buildGallery(registry2, o) {
8664
10557
  mkdirSync7(join13(o.out, folder(lang.id)), { recursive: true });
8665
10558
  writeFileSync8(
8666
10559
  join13(o.out, folder(lang.id), "index.html"),
8667
- `<!doctype html><html lang="${lang.id}" dir="${lang.dir}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(L(T.title))}</title>
10560
+ `<!doctype html><html lang="${lang.id}" dir="${lang.dir}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(L(T2.title))}</title>
8668
10561
  <style>
8669
10562
  :root{color-scheme:dark;--bg:#0a0d13;--panel:#121722;--line:rgba(255,255,255,.08);--text:#e7ecf4;--dim:#a3adbf}
8670
10563
  body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
@@ -8681,15 +10574,15 @@ figcaption code{color:#22d3ee;font-size:12px}figcaption span{flex-basis:100%;col
8681
10574
  a{color:#22d3ee}
8682
10575
  p.os{margin-top:14px}p.os b{color:var(--text)}
8683
10576
  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}
8684
- </style></head><body><header><p><a href="${home}">\u2190 Kiosko</a></p><h1>${esc(L(T.title))}</h1><p>${esc(L(T.lede).replace("{n}", String(listedHere.reduce((n, p) => n + p.def.widgets.length, 0))))} <a href="https://github.com/kiosko-lcd/kiosko">${esc(L(T.github))}</a></p><p><a class="try" href="${HOME_URL}demo/?lang=${lang.locale}">${esc(L(T.editor))}</a> &nbsp; <a class="try" href="${HOME_URL}demo/3d/?lang=${lang.locale}">${esc(L(T.in3d))}</a></p><p class="os">${L(T.os).replace("{releases}", RELEASES_URL).replace("{usb}", usb)}</p></header><main>${sections.join("")}</main></body></html>`
10577
+ </style></head><body><header><p><a href="${home}">\u2190 Kiosko</a></p><h1>${esc(L(T2.title))}</h1><p>${esc(L(T2.lede).replace("{n}", String(listedHere.reduce((n, p) => n + p.def.widgets.length, 0))))} <a href="https://github.com/kiosko-lcd/kiosko">${esc(L(T2.github))}</a></p><p><a class="try" href="${HOME_URL}demo/?lang=${lang.locale}">${esc(L(T2.editor))}</a> &nbsp; <a class="try" href="${HOME_URL}demo/3d/?lang=${lang.locale}">${esc(L(T2.in3d))}</a></p><p class="os">${L(T2.os).replace("{releases}", RELEASES_URL).replace("{usb}", usb)}</p></header><main>${sections.join("")}</main></body></html>`
8685
10578
  );
8686
10579
  }
8687
10580
  if (o.pages) {
8688
10581
  const sample = normalize(o.pages);
8689
10582
  const screen = [...sample.screens].sort((a, b) => b.width / b.height - a.width / a.height)[0];
8690
10583
  for (const page of screen?.pages.filter((p) => p.enabled !== false) ?? []) {
8691
- const name = `img/page-${slug2(page.name || page.id)}`;
8692
- data.pages.push({ id: page.id, name: page.name, file: Object.fromEntries(langs.map((l) => [l.id, l.id === first ? `${name}.jpg` : `${name}.${l.id}.jpg`])), width: screen.width, height: screen.height });
10584
+ const name2 = `img/page-${slug2(page.name || page.id)}`;
10585
+ data.pages.push({ id: page.id, name: page.name, file: Object.fromEntries(langs.map((l) => [l.id, l.id === first ? `${name2}.jpg` : `${name2}.${l.id}.jpg`])), width: screen.width, height: screen.height });
8693
10586
  }
8694
10587
  for (const l of langs) {
8695
10588
  const local = normalize({ ...localizeSample(sample, l.locale), locale: l.locale });
@@ -8759,7 +10652,7 @@ function widgetFor(m, reg, notes, modulesDir) {
8759
10652
  }
8760
10653
  return { ...base3, type: "legacy/module", options: { module: m.module, dir: modulesDir, json: m.config ? JSON.stringify(m.config, null, 2) : "" } };
8761
10654
  }
8762
- function columnsPage(name, width, height, mods, rotateMs, reg, notes, modulesDir) {
10655
+ function columnsPage(name2, width, height, mods, rotateMs, reg, notes, modulesDir) {
8763
10656
  const groups = [];
8764
10657
  const byColumn = /* @__PURE__ */ new Map();
8765
10658
  for (const m of mods) {
@@ -8781,7 +10674,7 @@ function columnsPage(name, width, height, mods, rotateMs, reg, notes, modulesDir
8781
10674
  x += w;
8782
10675
  return t2;
8783
10676
  });
8784
- return { id: newId("page"), name, enabled: true, durationMs: 10 * 6e4, when: "always", grid, gravity: "left", background: {}, tiles };
10677
+ return { id: newId("page"), name: name2, enabled: true, durationMs: 10 * 6e4, when: "always", grid, gravity: "left", background: {}, tiles };
8785
10678
  }
8786
10679
  function importAimonitor(old, reg, modeOverride, o = {}) {
8787
10680
  const notes = [];
@@ -8792,19 +10685,19 @@ function importAimonitor(old, reg, modeOverride, o = {}) {
8792
10685
  const device = trcc.frameDir ? { driver: "file", dir: trcc.frameDir, format: "jpeg" } : { driver: "trcc", url: trcc.api?.url ?? "http://127.0.0.1:8099", ...trcc.api?.tokenFile ? { tokenFile: trcc.api.tokenFile } : {}, ...trcc.serial ? { serial: trcc.serial } : {}, ...trcc.deviceKey ? { deviceKey: trcc.deviceKey } : {} };
8793
10686
  const grid = { cols: 24, rows: 6, gap: 10, padding: 10 };
8794
10687
  const W = (type, options2 = {}, title) => ({ id: newId("w"), type, options: options2, ...title ? { title } : {} });
8795
- const T2 = (x, y, w, h, widgets, chrome = "auto", rotateMs = 3e4) => ({ id: newId("tile"), x, y, w, h, widgets, rotateMs, chrome });
10688
+ const T3 = (x, y, w, h, widgets, chrome = "auto", rotateMs = 3e4) => ({ id: newId("tile"), x, y, w, h, widgets, rotateMs, chrome });
8796
10689
  const railOn = old.rail?.enabled !== false && old.usage?.enabled !== false;
8797
10690
  const sysOn = old.system?.enabled !== false;
8798
10691
  const sessionsOpts = { ...old.tile ? { tileMin: old.tile.min, tileMax: old.tile.max, gap: old.tile.gap, detailLines: old.tile.detailLines } : {}, ...old.spineWidth ? { spineWidth: old.spineWidth } : {} };
8799
- const dashTiles = [T2(0, 0, 24, 1, [W("agents/summary")], "bare"), T2(0, 1, railOn ? sysOn ? 13 : 19 : sysOn ? 18 : 24, 5, [W("agents/sessions", sessionsOpts)], "bare")];
8800
- if (sysOn) dashTiles.push(T2(railOn ? 13 : 18, 1, 6, 5, [W("vitals/vitals")], "bare"));
8801
- if (railOn) dashTiles.push(T2(19, 1, 5, 5, [W("usage/rail")], "bare"));
10692
+ const dashTiles = [T3(0, 0, 24, 1, [W("agents/summary")], "bare"), T3(0, 1, railOn ? sysOn ? 13 : 19 : sysOn ? 18 : 24, 5, [W("agents/sessions", sessionsOpts)], "bare")];
10693
+ if (sysOn) dashTiles.push(T3(railOn ? 13 : 18, 1, 6, 5, [W("vitals/vitals")], "bare"));
10694
+ if (railOn) dashTiles.push(T3(19, 1, 5, 5, [W("usage/rail")], "bare"));
8802
10695
  const dashboard = { id: newId("page"), name: "Dashboard", enabled: true, durationMs: old.scene?.alternateMs ?? 10 * 6e4, when: "always", grid, gravity: "none", background: {}, tiles: dashTiles };
8803
10696
  const cardWidgets = (old.modules ?? []).map((m) => widgetFor(m, reg, notes, modulesDir)).filter((w) => !!w);
8804
10697
  if (railOn) cardWidgets.push(W("usage/rail", {}, "Consumo"));
8805
10698
  const side = old.scene?.side === "izquierda" ? "left" : "right";
8806
- const catsTiles = [T2(side === "right" ? 0 : 7, 0, 17, 6, [W("cats/room", { room: old.scene?.room === "rotar" || !old.scene?.room ? "rotate" : old.scene.room })], "bare")];
8807
- if (cardWidgets.length) catsTiles.push(T2(side === "right" ? 17 : 0, 0, 7, 6, cardWidgets, "card", old.timesheet?.alternateMs || 3e4));
10699
+ const catsTiles = [T3(side === "right" ? 0 : 7, 0, 17, 6, [W("cats/room", { room: old.scene?.room === "rotar" || !old.scene?.room ? "rotate" : old.scene.room })], "bare")];
10700
+ if (cardWidgets.length) catsTiles.push(T3(side === "right" ? 17 : 0, 0, 7, 6, cardWidgets, "card", old.timesheet?.alternateMs || 3e4));
8808
10701
  const cats = { id: newId("page"), name: "Cats", enabled: true, durationMs: old.scene?.alternateMs ?? 10 * 6e4, when: "always", grid, gravity: "none", background: {}, tiles: catsTiles };
8809
10702
  const override = (modeOverride ?? "").trim().toLowerCase();
8810
10703
  const mode = ["gatos", "tablero", "alternar"].includes(override) ? override : old.scene?.mode ?? "tablero";
@@ -8992,14 +10885,17 @@ function runService(action, plan) {
8992
10885
  }
8993
10886
 
8994
10887
  // packages/server/src/server.ts
8995
- import { existsSync as existsSync14, readFileSync as readFileSync9, statSync as statSync3 } from "node:fs";
10888
+ import { spawn as spawn2 } from "node:child_process";
10889
+ import { randomBytes as randomBytes4 } from "node:crypto";
10890
+ import { existsSync as existsSync16, openSync, readFileSync as readFileSync12, statSync as statSync3 } from "node:fs";
8996
10891
  import { createServer } from "node:http";
10892
+ import { tmpdir as tmpdir2 } from "node:os";
8997
10893
  import { createRequire as createRequire3 } from "node:module";
8998
- import { dirname as dirname7, extname, join as join17, normalize as normPath, resolve as resolve7 } from "node:path";
10894
+ import { dirname as dirname8, extname, join as join18, normalize as normPath, resolve as resolve7 } from "node:path";
8999
10895
 
9000
10896
  // packages/server/src/plugins-manage.ts
9001
10897
  import { execFile } from "node:child_process";
9002
- import { existsSync as existsSync12, lstatSync as lstatSync2, mkdirSync as mkdirSync9, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "node:fs";
10898
+ import { existsSync as existsSync12, lstatSync as lstatSync2, mkdirSync as mkdirSync9, readFileSync as readFileSync8, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "node:fs";
9003
10899
  import { join as join15, relative as relative2, resolve as resolve6, sep } from "node:path";
9004
10900
  var NPM_NAME = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(@[\w.^~<>=*-]+)?$/i;
9005
10901
  var packageName = (spec) => spec.startsWith("@") ? `@${spec.slice(1).split("@")[0]}` : spec.split("@")[0];
@@ -9016,10 +10912,10 @@ var realNpm = (args, cwd) => new Promise((ok, fail) => {
9016
10912
  const npm2 = process.platform === "win32" ? "npm.cmd" : "npm";
9017
10913
  execFile(npm2, args, { cwd, timeout: 18e4, shell: process.platform === "win32" }, (err, stdout, stderr) => err ? fail(new Error((stderr || err.message).slice(-2e3))) : ok(stdout.slice(-2e3)));
9018
10914
  });
9019
- function installedIntegrity(dir, name) {
10915
+ function installedIntegrity(dir, name2) {
9020
10916
  try {
9021
- const lock = JSON.parse(readFileSync7(join15(dir, "node_modules", ".package-lock.json"), "utf8"));
9022
- return lock.packages?.[`node_modules/${name}`]?.integrity;
10917
+ const lock = JSON.parse(readFileSync8(join15(dir, "node_modules", ".package-lock.json"), "utf8"));
10918
+ return lock.packages?.[`node_modules/${name2}`]?.integrity;
9023
10919
  } catch {
9024
10920
  return void 0;
9025
10921
  }
@@ -9031,7 +10927,7 @@ async function installPlugin(spec, o) {
9031
10927
  const npm2 = o.npm ?? realNpm;
9032
10928
  const r = o.registry;
9033
10929
  const folder = join15(dir, "node_modules", packageName(spec));
9034
- const readPkg = () => existsSync12(join15(folder, "package.json")) ? JSON.parse(readFileSync7(join15(folder, "package.json"), "utf8")) : null;
10930
+ const readPkg = () => existsSync12(join15(folder, "package.json")) ? JSON.parse(readFileSync8(join15(folder, "package.json"), "utf8")) : null;
9035
10931
  const beforePkg = readPkg();
9036
10932
  const beforeId = beforePkg ? packageMeta(beforePkg).id : void 0;
9037
10933
  const output = await npm2(["install", "--no-audit", "--no-fund", "--ignore-scripts", "--save-exact", spec], dir);
@@ -9084,8 +10980,8 @@ async function removePlugin(id, o) {
9084
10980
  if (rel.startsWith("..") || rel === "") return { removed: false, reason: `it was loaded from ${origin}, outside the plugins folder` };
9085
10981
  const parts = rel.split(sep);
9086
10982
  if (parts[0] === "node_modules") {
9087
- const name = parts[1].startsWith("@") ? `${parts[1]}/${parts[2]}` : parts[1];
9088
- await (o.npm ?? realNpm)(["uninstall", "--no-audit", "--no-fund", name], dir);
10983
+ const name2 = parts[1].startsWith("@") ? `${parts[1]}/${parts[2]}` : parts[1];
10984
+ await (o.npm ?? realNpm)(["uninstall", "--no-audit", "--no-fund", name2], dir);
9089
10985
  } else {
9090
10986
  const top = join15(dir, parts[0]);
9091
10987
  if (!lstatSync2(top).isSymbolicLink()) return { removed: false, reason: `${top} is a folder you put there: delete it yourself if you mean it` };
@@ -9102,7 +10998,7 @@ async function reloadPlugin(id, o) {
9102
10998
  }
9103
10999
 
9104
11000
  // packages/server/src/store.ts
9105
- import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync8, renameSync as renameSync4, writeFileSync as writeFileSync11 } from "node:fs";
11001
+ import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync9, renameSync as renameSync4, writeFileSync as writeFileSync11 } from "node:fs";
9106
11002
  import { dirname as dirname6, join as join16 } from "node:path";
9107
11003
  var STORE_URL = "https://kioskolcd.dev/store/v1/";
9108
11004
  function shipped(...candidates) {
@@ -9112,7 +11008,7 @@ function shipped(...candidates) {
9112
11008
  function snapshotIndex() {
9113
11009
  const file = shipped(join16(import.meta.dirname, "../assets/store-index.json"), join16(import.meta.dirname, "assets/store-index.json"));
9114
11010
  try {
9115
- return file ? JSON.parse(readFileSync8(file, "utf8")) : null;
11011
+ return file ? JSON.parse(readFileSync9(file, "utf8")) : null;
9116
11012
  } catch {
9117
11013
  return null;
9118
11014
  }
@@ -9121,7 +11017,7 @@ var schema;
9121
11017
  function indexSchema() {
9122
11018
  if (schema !== void 0) return schema;
9123
11019
  const file = shipped(join16(import.meta.dirname, "../../core/schema/store-index.json"), join16(import.meta.dirname, "assets/store-index.schema.json"));
9124
- schema = file ? JSON.parse(readFileSync8(file, "utf8")) : null;
11020
+ schema = file ? JSON.parse(readFileSync9(file, "utf8")) : null;
9125
11021
  return schema;
9126
11022
  }
9127
11023
  function indexProblem(x) {
@@ -9153,7 +11049,7 @@ var StoreCatalog = class {
9153
11049
  }
9154
11050
  readCache() {
9155
11051
  try {
9156
- const c = JSON.parse(readFileSync8(this.file, "utf8"));
11052
+ const c = JSON.parse(readFileSync9(this.file, "utf8"));
9157
11053
  return indexProblem(c.index) ? null : c;
9158
11054
  } catch {
9159
11055
  return null;
@@ -9218,10 +11114,10 @@ var StoreCatalog = class {
9218
11114
  };
9219
11115
 
9220
11116
  // packages/server/src/homeassistant.ts
9221
- import { hostname } from "node:os";
11117
+ import { hostname as hostname3 } from "node:os";
9222
11118
 
9223
11119
  // packages/server/src/mqtt.ts
9224
- import { EventEmitter as EventEmitter2 } from "node:events";
11120
+ import { EventEmitter as EventEmitter3 } from "node:events";
9225
11121
  import { connect as tcp } from "node:net";
9226
11122
  import { connect as tls } from "node:tls";
9227
11123
  var RETRY_MS2 = [2e3, 5e3, 1e4, 3e4, 6e4];
@@ -9294,7 +11190,7 @@ var CONNACK_ERRORS = {
9294
11190
  4: "wrong user name or password",
9295
11191
  5: "not authorised"
9296
11192
  };
9297
- var MqttClient = class extends EventEmitter2 {
11193
+ var MqttClient = class extends EventEmitter3 {
9298
11194
  state = "connecting";
9299
11195
  error = null;
9300
11196
  sock = null;
@@ -9407,14 +11303,14 @@ var MqttClient = class extends EventEmitter2 {
9407
11303
  this.ping();
9408
11304
  }, every);
9409
11305
  }
9410
- drop(why, refused = false) {
11306
+ drop(why2, refused = false) {
9411
11307
  if (this.closed) return;
9412
11308
  this.clear();
9413
11309
  const s = this.sock;
9414
11310
  this.sock = null;
9415
11311
  s?.destroy();
9416
11312
  this.awaitingPong = false;
9417
- this.set("error", why);
11313
+ this.set("error", why2);
9418
11314
  const ms = refused ? 5 * 6e4 : RETRY_MS2[Math.min(this.attempt++, RETRY_MS2.length - 1)];
9419
11315
  this.later(() => this.open(), ms);
9420
11316
  }
@@ -9435,10 +11331,10 @@ function pageOptions(screen, auto) {
9435
11331
  const byName = /* @__PURE__ */ new Map([[auto, null]]);
9436
11332
  const nameOf = /* @__PURE__ */ new Map();
9437
11333
  for (const p of screen.pages.filter((x) => x.enabled)) {
9438
- let name = p.name.trim() || p.id;
9439
- for (let i = 2; byName.has(name); i++) name = `${p.name} (${i})`;
9440
- byName.set(name, p.id);
9441
- nameOf.set(p.id, name);
11334
+ let name2 = p.name.trim() || p.id;
11335
+ for (let i = 2; byName.has(name2); i++) name2 = `${p.name} (${i})`;
11336
+ byName.set(name2, p.id);
11337
+ nameOf.set(p.id, name2);
9442
11338
  }
9443
11339
  return { options: [...byName.keys()], byName, nameOf };
9444
11340
  }
@@ -9501,7 +11397,7 @@ var HomeAssistantBridge = class {
9501
11397
  const base3 = `kiosko/${want.nodeId}`;
9502
11398
  const c = this.makeClient({
9503
11399
  url: want.broker,
9504
- clientId: `kiosko-${want.nodeId}-${hostname().slice(0, 20)}`.slice(0, 23),
11400
+ clientId: `kiosko-${want.nodeId}-${hostname3().slice(0, 20)}`.slice(0, 23),
9505
11401
  ...want.username ? { username: want.username } : {},
9506
11402
  ...want.password ? { password: want.password } : {},
9507
11403
  keepalive: 30,
@@ -9601,9 +11497,9 @@ var HomeAssistantBridge = class {
9601
11497
  });
9602
11498
  for (const slot of screen.interludes) {
9603
11499
  const def = this.runtime.registry.interlude(slot.type);
9604
- const name = def ? this.loc(def.name) || slot.type : slot.type;
11500
+ const name2 = def ? this.loc(def.name) || slot.type : slot.type;
9605
11501
  put("button", `${sid}_${slug3(slot.id)}`, {
9606
- name: `${this.loc(NAMES.interlude)}: ${name}`,
11502
+ name: `${this.loc(NAMES.interlude)}: ${name2}`,
9607
11503
  unique_id: id(slug3(slot.id)),
9608
11504
  icon: "mdi:play-circle-outline",
9609
11505
  command_topic: `${this.base}/${sid}/interlude/${slot.id}/press`,
@@ -9678,6 +11574,483 @@ var HomeAssistantBridge = class {
9678
11574
  }
9679
11575
  };
9680
11576
 
11577
+ // packages/server/src/install-kind.ts
11578
+ import { existsSync as existsSync14, readFileSync as readFileSync10, realpathSync } from "node:fs";
11579
+ import { posix, win32 as win323 } from "node:path";
11580
+ function detectInstall(i) {
11581
+ const exists = i.exists ?? existsSync14;
11582
+ const read = i.readFile ?? ((p) => readFileSync10(p, "utf8"));
11583
+ const win = i.platform === "win32";
11584
+ const P2 = win ? win323 : posix;
11585
+ const cli = i.cli;
11586
+ const service2 = detectService(i.platform, i.env, read);
11587
+ const base3 = { cli, service: service2, platform: i.platform };
11588
+ const norm = (p) => win ? p.toLowerCase() : p;
11589
+ const gitUp = (from) => {
11590
+ for (let d = from, n = 0; n < 8; n++) {
11591
+ if (exists(P2.join(d, ".git"))) return d;
11592
+ const up = P2.dirname(d);
11593
+ if (up === d) break;
11594
+ d = up;
11595
+ }
11596
+ return null;
11597
+ };
11598
+ if (cli.endsWith(".ts")) return { ...base3, kind: "source", dir: gitUp(P2.dirname(cli)) ?? P2.resolve(P2.dirname(cli), "..", "..", "..") };
11599
+ const dir = P2.dirname(cli);
11600
+ if (win && P2.basename(dir).toLowerCase() === "app") {
11601
+ const app = P2.dirname(dir);
11602
+ if (exists(P2.join(app, "kiosko.cmd")) && exists(P2.join(app, "unins000.exe")) && norm(i.execPath) === norm(P2.join(app, "node.exe"))) {
11603
+ const local = i.env.LOCALAPPDATA && norm(app).startsWith(norm(P2.join(i.env.LOCALAPPDATA, "Programs") + P2.sep));
11604
+ return { ...base3, kind: "windows-installer", dir: app, perUser: !!local };
11605
+ }
11606
+ }
11607
+ const checkout = gitUp(dir);
11608
+ if (checkout && !/[\\/]node_modules[\\/]/.test(dir)) return { ...base3, kind: "source", dir: checkout };
11609
+ if (/[\\/]_npx[\\/]/.test(dir)) return { ...base3, kind: "npx", dir };
11610
+ if (P2.basename(dir) === "kiosko" && P2.basename(P2.dirname(dir)) === "node_modules") {
11611
+ const nm = P2.dirname(dir);
11612
+ const prefix = win ? P2.dirname(nm) : P2.basename(P2.dirname(nm)) === "lib" ? P2.dirname(P2.dirname(nm)) : null;
11613
+ const shim = prefix && (win ? exists(P2.join(prefix, "kiosko.cmd")) : exists(P2.join(prefix, "bin", "kiosko")));
11614
+ if (prefix && shim) return { ...base3, kind: "npm-global", dir, prefix };
11615
+ }
11616
+ return { ...base3, kind: "other", dir };
11617
+ }
11618
+ function detectService(platform3, env, read) {
11619
+ if (platform3 === "linux") {
11620
+ try {
11621
+ if (/\/kiosko\.service(\/|$)/m.test(read("/proc/self/cgroup"))) return "systemd";
11622
+ } catch {
11623
+ }
11624
+ return null;
11625
+ }
11626
+ if (platform3 === "darwin") return env.XPC_SERVICE_NAME === "dev.kiosko" ? "launchd" : null;
11627
+ return null;
11628
+ }
11629
+ function currentInstall() {
11630
+ let cli = process.argv[1] ?? "";
11631
+ try {
11632
+ cli = realpathSync(cli);
11633
+ } catch {
11634
+ }
11635
+ return detectInstall({ cli, execPath: process.execPath, platform: process.platform, env: process.env });
11636
+ }
11637
+ var npmInstallCommand = (version, registry2) => `npm install -g kiosko@${version}${registry2 && registry2 !== REGISTRY ? ` --registry=${registry2}` : ""}`;
11638
+ function updateInstructions(info, version, registry2) {
11639
+ const url2 = releasePage(version);
11640
+ switch (info.kind) {
11641
+ case "windows-installer":
11642
+ return { kind: info.kind, version, url: url2, download: releaseAsset(version, windowsInstallerName(version)) };
11643
+ case "source":
11644
+ return { kind: info.kind, version, url: url2, command: "git pull && npm install && npm run web:build" };
11645
+ case "npx":
11646
+ return { kind: info.kind, version, url: url2, command: `npx kiosko@${version} start` };
11647
+ default:
11648
+ return { kind: info.kind, version, url: url2, command: npmInstallCommand(version, registry2), ...info.platform === "win32" ? { stopFirst: true } : {} };
11649
+ }
11650
+ }
11651
+ function updateBlocker(info, o = {}) {
11652
+ if (o.demo) return "demo";
11653
+ if (info.kind === "windows-installer") return null;
11654
+ if (info.kind !== "npm-global") return info.kind;
11655
+ if (info.platform === "win32") return "npmWindows";
11656
+ return null;
11657
+ }
11658
+
11659
+ // packages/server/src/self-update.ts
11660
+ import { spawn } from "node:child_process";
11661
+ import { createHash as createHash3 } from "node:crypto";
11662
+ import { createReadStream, createWriteStream, existsSync as existsSync15, mkdirSync as mkdirSync11, readFileSync as readFileSync11, realpathSync as realpathSync2, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "node:fs";
11663
+ import { dirname as dirname7, join as join17, win32 as win324 } from "node:path";
11664
+ import { Readable, Transform } from "node:stream";
11665
+ import { pipeline } from "node:stream/promises";
11666
+ var UpdateError = class extends Error {
11667
+ code;
11668
+ constructor(code, message) {
11669
+ super(message);
11670
+ this.code = code;
11671
+ this.name = "UpdateError";
11672
+ }
11673
+ };
11674
+ var tail = (s, n = 600) => (s.length > n ? `\u2026${s.slice(-n)}` : s).trim();
11675
+ var why = (s, n = 300) => s.split(/\r?\n/).map((l) => l.trim()).find((l) => /^(\w*Error|npm (ERR|error))\b/.test(l))?.slice(0, n) ?? tail(s, n);
11676
+ var isVersion = (v) => typeof v === "string" && !!parseVersion(v) && /^\d+\.\d+\.\d+(-[\w.]+)?$/.test(v);
11677
+ function lastJson(out) {
11678
+ for (const line of out.split(/\r?\n/).reverse()) {
11679
+ const l = line.trim();
11680
+ if (!l.startsWith("{")) continue;
11681
+ try {
11682
+ return JSON.parse(l);
11683
+ } catch {
11684
+ }
11685
+ }
11686
+ return null;
11687
+ }
11688
+ function judgeSelfCheck(now, next, target) {
11689
+ if (next.version !== target) return { ok: false, why: `the new Kiosko says it is ${next.version}, not ${target}`, warnings: [] };
11690
+ const refusedIds = new Set(next.refused.map((r) => r.id).filter(Boolean));
11691
+ const has = new Set(next.plugins.map((p) => p.id));
11692
+ const missing = now.ids.filter((id) => !has.has(id) && !refusedIds.has(id));
11693
+ const fresh = next.problems.filter((p) => !now.problems.includes(p.message) && !next.refused.some((r) => r.origin === p.origin));
11694
+ const warnings = next.refused.filter((r) => r.id && now.ids.includes(r.id)).map((r) => `${r.id}: ${r.reason}`);
11695
+ if (missing.length || fresh.length) return { ok: false, why: [missing.length ? `plugins that would not load: ${missing.join(", ")}` : "", ...fresh.map((p) => `${p.origin}: ${p.message}`)].filter(Boolean).join("; "), warnings };
11696
+ return { ok: true, warnings };
11697
+ }
11698
+ function parseSha256File(text3, name2) {
11699
+ for (const line of text3.split(/\r?\n/)) {
11700
+ const m = /^([a-f0-9]{64})(?:\s+\*?(.+?))?\s*$/i.exec(line.trim());
11701
+ if (m && (!m[2] || m[2] === name2)) return m[1].toLowerCase();
11702
+ }
11703
+ return null;
11704
+ }
11705
+ async function sha256File(file) {
11706
+ const h = createHash3("sha256");
11707
+ await pipeline(createReadStream(file), h);
11708
+ return h.digest("hex");
11709
+ }
11710
+ function restartHow(info, o) {
11711
+ if (info.kind === "windows-installer") return "installer";
11712
+ if (info.service === "systemd") return "systemd";
11713
+ if (info.service === "launchd") return "launchd";
11714
+ if (o.tty || o.pid === 1) return "manual";
11715
+ return "handover";
11716
+ }
11717
+ function installerArgs(perUser, log) {
11718
+ return [...perUser ? ["/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/CURRENTUSER"] : [], `/LOG=${log}`];
11719
+ }
11720
+ function windowsUpgradeScript(o) {
11721
+ const q3 = (s) => `"${s}"`;
11722
+ const kcmd = win324.join(o.dir, "kiosko.cmd");
11723
+ const up = `curl.exe -s -o nul -m 2 http://127.0.0.1:${o.port}/api/version`;
11724
+ return [
11725
+ "@echo off",
11726
+ // Paths with accents (a user's name): the lines after this one are read as UTF-8.
11727
+ "chcp 65001 >nul",
11728
+ "rem Written by Kiosko to update itself: runs the installer, then starts Kiosko again.",
11729
+ `${q3(o.exe)} ${o.args.map((a) => a.startsWith("/LOG=") ? `/LOG=${q3(a.slice(5))}` : a).join(" ")}`,
11730
+ ...o.service ? [`schtasks /Query /TN Kiosko >nul 2>&1 || call ${q3(kcmd)} service install >> ${q3(o.log)} 2>&1`] : [],
11731
+ "for /l %%i in (1,1,20) do (",
11732
+ ` ${up} && goto :eof`,
11733
+ " ping -n 2 127.0.0.1 >nul",
11734
+ ")",
11735
+ o.service ? "schtasks /Run /TN Kiosko >nul 2>&1" : `${q3(kcmd)} start >> ${q3(o.log)} 2>&1`,
11736
+ ""
11737
+ ].join("\r\n");
11738
+ }
11739
+ var idle = (from) => ({ state: "idle", target: null, from, method: null, steps: [], error: null, rolledBack: false, restart: null, sha256: null, warnings: [], logFile: null });
11740
+ var KioskoUpdater = class {
11741
+ status;
11742
+ file = null;
11743
+ /** This update's log lines, carried across the restart in the marker. */
11744
+ lines = [];
11745
+ d;
11746
+ constructor(d) {
11747
+ this.d = d;
11748
+ this.status = idle(d.current);
11749
+ }
11750
+ get now() {
11751
+ return (this.d.now ?? Date.now)();
11752
+ }
11753
+ set(patch) {
11754
+ this.status = { ...this.status, ...patch };
11755
+ this.d.changed(this.status);
11756
+ }
11757
+ step(code, ok, detail) {
11758
+ const steps = [...this.status.steps];
11759
+ const open2 = steps.findLastIndex((s2) => s2.code === code && s2.ok === null);
11760
+ const keep = detail ?? (open2 >= 0 ? steps[open2].detail : void 0);
11761
+ const s = { at: this.now, code, ok, ...keep ? { detail: keep } : {} };
11762
+ if (open2 >= 0 && ok !== null) steps[open2] = s;
11763
+ else steps.push(s);
11764
+ if (ok !== null || detail) this.say(`${code}${ok === false ? " failed" : ok ? " ok" : ""}${detail ? `: ${detail}` : ""}`);
11765
+ this.set({ steps });
11766
+ }
11767
+ say(line) {
11768
+ this.lines.push(line);
11769
+ this.d.log(line);
11770
+ }
11771
+ get busy() {
11772
+ return this.status.state === "working" || this.status.state === "restarting";
11773
+ }
11774
+ /** npm next to this Node (nvm, Homebrew…), else the one on the PATH. */
11775
+ npm() {
11776
+ const here = join17(dirname7(this.d.node), process.platform === "win32" ? "npm.cmd" : "npm");
11777
+ return existsSync15(here) ? here : process.platform === "win32" ? "npm.cmd" : "npm";
11778
+ }
11779
+ registryArgs() {
11780
+ return this.d.registry && this.d.registry !== REGISTRY ? [`--registry=${this.d.registry}`] : [];
11781
+ }
11782
+ /** Starts an update to `version` (the newest the check found). Resolves when it ends (or is ready to confirm, on Windows). */
11783
+ async start(version) {
11784
+ if (this.busy) throw new UpdateError("busy", "an update is already under way");
11785
+ if (!isVersion(version) || compareVersions(version, this.d.current) <= 0) throw new UpdateError("noUpdate", `${String(version)} is not newer than ${this.d.current}`);
11786
+ const method = this.d.install.kind === "windows-installer" ? "windows" : "npm";
11787
+ if (this.status.state === "ready" && this.status.target === version) return this.status;
11788
+ this.discard();
11789
+ this.status = { ...idle(this.d.current), state: "working", target: version, method };
11790
+ this.lines = [];
11791
+ this.say(`updating Kiosko ${this.d.current} \u2192 ${version} (${this.d.install.kind}, ${this.d.install.dir})`);
11792
+ this.d.changed(this.status);
11793
+ try {
11794
+ if (method === "windows") await this.downloadInstaller(version);
11795
+ else await this.viaNpm(version);
11796
+ } catch (err) {
11797
+ const e = err instanceof UpdateError ? err : new UpdateError("failed", err instanceof Error ? err.message : String(err));
11798
+ this.d.log(`update failed (${e.code}): ${e.message}`);
11799
+ this.set({ state: "failed", error: { code: e.code, detail: e.message } });
11800
+ }
11801
+ return this.status;
11802
+ }
11803
+ // ---------- npm ----------
11804
+ async viaNpm(version) {
11805
+ const { install, current } = this.d;
11806
+ if (install.kind !== "npm-global" || !install.prefix) throw new UpdateError("cantUpdate", `this Kiosko is not a global npm install (${install.kind})`);
11807
+ const npm2 = this.npm();
11808
+ this.step("prefix", null);
11809
+ const pr = await this.d.run(npm2, ["prefix", "-g"], { timeoutMs: 3e4 });
11810
+ const real = (p) => {
11811
+ try {
11812
+ return realpathSync2(p);
11813
+ } catch {
11814
+ return p;
11815
+ }
11816
+ };
11817
+ const prefix = pr.stdout.trim().split(/\r?\n/).at(-1) ?? "";
11818
+ if (pr.code !== 0 || real(prefix) !== real(install.prefix)) {
11819
+ this.step("prefix", false, `npm installs into ${prefix || "(npm did not say)"}, but this Kiosko runs from ${install.prefix}`);
11820
+ throw new UpdateError("prefixMismatch", `npm's global folder is ${prefix || "unknown"}, not ${install.prefix}: update it by hand with that npm`);
11821
+ }
11822
+ this.step("prefix", true, prefix);
11823
+ this.step("install", null, `npm install -g kiosko@${version}${this.registryArgs().length ? ` ${this.registryArgs()[0]}` : ""}`);
11824
+ const inst = await this.d.run(npm2, ["install", "-g", "--no-audit", "--no-fund", `kiosko@${version}`, ...this.registryArgs()], { timeoutMs: 15 * 6e4 });
11825
+ if (inst.code !== 0) {
11826
+ this.step("install", false, tail(inst.stderr || inst.stdout));
11827
+ await this.rollback(current, false);
11828
+ throw new UpdateError("installFailed", `npm could not install kiosko@${version}: ${why(inst.stderr || inst.stdout)}`);
11829
+ }
11830
+ this.step("install", true);
11831
+ const problem = await this.verify(version);
11832
+ if (problem) {
11833
+ await this.rollback(current, true);
11834
+ throw new UpdateError("verifyFailed", problem);
11835
+ }
11836
+ await this.restart(version);
11837
+ }
11838
+ /** null if the installed Kiosko is `version` and its dry run loads what runs now; else why not. */
11839
+ async verify(version) {
11840
+ const cli = this.d.install.cli;
11841
+ this.step("verify", null);
11842
+ const v = await this.d.run(this.d.node, [cli, "--version"], { timeoutMs: 6e4 });
11843
+ const said = v.stdout.trim().split(/\r?\n/).at(-1)?.trim() ?? "";
11844
+ if (v.code !== 0 || said !== version) {
11845
+ const problem = v.code !== 0 ? `the new Kiosko does not start: ${why(v.stderr || v.stdout)}` : `the installed Kiosko says ${said || "nothing"}, not ${version}`;
11846
+ this.step("verify", false, problem);
11847
+ return problem;
11848
+ }
11849
+ this.step("verify", true, `kiosko --version: ${said}`);
11850
+ this.step("selfCheck", null);
11851
+ const c = await this.d.run(this.d.node, [cli, "self-check", "--json"], { timeoutMs: 12e4, env: { ...process.env, KIOSKO_QUIET: "1" } });
11852
+ const report = lastJson(c.stdout);
11853
+ if (c.code !== 0 && !report) {
11854
+ const problem = `the new Kiosko failed loading its plugins: ${why(c.stderr || c.stdout)}`;
11855
+ this.step("selfCheck", false, problem);
11856
+ return problem;
11857
+ }
11858
+ if (report?.kiosko !== "self-check") {
11859
+ this.step("selfCheck", true, "no dry run in that version: checked its version only");
11860
+ return null;
11861
+ }
11862
+ const j = judgeSelfCheck(this.d.loaded(), report, version);
11863
+ if (j.warnings.length) this.set({ warnings: j.warnings });
11864
+ if (!j.ok) {
11865
+ this.step("selfCheck", false, j.why);
11866
+ return j.why ?? "the dry run failed";
11867
+ }
11868
+ this.step("selfCheck", true, `${report.plugins.length} plugins load${j.warnings.length ? `; not with this version: ${j.warnings.join("; ")}` : ""}`);
11869
+ return null;
11870
+ }
11871
+ /** Puts `version` back (after a failed install or check), and checks it is. */
11872
+ async rollback(version, needed) {
11873
+ if (!needed) {
11874
+ const v2 = await this.d.run(this.d.node, [this.d.install.cli, "--version"], { timeoutMs: 6e4 }).catch(() => ({ code: 1, stdout: "", stderr: "" }));
11875
+ if (v2.code === 0 && v2.stdout.trim().split(/\r?\n/).at(-1)?.trim() === version) return;
11876
+ }
11877
+ this.step("rollback", null, `npm install -g kiosko@${version}`);
11878
+ const r = await this.d.run(this.npm(), ["install", "-g", "--no-audit", "--no-fund", `kiosko@${version}`, ...this.registryArgs()], { timeoutMs: 15 * 6e4 });
11879
+ const v = r.code === 0 ? await this.d.run(this.d.node, [this.d.install.cli, "--version"], { timeoutMs: 6e4 }) : null;
11880
+ if (v && v.code === 0 && v.stdout.trim().split(/\r?\n/).at(-1)?.trim() === version) {
11881
+ this.step("rollback", true, `${version} is installed again`);
11882
+ this.set({ rolledBack: true });
11883
+ return;
11884
+ }
11885
+ this.step("rollback", false, tail(r.stderr || r.stdout || "the previous version did not come back"));
11886
+ throw new UpdateError("rollbackFailed", `the update failed and ${version} could not be installed again: this Kiosko keeps running, but before restarting it run: npm install -g kiosko@${version}`);
11887
+ }
11888
+ async restart(version) {
11889
+ const how = this.d.restartHow;
11890
+ this.d.mark?.({ from: this.d.current, to: version, at: this.now, how, lines: this.lines.slice(-30) });
11891
+ if (how === "manual") {
11892
+ this.step("restart", true, `installed; restart Kiosko to use ${version}`);
11893
+ this.set({ state: "done", restart: "manual" });
11894
+ return;
11895
+ }
11896
+ this.set({ state: "restarting", restart: how });
11897
+ if (how === "systemd" || how === "launchd") {
11898
+ const uid = process.getuid?.() ?? 0;
11899
+ const [cmd2, args] = how === "systemd" ? ["systemctl", ["--user", "--no-block", "restart", "kiosko.service"]] : ["launchctl", ["kickstart", "-k", `gui/${uid}/dev.kiosko`]];
11900
+ this.step("restart", null, `${cmd2} ${args.join(" ")}`);
11901
+ const r = await this.d.run(cmd2, args, { timeoutMs: 3e4 });
11902
+ if (r.code !== 0) {
11903
+ this.step("restart", false, tail(r.stderr || r.stdout));
11904
+ this.set({ state: "done", restart: "manual" });
11905
+ throw new UpdateError("restartFailed", `${version} is installed, but the service did not restart (${tail(r.stderr || r.stdout, 200)}): restart Kiosko yourself`);
11906
+ }
11907
+ return;
11908
+ }
11909
+ const h = this.d.handover;
11910
+ if (!h) throw new UpdateError("restartFailed", "no way to restart here");
11911
+ this.step("restart", null, `handing over to ${version}; its output goes to ${h.logFile}`);
11912
+ this.set({ logFile: h.logFile });
11913
+ await h.release();
11914
+ const child = h.spawn();
11915
+ let gone = false;
11916
+ void child.exited.then(() => gone = true);
11917
+ const sleep = this.d.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
11918
+ const until = this.now + (this.d.handoverTimeoutMs ?? 6e4);
11919
+ while (this.now < until && !gone) {
11920
+ await sleep(500);
11921
+ const p = await h.probe().catch(() => null);
11922
+ if (p && p.version === version && p.instance !== h.instance) {
11923
+ this.d.log(`Kiosko ${version} is running; this one (${this.d.current}) stops`);
11924
+ h.exit();
11925
+ return;
11926
+ }
11927
+ }
11928
+ child.kill();
11929
+ await h.reclaim();
11930
+ this.d.mark?.(null);
11931
+ this.step("restart", false, gone ? `the new Kiosko stopped right away (see ${h.logFile})` : "the new Kiosko did not answer in time");
11932
+ await this.rollback(this.d.current, true).catch((err) => this.d.log(String(err instanceof Error ? err.message : err)));
11933
+ throw new UpdateError("restartFailed", `Kiosko ${version} did not start (see ${h.logFile}); ${this.d.current} keeps running`);
11934
+ }
11935
+ // ---------- Windows ----------
11936
+ async downloadInstaller(version) {
11937
+ const name2 = windowsInstallerName(version);
11938
+ const exeUrl = releaseAsset(version, name2);
11939
+ const dir = join17(this.d.tmpDir, `kiosko-update-${version}`);
11940
+ rmSync4(dir, { recursive: true, force: true });
11941
+ mkdirSync11(dir, { recursive: true });
11942
+ const file = join17(dir, name2);
11943
+ this.step("download", null, exeUrl);
11944
+ let expected;
11945
+ try {
11946
+ const r = await this.d.fetch(`${exeUrl}.sha256`, { redirect: "follow" });
11947
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
11948
+ expected = parseSha256File((await r.text()).slice(0, 4096), name2);
11949
+ } catch (err) {
11950
+ this.step("download", false, `${name2}.sha256: ${err instanceof Error ? err.message : String(err)}`);
11951
+ throw new UpdateError("downloadFailed", `could not download ${name2}.sha256 from GitHub: download the installer from the release page instead`);
11952
+ }
11953
+ if (!expected) {
11954
+ this.step("download", false, `${name2}.sha256 names no checksum for ${name2}`);
11955
+ throw new UpdateError("hashMissing", `the release has no usable checksum for ${name2}: not running it`);
11956
+ }
11957
+ const hash = createHash3("sha256");
11958
+ let size = 0;
11959
+ try {
11960
+ const r = await this.d.fetch(exeUrl, { redirect: "follow" });
11961
+ if (!r.ok || !r.body) throw new Error(`HTTP ${r.status}`);
11962
+ const count = new Transform({
11963
+ transform(chunk, _e, cb) {
11964
+ size += chunk.length;
11965
+ if (size > 500 * 1024 * 1024) return cb(new Error("larger than 500 MB: not an installer of ours"));
11966
+ hash.update(chunk);
11967
+ cb(null, chunk);
11968
+ }
11969
+ });
11970
+ await pipeline(Readable.fromWeb(r.body), count, createWriteStream(file));
11971
+ } catch (err) {
11972
+ rmSync4(dir, { recursive: true, force: true });
11973
+ this.step("download", false, err instanceof Error ? err.message : String(err));
11974
+ throw new UpdateError("downloadFailed", `could not download ${name2}: ${err instanceof Error ? err.message : String(err)}`);
11975
+ }
11976
+ this.step("download", true, `${(size / 1024 / 1024).toFixed(1)} MB`);
11977
+ const got = hash.digest("hex");
11978
+ if (got !== expected) {
11979
+ rmSync4(dir, { recursive: true, force: true });
11980
+ this.step("hash", false, `sha256 ${got}, the release says ${expected}`);
11981
+ throw new UpdateError("hashMismatch", `${name2} is not the file the release publishes (sha256 ${got.slice(0, 12)}\u2026, expected ${expected.slice(0, 12)}\u2026): deleted, not run`);
11982
+ }
11983
+ this.step("hash", true, `sha256 ${got}`);
11984
+ this.file = file;
11985
+ this.set({ state: "ready", sha256: got });
11986
+ }
11987
+ /** Windows, after the person confirms: checks the file once more and runs the installer. */
11988
+ async confirm(version) {
11989
+ if (this.status.state !== "ready" || this.status.target !== version || !this.file) throw new UpdateError("notReady", `no verified installer of ${String(version)} waiting`);
11990
+ const got = await sha256File(this.file).catch(() => null);
11991
+ if (got !== this.status.sha256) {
11992
+ this.discard();
11993
+ this.set({ state: "failed", error: { code: "hashMismatch", detail: "the downloaded installer changed since it was checked: deleted, not run" } });
11994
+ return this.status;
11995
+ }
11996
+ const info = this.d.install;
11997
+ const dir = dirname7(this.file);
11998
+ const service2 = await this.d.serviceTask?.().catch(() => false) ?? false;
11999
+ const script = join17(dir, "kiosko-upgrade.cmd");
12000
+ const log = win324.join(this.d.home, "kiosko.log");
12001
+ writeFileSync12(script, windowsUpgradeScript({ exe: this.file, args: installerArgs(!!info.perUser, join17(dir, "install.log")), dir: info.dir, service: service2, port: this.d.port, log }));
12002
+ this.d.mark?.({ from: this.d.current, to: version, at: this.now, how: "installer", lines: this.lines.slice(-30) });
12003
+ this.step("launch", true, `${this.file} ${installerArgs(!!info.perUser, join17(dir, "install.log")).join(" ")}${info.perUser ? "" : " (the wizard: this Kiosko is not installed per user)"}`);
12004
+ this.set({ state: "restarting", restart: "installer" });
12005
+ this.d.launch?.(script);
12006
+ return this.status;
12007
+ }
12008
+ /** Forgets a downloaded installer (Cancel in the editor, or a new start). */
12009
+ discard() {
12010
+ if (this.file) rmSync4(dirname7(this.file), { recursive: true, force: true });
12011
+ this.file = null;
12012
+ if (this.status.state === "ready") this.set(idle(this.d.current));
12013
+ }
12014
+ };
12015
+ var realRun = (cmd2, args, o = {}) => new Promise((ok) => {
12016
+ const shell = process.platform === "win32" && /\.cmd$/i.test(cmd2);
12017
+ const child = spawn(shell && /\s/.test(cmd2) ? `"${cmd2}"` : cmd2, args, { env: o.env ?? process.env, shell, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
12018
+ let stdout = "";
12019
+ let stderr = "";
12020
+ child.stdout.on("data", (d) => stdout = (stdout + d).slice(-2e4));
12021
+ child.stderr.on("data", (d) => stderr = (stderr + d).slice(-2e4));
12022
+ const t2 = setTimeout(() => child.kill(), o.timeoutMs ?? 12e4);
12023
+ child.on("error", (err) => {
12024
+ clearTimeout(t2);
12025
+ ok({ code: 127, stdout, stderr: stderr || err.message });
12026
+ });
12027
+ child.on("close", (code) => {
12028
+ clearTimeout(t2);
12029
+ ok({ code: code ?? 1, stdout, stderr });
12030
+ });
12031
+ });
12032
+ var markerFile = (home) => join17(home, "update.json");
12033
+ function writeMarker(home, m) {
12034
+ if (!m) return void rmSync4(markerFile(home), { force: true });
12035
+ mkdirSync11(home, { recursive: true });
12036
+ writeFileSync12(markerFile(home), `${JSON.stringify(m)}
12037
+ `);
12038
+ }
12039
+ function readMarker(home, version, now = Date.now()) {
12040
+ const f = markerFile(home);
12041
+ if (!existsSync15(f)) return null;
12042
+ let m = {};
12043
+ try {
12044
+ m = JSON.parse(readFileSync11(f, "utf8"));
12045
+ } catch {
12046
+ }
12047
+ rmSync4(f, { force: true });
12048
+ if (typeof m.at !== "number" || now - m.at > 36e5 || !m.to || !m.from) return null;
12049
+ const lines = Array.isArray(m.lines) ? m.lines.filter((l) => typeof l === "string").slice(-30) : [];
12050
+ if (m.to === version) return { ok: true, message: `Kiosko updated from ${m.from} to ${version}`, lines };
12051
+ return { ok: false, message: `the update to ${m.to} did not happen: this is Kiosko ${version}`, lines };
12052
+ }
12053
+
9681
12054
  // packages/server/src/server.ts
9682
12055
  var require3 = createRequire3(import.meta.url);
9683
12056
  var MIME = {
@@ -9691,11 +12064,15 @@ var MIME = {
9691
12064
  ".woff2": "font/woff2",
9692
12065
  ".ico": "image/x-icon"
9693
12066
  };
12067
+ var realDiscover = async (url2, tokenFile) => {
12068
+ const [trcc, usb, remote] = await Promise.all([discoverTrcc(url2, tokenFile), discoverUsb(), discoverRemote()]);
12069
+ return { trcc, usb, remote };
12070
+ };
9694
12071
  function webRoot() {
9695
- const bundled = join17(import.meta.dirname, "web");
9696
- if (existsSync14(join17(bundled, "index.html"))) return bundled;
12072
+ const bundled = join18(import.meta.dirname, "web");
12073
+ if (existsSync16(join18(bundled, "index.html"))) return bundled;
9697
12074
  try {
9698
- return join17(dirname7(require3.resolve("@kiosko/web/package.json")), "dist");
12075
+ return join18(dirname8(require3.resolve("@kiosko/web/package.json")), "dist");
9699
12076
  } catch {
9700
12077
  return resolve7(import.meta.dirname, "../../web/dist");
9701
12078
  }
@@ -9737,9 +12114,95 @@ function startServer(o) {
9737
12114
  const checking = o.checkUpdates ?? (!runtime.demoMode && process.env.KIOSKO_NO_UPDATE_CHECK !== "1");
9738
12115
  const updateTimers = checking ? [setTimeout(() => void refreshUpdates().catch(() => void 0), 2e4), setInterval(() => void refreshUpdates().catch(() => void 0), 24 * 36e5)] : [];
9739
12116
  for (const t2 of updateTimers) t2.unref?.();
9740
- const store = o.store ?? new StoreCatalog({ cacheDir: join17(paths.home, "store") });
12117
+ const store = o.store ?? new StoreCatalog({ cacheDir: join18(paths.home, "store") });
9741
12118
  const storeTimers = checking ? [setTimeout(() => void store.refresh(), 15e3), setInterval(() => void store.refresh(), 24 * 36e5)] : [];
9742
12119
  for (const t2 of storeTimers) t2.unref?.();
12120
+ const home = o.home ?? paths.home;
12121
+ const install = o.install ?? currentInstall();
12122
+ const registryUrl = o.selfUpdate?.registry ?? npmRegistry();
12123
+ const blocker = updateBlocker(install, { demo: runtime.demoMode });
12124
+ const instance = randomBytes4(8).toString("hex");
12125
+ const how = o.selfUpdate?.restartHow ?? restartHow(install, { tty: !!process.stdout.isTTY, pid: process.pid });
12126
+ const probeHost = o.host === "0.0.0.0" || o.host === "::" ? "127.0.0.1" : o.host.includes(":") ? `[${o.host}]` : o.host;
12127
+ const handover = {
12128
+ instance,
12129
+ logFile: join18(home, "kiosko.log"),
12130
+ release: async () => {
12131
+ runtime.stop();
12132
+ for (const c of clients) c.end();
12133
+ clients.clear();
12134
+ await new Promise((ok) => {
12135
+ server.close(() => ok());
12136
+ server.closeAllConnections();
12137
+ setTimeout(ok, 3e3).unref();
12138
+ });
12139
+ },
12140
+ reclaim: async () => {
12141
+ await new Promise((ok, fail) => {
12142
+ server.once("error", fail);
12143
+ server.listen(o.port, o.host, () => {
12144
+ server.off("error", fail);
12145
+ ok();
12146
+ });
12147
+ });
12148
+ runtime.start();
12149
+ },
12150
+ spawn: () => {
12151
+ const out = openSync(join18(home, "kiosko.log"), "a");
12152
+ const args = process.argv.slice(2).filter((a) => a !== "--open");
12153
+ const child = spawn2(process.execPath, [...process.execArgv, install.cli, ...args], { detached: true, stdio: ["ignore", out, out], env: process.env, cwd: process.cwd(), windowsHide: true });
12154
+ const exited = new Promise((ok) => {
12155
+ child.once("exit", ok);
12156
+ child.once("error", ok);
12157
+ });
12158
+ child.unref();
12159
+ return { exited, kill: () => void child.kill() };
12160
+ },
12161
+ probe: async () => {
12162
+ const r = await fetch(`http://${probeHost}:${o.port}/api/version`, { signal: AbortSignal.timeout(1500) });
12163
+ return r.ok ? await r.json() : null;
12164
+ },
12165
+ exit: () => {
12166
+ close();
12167
+ runtime.stop();
12168
+ setTimeout(() => process.exit(0), 100);
12169
+ }
12170
+ };
12171
+ const updater = new KioskoUpdater({
12172
+ install,
12173
+ current: o.version,
12174
+ registry: registryUrl,
12175
+ node: process.execPath,
12176
+ run: realRun,
12177
+ fetch: (u, i) => fetch(u, i),
12178
+ loaded: () => ({ ids: runtime.registry.list().map((p) => p.def.id), problems: runtime.registry.problems.map((p) => p.message) }),
12179
+ log: (m) => runtime.log("kiosko-update", m),
12180
+ changed: (st) => send("kiosko-update", st),
12181
+ tmpDir: tmpdir2(),
12182
+ restartHow: how,
12183
+ handover,
12184
+ mark: (m) => writeMarker(home, m),
12185
+ launch: (script) => spawn2("cmd.exe", ["/d", "/c", script], { detached: true, stdio: "ignore", windowsHide: true }).unref(),
12186
+ serviceTask: async () => (await realRun("schtasks", ["/Query", "/TN", "Kiosko"], { timeoutMs: 15e3 })).code === 0,
12187
+ port: o.port,
12188
+ home,
12189
+ ...o.selfUpdate
12190
+ });
12191
+ if (!runtime.demoMode) {
12192
+ const m = readMarker(home, o.version);
12193
+ if (m) {
12194
+ for (const l of m.lines) runtime.log("kiosko-update", `(before the restart) ${l}`);
12195
+ runtime.log("kiosko-update", m.message);
12196
+ }
12197
+ }
12198
+ const kioskoUpdateState = () => ({
12199
+ install: { kind: install.kind, service: install.service, dir: install.dir, perUser: install.perUser ?? false, platform: install.platform },
12200
+ canUpdate: blocker === null,
12201
+ blocker,
12202
+ restart: how,
12203
+ instructions: updates?.kiosko ? updateInstructions(install, updates.kiosko.latest, registryUrl) : null,
12204
+ status: updater.status
12205
+ });
9743
12206
  const installFromStore = async (p, version) => {
9744
12207
  const index = store.current().index;
9745
12208
  const release = p.releases.find((r) => r.version === version);
@@ -9772,16 +12235,23 @@ data: ${JSON.stringify(data)}
9772
12235
  const fullStatus = () => ({ ...runtime.status(), homeassistant: bridge?.status() ?? { enabled: false, state: "off", error: null } });
9773
12236
  const statusTimer = setInterval(() => send("status", fullStatus()), 3e3);
9774
12237
  const allowedHosts = /* @__PURE__ */ new Set([`127.0.0.1:${o.port}`, `localhost:${o.port}`, `[::1]:${o.port}`, `${o.host}:${o.port}`]);
9775
- function state() {
12238
+ function uiLocale(req) {
12239
+ const l = runtime.config.locale;
12240
+ if (l && l !== "auto") return l;
12241
+ const first = String(req?.headers["accept-language"] ?? "").split(",")[0]?.split(";")[0]?.trim();
12242
+ return first && first !== "*" ? first : resolveLocale(runtime.config);
12243
+ }
12244
+ function state(req) {
9776
12245
  const locale = resolveLocale(runtime.config);
9777
12246
  return {
9778
12247
  version: o.version,
9779
12248
  rev,
9780
12249
  locale,
9781
12250
  config: runtime.config,
9782
- catalog: runtime.registry.catalog(locale),
12251
+ catalog: runtime.registry.catalog(uiLocale(req)),
9783
12252
  refused: runtime.registry.refused,
9784
12253
  updates: updates && { checkedAt: updates.checkedAt, plugins: updates.plugins, kiosko: updates.kiosko ?? null },
12254
+ kioskoUpdate: kioskoUpdateState(),
9785
12255
  categories: CATEGORIES,
9786
12256
  themes: THEMES,
9787
12257
  presets: PANEL_PRESETS,
@@ -9794,6 +12264,18 @@ data: ${JSON.stringify(data)}
9794
12264
  platform: process.platform
9795
12265
  };
9796
12266
  }
12267
+ const remote = remoteApi({
12268
+ runtime,
12269
+ json,
12270
+ body,
12271
+ commit: (cfg) => {
12272
+ const c = normalize(cfg);
12273
+ saveConfig(c, o.configPath);
12274
+ rev++;
12275
+ runtime.apply(c);
12276
+ send("config", { rev, by: null });
12277
+ }
12278
+ });
9797
12279
  function findScreen(cfg, id) {
9798
12280
  return cfg.screens.find((s) => s.id === id);
9799
12281
  }
@@ -9801,12 +12283,12 @@ data: ${JSON.stringify(data)}
9801
12283
  const p = url2.pathname;
9802
12284
  const m = req.method ?? "GET";
9803
12285
  if (m !== "GET" && req.headers["x-kiosko"] !== "1") return json(res, 403, { error: "missing X-Kiosko header" });
9804
- if (p === "/api/state" && m === "GET") return json(res, 200, state());
12286
+ if (p === "/api/state" && m === "GET") return json(res, 200, state(req));
9805
12287
  if (p === "/api/config" && m === "PUT") {
9806
12288
  const b = await body(req);
9807
- const raw = b && typeof b === "object" && "config" in b ? b.config : b;
12289
+ const raw2 = b && typeof b === "object" && "config" in b ? b.config : b;
9808
12290
  if (typeof b?.baseRev === "number" && b.baseRev !== rev) return json(res, 409, { error: "the configuration changed elsewhere", code: "conflict", rev, config: runtime.config });
9809
- const cfg = normalize(raw);
12291
+ const cfg = normalize(raw2);
9810
12292
  saveConfig(cfg, o.configPath);
9811
12293
  rev++;
9812
12294
  runtime.apply(cfg);
@@ -9920,25 +12402,51 @@ data: ${JSON.stringify({ version: o.version })}
9920
12402
  runtime.refreshWidget(decodeURIComponent(mm[1]));
9921
12403
  return json(res, 200, { ok: true });
9922
12404
  }
12405
+ if ((p.startsWith("/api/remote/") || /^\/api\/screens\/[^/]+\/remote\//.test(p)) && await remote(req, res, p, m)) return;
9923
12406
  if (p === "/api/devices/discover" && m === "GET") {
9924
12407
  const url0 = url2.searchParams.get("url") ?? "http://127.0.0.1:8099";
9925
- return json(res, 200, { trcc: await discoverTrcc(url0, url2.searchParams.get("tokenFile") ?? void 0), usb: await discoverUsb() });
12408
+ return json(res, 200, await (o.discover ?? realDiscover)(url0, url2.searchParams.get("tokenFile") ?? void 0));
12409
+ }
12410
+ if (p === "/api/version" && m === "GET") return json(res, 200, { version: o.version, instance });
12411
+ if (p === "/api/kiosko/update" && m === "GET") return json(res, 200, kioskoUpdateState());
12412
+ if (p === "/api/kiosko/update" && m === "POST") {
12413
+ const b = await body(req, 4096);
12414
+ if (runtime.demoMode) return json(res, 409, { error: "not in demo mode", code: "demo" });
12415
+ if (blocker) return json(res, 409, { error: `this Kiosko can't update itself (${blocker}): follow the instructions`, code: "cantUpdateKiosko", params: { why: blocker } });
12416
+ const latest = updates?.kiosko?.latest;
12417
+ if (!latest || b.version !== latest) return json(res, 409, { error: `no update of Kiosko to ${String(b.version)}`, code: "noKioskoUpdate", params: { version: String(b.version) } });
12418
+ if (updater.busy) return json(res, 409, { error: "an update is already under way", code: "updateBusy" });
12419
+ updater.start(latest).catch((err) => runtime.log("kiosko-update", String(err instanceof Error ? err.message : err)));
12420
+ return json(res, 202, kioskoUpdateState());
12421
+ }
12422
+ if (p === "/api/kiosko/update/confirm" && m === "POST") {
12423
+ const b = await body(req, 4096);
12424
+ try {
12425
+ await updater.confirm(String(b.version));
12426
+ return json(res, 200, kioskoUpdateState());
12427
+ } catch (err) {
12428
+ return json(res, 409, { error: err instanceof Error ? err.message : String(err), code: err instanceof UpdateError ? err.code : "failed" });
12429
+ }
12430
+ }
12431
+ if (p === "/api/kiosko/update/cancel" && m === "POST") {
12432
+ updater.discard();
12433
+ return json(res, 200, kioskoUpdateState());
9926
12434
  }
9927
12435
  if (p === "/api/logs" && m === "GET") return json(res, 200, runtime.logs.slice(-200));
9928
12436
  if (p === "/api/choices" && m === "GET") {
9929
12437
  const source = url2.searchParams.get("source") ?? "";
9930
12438
  const list2 = url2.searchParams.get("list") ?? "";
9931
- return json(res, 200, runtime.registry.choices(source, list2, runtime.hub.data(source), resolveLocale(runtime.config)));
12439
+ return json(res, 200, runtime.registry.choices(source, list2, runtime.hub.data(source), uiLocale(req)));
9932
12440
  }
9933
12441
  if (p === "/api/plugins/install" && m === "POST") {
9934
12442
  const b = await body(req);
9935
- const name = String(b.name ?? "").trim();
12443
+ const name2 = String(b.name ?? "").trim();
9936
12444
  try {
9937
- const r = await installPlugin(name, { registry: runtime.registry, runtime });
12445
+ const r = await installPlugin(name2, { registry: runtime.registry, runtime });
9938
12446
  if (r.restart) restartNeeded = true;
9939
12447
  rev++;
9940
12448
  send("config", { rev, by: null });
9941
- return json(res, 200, { ok: true, output: r.output, ids: r.ids, problem: r.problem ?? null, rolledBack: !!r.rolledBack, addedPermissions: r.addedPermissions ?? null, restartNeeded, state: state() });
12449
+ return json(res, 200, { ok: true, output: r.output, ids: r.ids, problem: r.problem ?? null, rolledBack: !!r.rolledBack, addedPermissions: r.addedPermissions ?? null, restartNeeded, state: state(req) });
9942
12450
  } catch (err) {
9943
12451
  return json(res, /valid npm/.test(String(err)) ? 400 : 500, { error: err instanceof Error ? err.message : String(err) });
9944
12452
  }
@@ -9974,8 +12482,8 @@ data: ${JSON.stringify({ version: o.version })}
9974
12482
  const release = sp.releases.find((r) => r.version === b.version);
9975
12483
  if (!release) return json(res, 409, { error: `${sp.package} has no release ${String(b.version)} in the store`, code: "noRelease", params: { id, version: String(b.version) } });
9976
12484
  if (release.withdrawn) return json(res, 409, { error: `${sp.package}@${release.version} was withdrawn`, code: "withdrawn", params: { id, version: release.version } });
9977
- const why = releaseProblem({ sdk: release.sdk, platforms: release.platforms ?? sp.platforms }, { sdk: SDK_VERSION, platform: process.platform });
9978
- if (why) return json(res, 409, { error: why.code === "sdk" ? `written for the plugin API ${why.range}; this Kiosko has ${SDK_VERSION}` : `works on ${why.platforms.join(", ")}, not ${process.platform}`, code: "cantInstall", params: { id } });
12485
+ const why2 = releaseProblem({ sdk: release.sdk, platforms: release.platforms ?? sp.platforms }, { sdk: SDK_VERSION, platform: process.platform });
12486
+ if (why2) return json(res, 409, { error: why2.code === "sdk" ? `written for the plugin API ${why2.range}; this Kiosko has ${SDK_VERSION}` : `works on ${why2.platforms.join(", ")}, not ${process.platform}`, code: "cantInstall", params: { id } });
9979
12487
  if (sp.tier === "found" && b.acceptRisk !== true) return json(res, 409, { error: `${sp.package} is unreviewed: confirm you accept the risk`, code: "acceptRisk", params: { id } });
9980
12488
  try {
9981
12489
  const results = await installFromStore(sp, release.version);
@@ -9983,7 +12491,7 @@ data: ${JSON.stringify({ version: o.version })}
9983
12491
  rev++;
9984
12492
  send("config", { rev, by: null });
9985
12493
  const problem = results.map((r) => r.problem).filter(Boolean).join("; ") || null;
9986
- return json(res, 200, { ok: !problem, ids: results.flatMap((r) => r.ids), problem, rolledBack: results.some((r) => r.rolledBack), addedPermissions: results.at(-1)?.addedPermissions ?? null, version: release.version, restartNeeded, state: state() });
12494
+ return json(res, 200, { ok: !problem, ids: results.flatMap((r) => r.ids), problem, rolledBack: results.some((r) => r.rolledBack), addedPermissions: results.at(-1)?.addedPermissions ?? null, version: release.version, restartNeeded, state: state(req) });
9987
12495
  } catch (err) {
9988
12496
  return json(res, err instanceof IntegrityError ? 409 : 500, { error: err instanceof Error ? err.message : String(err), ...err instanceof IntegrityError ? { code: "integrity", params: { id } } : {} });
9989
12497
  }
@@ -9996,7 +12504,7 @@ data: ${JSON.stringify({ version: o.version })}
9996
12504
  if (!r.removed) return json(res, 409, { error: `can't remove "${id}": ${r.reason}`, code: "cantRemove", params: { id, why: r.reason } });
9997
12505
  rev++;
9998
12506
  send("config", { rev, by: null });
9999
- return json(res, 200, state());
12507
+ return json(res, 200, state(req));
10000
12508
  } catch (err) {
10001
12509
  return json(res, 500, { error: err instanceof Error ? err.message : String(err) });
10002
12510
  }
@@ -10022,7 +12530,7 @@ data: ${JSON.stringify({ version: o.version })}
10022
12530
  if (r.restart) restartNeeded = true;
10023
12531
  rev++;
10024
12532
  send("config", { rev, by: null });
10025
- return json(res, 200, { ok: !r.problem, ids: r.ids, problem: r.problem ?? null, rolledBack: !!r.rolledBack, addedPermissions: r.addedPermissions ?? null, version: u.version, state: state() });
12533
+ return json(res, 200, { ok: !r.problem, ids: r.ids, problem: r.problem ?? null, rolledBack: !!r.rolledBack, addedPermissions: r.addedPermissions ?? null, version: u.version, state: state(req) });
10026
12534
  } catch (err) {
10027
12535
  return json(res, 500, { error: err instanceof Error ? err.message : String(err) });
10028
12536
  }
@@ -10034,7 +12542,7 @@ data: ${JSON.stringify({ version: o.version })}
10034
12542
  if (problem) return json(res, 409, { error: problem, code: "reloadFailed", params: { id, why: problem } });
10035
12543
  rev++;
10036
12544
  send("config", { rev, by: null });
10037
- return json(res, 200, state());
12545
+ return json(res, 200, state(req));
10038
12546
  }
10039
12547
  mm = /^\/api\/plugins\/([^/]+)\/enabled$/.exec(p);
10040
12548
  if (mm && m === "POST") {
@@ -10048,7 +12556,7 @@ data: ${JSON.stringify({ version: o.version })}
10048
12556
  rev++;
10049
12557
  runtime.apply(cfg);
10050
12558
  send("config", { rev, by: null });
10051
- return json(res, 200, state());
12559
+ return json(res, 200, state(req));
10052
12560
  }
10053
12561
  if (p === "/api/screens/export" && m === "GET") {
10054
12562
  const id = url2.searchParams.get("id") ?? "";
@@ -10061,16 +12569,16 @@ data: ${JSON.stringify({ version: o.version })}
10061
12569
  }
10062
12570
  function serveStatic(res, pathname) {
10063
12571
  const rel = normPath(decodeURIComponent(pathname)).replace(/^([/\\])+/, "");
10064
- let file = join17(root, rel || "index.html");
12572
+ let file = join18(root, rel || "index.html");
10065
12573
  if (!file.startsWith(root)) return void json(res, 400, { error: "bad path" });
10066
- if (!existsSync14(file) || statSync3(file).isDirectory()) file = join17(root, "index.html");
10067
- if (!existsSync14(file)) {
12574
+ if (!existsSync16(file) || statSync3(file).isDirectory()) file = join18(root, "index.html");
12575
+ if (!existsSync16(file)) {
10068
12576
  res.writeHead(500, { "content-type": "text/plain" });
10069
12577
  return void res.end("The editor is not built. Run `npm run web:build`.");
10070
12578
  }
10071
12579
  const ext = extname(file);
10072
12580
  res.writeHead(200, { "content-type": MIME[ext] ?? "application/octet-stream", "cache-control": ext === ".html" ? "no-cache" : "max-age=300" });
10073
- res.end(readFileSync9(file));
12581
+ res.end(readFileSync12(file));
10074
12582
  }
10075
12583
  const server = createServer((req, res) => {
10076
12584
  const host = req.headers.host ?? "";
@@ -10092,64 +12600,75 @@ data: ${JSON.stringify({ version: o.version })}
10092
12600
  serveStatic(res, url2.pathname);
10093
12601
  });
10094
12602
  server.listen(o.port, o.host);
10095
- return {
10096
- server,
10097
- close() {
10098
- clearInterval(statusTimer);
10099
- bridge?.stop();
10100
- for (const t2 of updateTimers) clearTimeout(t2);
10101
- for (const t2 of storeTimers) clearTimeout(t2);
10102
- runtime.off("frame", onFrame);
10103
- runtime.off("alerts", onAlerts);
10104
- runtime.off("log", onLog);
10105
- for (const c of clients) c.end();
10106
- clients.clear();
10107
- server.close();
10108
- }
10109
- };
12603
+ function close() {
12604
+ clearInterval(statusTimer);
12605
+ bridge?.stop();
12606
+ for (const t2 of updateTimers) clearTimeout(t2);
12607
+ for (const t2 of storeTimers) clearTimeout(t2);
12608
+ runtime.off("frame", onFrame);
12609
+ runtime.off("alerts", onAlerts);
12610
+ runtime.off("log", onLog);
12611
+ for (const c of clients) c.end();
12612
+ clients.clear();
12613
+ server.close();
12614
+ }
12615
+ return { server, close, updater };
10110
12616
  }
10111
12617
 
10112
12618
  // packages/server/src/starter.ts
10113
- function starterConfig(registry2, o = {}) {
10114
- const width = o.width ?? 1920;
10115
- const height = o.height ?? 462;
10116
- const L = (t2) => localize(t2, o.locale ?? "en");
10117
- const screen = newScreen(L({ en: "My panel", es: "Mi panel", de: "Mein Panel", "zh-Hant": "\u6211\u7684\u9762\u677F", "zh-Hans": "\u6211\u7684\u5C4F\u5E55" }), width, height);
10118
- const market = languageById(pickLocale(LANGUAGE_IDS, o.locale ?? "en") ?? "en")?.plugins;
10119
- const offered = (t2) => !market?.without.includes(t2.split("/")[0]) && !market?.instead[t2];
10120
- const has = (t2) => offered(t2) && !!registry2.widget(t2);
10121
- const page = newPage(L({ en: "Home", es: "Inicio", de: "Start", "zh-Hant": "\u9996\u9801", "zh-Hans": "\u9996\u9875" }), width, height);
10122
- page.grid = { cols: 24, rows: 6, gap: 10, padding: 10 };
10123
- page.gravity = "left";
10124
- const tiles = [];
10125
- const add = (r, types2, title) => {
10126
- const ws = types2.filter(has).map((t2) => newWidget(t2, {}, title));
10127
- if (ws.length) tiles.push(newTile(r, ws));
12619
+ import { existsSync as existsSync17, readdirSync as readdirSync5 } from "node:fs";
12620
+ import { homedir as homedir5 } from "node:os";
12621
+ import { join as join19 } from "node:path";
12622
+ var ROTATIONS2 = [0, 90, 180, 270];
12623
+ function starterPanels(found, trccUrl = "http://127.0.0.1:8099") {
12624
+ const out = [];
12625
+ const named = (width, height) => {
12626
+ const base3 = PANEL_PRESETS.find((p) => p.width === width && p.height === height || p.width === height && p.height === width)?.name ?? `${width}\xD7${height}`;
12627
+ const same3 = out.filter((p) => p.name === base3 || p.name.startsWith(`${base3} `)).length;
12628
+ if (same3 === 1) out.find((p) => p.name === base3).name = `${base3} 1`;
12629
+ return same3 ? `${base3} ${same3 + 1}` : base3;
10128
12630
  };
10129
- const lead = "agents/sessions";
10130
- if (has(lead)) add({ x: 0, y: 0, w: 11, h: 6 }, [lead]);
10131
- else add({ x: 0, y: 0, w: 11, h: 6 }, ["core/text"], L({ en: "Welcome", es: "Bienvenida", de: "Willkommen", "zh-Hant": "\u6B61\u8FCE", "zh-Hans": "\u6B22\u8FCE" }));
10132
- add({ x: 11, y: 0, w: 5, h: 4 }, ["core/clock"]);
10133
- add({ x: 11, y: 4, w: 5, h: 2 }, ["weather/forecast", "mirror/compliments"]);
10134
- add({ x: 16, y: 0, w: 8, h: 6 }, ["usage/rail", "vitals/vitals", "system/health", "mirror/countdown"].filter(has).slice(0, 3));
10135
- if (!has(lead)) {
10136
- const welcome = tiles[0]?.widgets[0];
10137
- if (welcome) welcome.options = { text: L({ en: "Hi there.\nDrag widgets from the library to build your panel.", es: "Hola.\nArrastra widgets desde la biblioteca para montar tu panel.", de: "Hallo!\nZieh Widgets aus der Bibliothek, um dein Panel zu gestalten.", "zh-Hant": "\u4F60\u597D\u3002\n\u5F9E\u5C0F\u5DE5\u5177\u5EAB\u62D6\u66F3\u5C0F\u5DE5\u5177\uFF0C\n\u6253\u9020\u4F60\u7684\u9762\u677F\u3002", "zh-Hans": "\u4F60\u597D\u3002\n\u4ECE\u7EC4\u4EF6\u5E93\u62D6\u52A8\u5C0F\u7EC4\u4EF6\uFF0C\n\u5E03\u7F6E\u4F60\u7684\u526F\u5C4F\u3002" }), maxSize: 54 };
10138
- }
10139
- page.tiles = tiles;
10140
- if (height > width) transposePage(page, width, height);
10141
- else {
10142
- const grid = suggestGrid(width, height);
10143
- page.tiles = rescale(page.tiles, page.grid, grid);
10144
- page.grid = grid;
12631
+ for (const u of found.usb) {
12632
+ const width = u.width || 1920;
12633
+ const height = u.height || 462;
12634
+ out.push({ name: named(width, height), width, height, rotate: ROTATIONS2.includes(u.rotate ?? 0) ? u.rotate ?? 0 : 0, device: { driver: "usb", ...u.serial ? { serial: u.serial } : {} } });
10145
12635
  }
10146
- screen.pages = [page];
10147
- screen.interludes = offered("agents/runner") && registry2.interlude("agents/runner") ? [{ id: "interlude-runner", type: "agents/runner", enabled: false, everyMs: 15 * 6e4, maxSeconds: 30, options: {} }] : [];
10148
- return normalize({ screens: [screen], locale: "auto" });
12636
+ for (const t2 of found.trcc) out.push({ name: named(t2.width, t2.height), width: t2.width, height: t2.height, rotate: 0, device: { driver: "trcc", url: trccUrl, deviceKey: t2.key } });
12637
+ return out;
12638
+ }
12639
+ function agentTraces(env = process.env, home = homedir5()) {
12640
+ const dirs = [env.AGENT_SESSIONS_DIR ?? join19(env.AIMONITOR_DIR ?? join19(home, ".aimonitor"), "sessions"), join19(home, ".codex", "sessions"), join19(home, ".qwen", "projects"), join19(home, ".kimi", "sessions")];
12641
+ return dirs.some((d) => {
12642
+ try {
12643
+ return existsSync17(d) && readdirSync5(d).length > 0;
12644
+ } catch {
12645
+ return false;
12646
+ }
12647
+ });
12648
+ }
12649
+ var CATS_PAGE = { en: "Cats room", es: "Sala de los gatos", de: "Katzenzimmer", "zh-Hant": "\u8C93\u54AA\u623F\u9593", "zh-Hans": "\u732B\u54AA\u623F\u95F4" };
12650
+ function starterConfig(registry2, o = {}) {
12651
+ const locale = o.locale ?? "en";
12652
+ const has = (t2) => !!registry2.widget(t2);
12653
+ const one = (name2, width, height, device, rotate = 0) => {
12654
+ const screen = newScreen(name2, width, height, device);
12655
+ screen.rotate = rotate;
12656
+ screen.pages = [starterPage(has, { width, height, locale, agents: o.agents ?? true, weather: o.weather ?? true })];
12657
+ if ((o.agents ?? true) && has("cats/room")) {
12658
+ const cats = newPage(localize(CATS_PAGE, locale), width, height);
12659
+ cats.tiles = [newTile({ x: 0, y: 0, w: cats.grid.cols, h: cats.grid.rows }, [newWidget("cats/room")])];
12660
+ cats.tiles[0].chrome = "bare";
12661
+ screen.pages.push(cats);
12662
+ }
12663
+ screen.interludes = starterInterludes((t2) => !!registry2.interlude(t2), locale);
12664
+ return screen;
12665
+ };
12666
+ const screens = o.panels?.length ? o.panels.map((p) => one(p.name, p.width, p.height, p.device, p.rotate)) : [one(localize(STARTER_NAMES.screen, locale), o.width ?? 1920, o.height ?? 462)];
12667
+ return normalize({ screens, locale: "auto", setup: "pending" });
10149
12668
  }
10150
12669
 
10151
12670
  // packages/server/src/cli.ts
10152
- var VERSION = "0.2.8";
12671
+ var VERSION = "0.2.10";
10153
12672
  var USAGE2 = `Kiosko ${VERSION}: a widget mosaic for USB LCD panels
10154
12673
 
10155
12674
  kiosko start [--port 7420] [--host 127.0.0.1] [--config file] [--open] [--demo]
@@ -10163,19 +12682,23 @@ var USAGE2 = `Kiosko ${VERSION}: a widget mosaic for USB LCD panels
10163
12682
  kiosko usb [list] the LY panels libusb sees, with their serial numbers
10164
12683
  kiosko usb test [--serial S] [--seconds 10] [--size 1920x462] [--rotate 180]
10165
12684
  drive a panel with the sample screen (experimental)
12685
+ kiosko remote [list] Kiosko remote screens on the network (mDNS)
12686
+ kiosko remote pair <uid|host> [--screen id] pair one (type the code it shows)
12687
+ kiosko remote ota|logs|unpair <screen> [firmware.bin]
10166
12688
  kiosko gallery [--out gallery] [--locale en | --all-languages] [--theme midnight] [--pages config.json]
10167
12689
  kiosko plugins [list|add <id>\u2026|link <folder>\u2026|remove <id>\u2026]
10168
12690
  kiosko service install|uninstall|print (start with your session)
12691
+ kiosko self-check [--json] load the plugins as start would and say what loads (the updater's dry run)
10169
12692
  kiosko version`;
10170
12693
  var argv = process.argv.slice(2);
10171
12694
  var FLAG_COMMANDS = /* @__PURE__ */ new Set(["--help", "-h", "--version", "-v"]);
10172
12695
  var cmd = argv.includes("--help") || argv.includes("-h") ? "help" : argv[0] && (!argv[0].startsWith("-") || FLAG_COMMANDS.has(argv[0])) ? argv[0] : "start";
10173
- var flag = (name) => argv.includes(name);
10174
- var opt = (name) => {
10175
- const i = argv.indexOf(name);
12696
+ var flag = (name2) => argv.includes(name2);
12697
+ var opt = (name2) => {
12698
+ const i = argv.indexOf(name2);
10176
12699
  return i >= 0 ? argv[i + 1] : void 0;
10177
12700
  };
10178
- var SCREEN_THREAD = ["./screen-thread.js", "./screen-thread.ts"].map((f) => new URL(f, import.meta.url)).find((u) => existsSync15(u));
12701
+ var SCREEN_THREAD = ["./screen-thread.js", "./screen-thread.ts"].map((f) => new URL(f, import.meta.url)).find((u) => existsSync18(u));
10179
12702
  var THREADS = SCREEN_THREAD ? { threadEntry: SCREEN_THREAD } : {};
10180
12703
  async function registry() {
10181
12704
  installSdkResolver();
@@ -10186,8 +12709,8 @@ async function registry() {
10186
12709
  if (r.plugin(o.id)) continue;
10187
12710
  try {
10188
12711
  const url2 = import.meta.resolve(o.npm);
10189
- const mod = await import(url2);
10190
- if (mod.default) r.add(mod.default, `npm:${o.npm}`, url2);
12712
+ const mod2 = await import(url2);
12713
+ if (mod2.default) r.add(mod2.default, `npm:${o.npm}`, url2);
10191
12714
  } catch {
10192
12715
  }
10193
12716
  }
@@ -10201,15 +12724,17 @@ async function config(reg, path) {
10201
12724
  process.exit(1);
10202
12725
  }
10203
12726
  if (exists) return cfg;
10204
- const starter = starterConfig(reg, { locale: Intl.DateTimeFormat().resolvedOptions().locale });
12727
+ const found = await realDiscover("http://127.0.0.1:8099");
12728
+ const panels = starterPanels(found);
12729
+ const starter = starterConfig(reg, { locale: Intl.DateTimeFormat().resolvedOptions().locale, panels, agents: agentTraces(), weather: false });
10205
12730
  saveConfig(starter, path);
10206
- console.log(`created ${path} with a starter screen`);
12731
+ console.log(`created ${path} with ${panels.length ? `a screen for each panel found: ${panels.map((p) => `${p.name} (${p.width}\xD7${p.height})`).join(", ")}` : "a starter screen (no panel found)"}`);
10207
12732
  return starter;
10208
12733
  }
10209
12734
  function openBrowser(url2) {
10210
12735
  const [bin, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url2]] : ["xdg-open", [url2]];
10211
12736
  try {
10212
- spawn(bin, args, { stdio: "ignore", detached: true }).unref();
12737
+ spawn3(bin, args, { stdio: "ignore", detached: true }).unref();
10213
12738
  } catch {
10214
12739
  }
10215
12740
  }
@@ -10221,7 +12746,9 @@ async function main() {
10221
12746
  const cfg = await config(reg, path);
10222
12747
  const host = opt("--host") ?? cfg.server.host;
10223
12748
  const port = Number(opt("--port") ?? cfg.server.port);
10224
- const rt = new Runtime(reg, cfg, { demo: flag("--demo"), ...THREADS });
12749
+ const shown = host === "0.0.0.0" || host === "::" || !host ? "127.0.0.1" : host;
12750
+ const editorAt = `http://${shown.includes(":") ? `[${shown}]` : shown}:${port}`;
12751
+ const rt = new Runtime(reg, cfg, { demo: flag("--demo"), welcome: true, editorUrl: editorAt, ...THREADS });
10225
12752
  if (flag("--demo")) console.log("demo mode: every widget shows sample data, nothing is read");
10226
12753
  rt.start();
10227
12754
  const srv = startServer({ runtime: rt, host, port, configPath: path, version: VERSION });
@@ -10277,20 +12804,20 @@ async function main() {
10277
12804
  }
10278
12805
  case "import-aimonitor": {
10279
12806
  const from = opt("--from") ?? `${process.env.HOME ?? ""}/.aimonitor/config.json`;
10280
- if (!existsSync15(from)) {
12807
+ if (!existsSync18(from)) {
10281
12808
  console.error(`not found: ${from}`);
10282
12809
  process.exit(1);
10283
12810
  }
10284
12811
  const reg = await registry();
10285
- const modePath = join18(dirname8(from), "modo");
10286
- const modeOverride = existsSync15(modePath) ? readFileSync10(modePath, "utf8") : null;
10287
- const { config: imported, notes } = importAimonitor(JSON.parse(readFileSync10(from, "utf8")), reg, modeOverride, { withSecrets: flag("--with-secrets") });
12812
+ const modePath = join20(dirname9(from), "modo");
12813
+ const modeOverride = existsSync18(modePath) ? readFileSync13(modePath, "utf8") : null;
12814
+ const { config: imported, notes } = importAimonitor(JSON.parse(readFileSync13(from, "utf8")), reg, modeOverride, { withSecrets: flag("--with-secrets") });
10288
12815
  if (modeOverride) notes.push(`mode from ${modePath}: ${modeOverride.trim()}`);
10289
12816
  for (const n of notes) console.log(`- ${n}`);
10290
12817
  if (flag("--write")) {
10291
- if (existsSync15(path)) writeFileSync12(`${path}.bak`, readFileSync10(path));
12818
+ if (existsSync18(path)) writeFileSync13(`${path}.bak`, readFileSync13(path));
10292
12819
  saveConfig(imported, path);
10293
- console.log(`written ${path}${existsSync15(`${path}.bak`) ? ` (previous one in ${path}.bak)` : ""}`);
12820
+ console.log(`written ${path}${existsSync18(`${path}.bak`) ? ` (previous one in ${path}.bak)` : ""}`);
10294
12821
  } else {
10295
12822
  console.log(JSON.stringify(imported, null, 2));
10296
12823
  console.log("\n(dry run: add --write to save it)");
@@ -10341,12 +12868,24 @@ async function main() {
10341
12868
  if (!usb.ok) console.log(`usb not available: ${usb.error}`);
10342
12869
  else if (!usb.panels.length) console.log("usb no LY panel (0416:5408/5409) plugged in");
10343
12870
  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}` : ""}`);
12871
+ const remote = await discoverRemote(2e3);
12872
+ if (!remote.length) console.log("remote no Kiosko remote screen answered on this network (mDNS)");
12873
+ for (const r of remote) {
12874
+ const used = cfg.screens.find((s) => s.device.driver === "remote" && s.device.uid === r.uid);
12875
+ console.log(`remote ${r.id} (${r.model} ${r.width}\xD7${r.height}, fw ${r.fw}, uid ${r.uid}) at ${r.address}, ${r.paired ? "paired" : "not paired"}${used ? `, screen "${used.name}"` : ""}`);
12876
+ }
12877
+ for (const s of cfg.screens) if (s.device.driver === "remote" && !s.device.key) console.log(`remote \u2717 screen "${s.name}" is not paired: Screens \u2192 Detect panels \u2192 Pair`);
10344
12878
  for (const s of cfg.screens) {
10345
12879
  const missing = s.pages.flatMap((p) => p.tiles.flatMap((t2) => t2.widgets.filter((w) => !reg.widget(w.type)).map((w) => w.type)));
10346
12880
  console.log(`screen ${s.name} ${s.width}\xD7${s.height} ${s.device.driver}${missing.length ? ` \u2717 unknown widgets: ${[...new Set(missing)].join(", ")}` : ""}`);
10347
12881
  }
10348
12882
  return;
10349
12883
  }
12884
+ case "remote": {
12885
+ process.env.KIOSKO_QUIET ??= "1";
12886
+ process.exitCode = await remoteCommand(argv.slice(1), { configPath: path, port: Number(opt("--port")) || 7420, registry });
12887
+ return;
12888
+ }
10350
12889
  case "service": {
10351
12890
  const pass = ["--port", "--host", "--config"].flatMap((f) => opt(f) ? [f, opt(f)] : []);
10352
12891
  const env = process.env.KIOSKO_HOME ? { KIOSKO_HOME: process.env.KIOSKO_HOME } : {};
@@ -10360,7 +12899,7 @@ async function main() {
10360
12899
  const reg = await registry();
10361
12900
  const out = opt("--out") ?? "gallery";
10362
12901
  const sample = opt("--pages");
10363
- const n = buildGallery(reg, { out, locale: opt("--locale") ?? "en", languages: flag("--all-languages"), theme: opt("--theme") ?? "midnight", ...sample ? { pages: JSON.parse(readFileSync10(sample, "utf8")) } : {} });
12902
+ const n = buildGallery(reg, { out, locale: opt("--locale") ?? "en", languages: flag("--all-languages"), theme: opt("--theme") ?? "midnight", ...sample ? { pages: JSON.parse(readFileSync13(sample, "utf8")) } : {} });
10364
12903
  console.log(`${n} widgets \u2192 ${out}/index.html`);
10365
12904
  return;
10366
12905
  }
@@ -10374,6 +12913,17 @@ async function main() {
10374
12913
  process.exitCode = await configCommand(argv.slice(1), { registry, configPath: path });
10375
12914
  return;
10376
12915
  }
12916
+ case "self-check": {
12917
+ process.env.KIOSKO_QUIET ??= "1";
12918
+ const reg = await registry();
12919
+ const report = { kiosko: "self-check", version: VERSION, node: process.version, plugins: reg.list().map((p) => ({ id: p.def.id, version: p.def.version })), problems: reg.problems, refused: reg.refused };
12920
+ if (flag("--json")) console.log(JSON.stringify(report));
12921
+ else {
12922
+ console.log(`Kiosko ${VERSION}, Node ${process.version}: ${report.plugins.length} plugins load (${report.plugins.map((p) => p.id).join(", ")})`);
12923
+ for (const pr of report.problems) console.log(` \u2717 ${pr.origin}: ${pr.message}`);
12924
+ }
12925
+ process.exit(0);
12926
+ }
10377
12927
  case "help":
10378
12928
  case "--help":
10379
12929
  case "-h":