kiosko 0.2.9 → 0.2.11

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);
@@ -219,7 +219,7 @@ function toJsonSchema(f) {
219
219
  case "list":
220
220
  return { ...base3, type: "array", items: toJsonSchema(f.item), maxItems: f.max, ...f.filter ? { "x-ui": { ...ui, widget: "filter", choices: f.item.kind === "string" ? f.item.choices : void 0 }, "x-filter": true } : {} };
221
221
  case "map":
222
- return { ...base3, type: "object", additionalProperties: { type: "string" } };
222
+ return { ...base3, type: "object", additionalProperties: { type: "string" }, ...f.keyChoices ? { "x-ui": { ...ui, keyChoices: f.keyChoices } } : {} };
223
223
  case "object":
224
224
  return { ...base3, type: "object", properties: Object.fromEntries(Object.entries(f.props).map(([k, sub]) => [k, toJsonSchema(sub)])) };
225
225
  }
@@ -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
  }
@@ -1139,7 +1139,7 @@ var init_testing = __esm({
1139
1139
 
1140
1140
  // packages/server/src/cli.ts
1141
1141
  import { spawn as spawn3 } from "node:child_process";
1142
- import { existsSync as existsSync18, readFileSync as readFileSync12, writeFileSync as writeFileSync13 } from "node:fs";
1142
+ import { existsSync as existsSync18, readFileSync as readFileSync13, writeFileSync as writeFileSync13 } from "node:fs";
1143
1143
  import { dirname as dirname9, join as join20 } from "node:path";
1144
1144
 
1145
1145
  // packages/core/src/config/model.ts
@@ -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;
@@ -1238,9 +1244,9 @@ function newId(prefix = "id") {
1238
1244
  counter = (counter + 1) % 1296;
1239
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")}`;
1240
1246
  }
1241
- function newPage(name, width, height, tiles = []) {
1247
+ function newPage(name2, width, height, tiles = []) {
1242
1248
  const grid = suggestGrid(width, height);
1243
- 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 };
1244
1250
  }
1245
1251
  function newTile(r, widgets = []) {
1246
1252
  return { id: newId("tile"), ...r, widgets, rotateMs: 3e4, chrome: "auto" };
@@ -1248,10 +1254,10 @@ function newTile(r, widgets = []) {
1248
1254
  function newWidget(type, options2 = {}, title) {
1249
1255
  return { id: newId("w"), type, options: options2, ...title ? { title } : {} };
1250
1256
  }
1251
- function newScreen(name, width = 1920, height = 462, device = { driver: "virtual" }) {
1257
+ function newScreen(name2, width = 1920, height = 462, device = { driver: "virtual" }) {
1252
1258
  return {
1253
1259
  id: newId("screen"),
1254
- name,
1260
+ name: name2,
1255
1261
  enabled: true,
1256
1262
  width,
1257
1263
  height,
@@ -1379,7 +1385,7 @@ var CATEGORIES = [
1379
1385
  ];
1380
1386
  var ALERT_LEVELS = ["info", "warn", "critical"];
1381
1387
  var PAD_KEYS = ["up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select"];
1382
- var SDK_VERSION = "0.2.9";
1388
+ var SDK_VERSION = "0.2.11";
1383
1389
  function defineWidget(w) {
1384
1390
  return w;
1385
1391
  }
@@ -1522,7 +1528,7 @@ import { join, win32 } from "node:path";
1522
1528
  function expandPath(p, o = {}) {
1523
1529
  const env = o.env ?? process.env;
1524
1530
  let v = p.replace(/\$(?:\{(\w+)\}|(\w+))/g, (whole, a, b) => env[a ?? b ?? ""] ?? whole);
1525
- 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);
1526
1532
  const home = o.home ?? homedir();
1527
1533
  if (v === "~") return home;
1528
1534
  return v.startsWith("~/") || v.startsWith("~\\") ? join(home, v.slice(2)) : v;
@@ -1738,8 +1744,8 @@ var paths = {
1738
1744
  // packages/core/src/config/normalize.ts
1739
1745
  init_format();
1740
1746
  init_workday();
1741
- function normalize(raw) {
1742
- const { $schema, threads, setup, bootAnimation, ...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 : {};
1743
1749
  const screens = Array.isArray(c.screens) ? c.screens.map(normalizeScreen) : [];
1744
1750
  return {
1745
1751
  ...typeof $schema === "string" && $schema ? { $schema } : {},
@@ -1809,9 +1815,9 @@ function normalizeScreen(s, i) {
1809
1815
  };
1810
1816
  }
1811
1817
  var HHMM = /^([01][0-9]|2[0-3]):[0-5][0-9]$/;
1812
- function normalizeAlerts(raw) {
1813
- if (!raw || typeof raw !== "object") return {};
1814
- const a = raw;
1818
+ function normalizeAlerts(raw2) {
1819
+ if (!raw2 || typeof raw2 !== "object") return {};
1820
+ const a = raw2;
1815
1821
  const minLevel = ALERT_THRESHOLDS.includes(a.minLevel) ? a.minLevel : "info";
1816
1822
  const q3 = a.quiet;
1817
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;
@@ -2177,6 +2183,22 @@ function configSchema(plugins) {
2177
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." }
2178
2184
  }
2179
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
+ brightness: { type: "integer", minimum: 0, maximum: 100, description: "Backlight brightness, 0-100 (perceived; 0 = off), pushed to the screen on every connection. Screen firmware 0.1.2 or later; older ones ignore it. Empty: the screen keeps its own (70 % unless set on its setup page)." }
2200
+ }
2201
+ },
2180
2202
  {
2181
2203
  title: "Frame file",
2182
2204
  description: "Writes frame.jpg atomically into a folder; an external sender takes it to the panel.",
@@ -2319,8 +2341,8 @@ function toPointer(segs) {
2319
2341
  function resolvePointer(root, ref) {
2320
2342
  if (!ref.startsWith("#")) throw new Error(`only local $ref are supported (${ref})`);
2321
2343
  let cur = root;
2322
- for (const raw of ref.slice(1).split("/").slice(1)) {
2323
- const key = decodeURIComponent(raw).replace(/~1/g, "/").replace(/~0/g, "~");
2344
+ for (const raw2 of ref.slice(1).split("/").slice(1)) {
2345
+ const key = decodeURIComponent(raw2).replace(/~1/g, "/").replace(/~0/g, "~");
2324
2346
  cur = Array.isArray(cur) ? cur[Number(key)] : isObj(cur) ? cur[key] : void 0;
2325
2347
  }
2326
2348
  if (cur === void 0) throw new Error(`$ref ${ref} points nowhere`);
@@ -2606,13 +2628,13 @@ function repeated(items, path, what2, out) {
2606
2628
  else seen.set(x.id, i);
2607
2629
  });
2608
2630
  }
2609
- function checkConfig(raw, plugins) {
2631
+ function checkConfig(raw2, plugins) {
2610
2632
  const errors = [];
2611
2633
  const warnings = [];
2612
- if (!isObj2(raw)) return { errors: [issue([], "the config must be a JSON object")], warnings };
2634
+ if (!isObj2(raw2)) return { errors: [issue([], "the config must be a JSON object")], warnings };
2613
2635
  let cfg;
2614
2636
  try {
2615
- cfg = normalize(raw);
2637
+ cfg = normalize(raw2);
2616
2638
  } catch {
2617
2639
  return { errors, warnings };
2618
2640
  }
@@ -2697,9 +2719,9 @@ function checkConfig(raw, plugins) {
2697
2719
  }
2698
2720
  return { errors, warnings };
2699
2721
  }
2700
- function validateConfig(raw, plugins, schema2 = configSchema(plugins)) {
2701
- const shape = validateJson(schema2, raw);
2702
- const more = checkConfig(raw, plugins);
2722
+ function validateConfig(raw2, plugins, schema2 = configSchema(plugins)) {
2723
+ const shape = validateJson(schema2, raw2);
2724
+ const more = checkConfig(raw2, plugins);
2703
2725
  return { errors: [...shape, ...more.errors], warnings: more.warnings };
2704
2726
  }
2705
2727
 
@@ -2736,7 +2758,7 @@ var pageText = (p) => {
2736
2758
  const ts = pageTypes(p);
2737
2759
  return `page ${q2(p.name)}: ${plural2(p.tiles.length, "tile")}${ts.length ? ` (${ts.slice(0, 6).join(", ")}${ts.length > 6 ? `, +${ts.length - 6} more` : ""})` : ""}`;
2738
2760
  };
2739
- 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;
2761
+ 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;
2740
2762
  var changedKeys = (a, b) => [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].filter((k) => !same(a[k], b[k]));
2741
2763
  function diffTiles(before, after, depth, out) {
2742
2764
  const m = match(before.tiles, after.tiles, rect);
@@ -2854,7 +2876,7 @@ function annotatedValues(config2, schema2) {
2854
2876
  const risks = risksOf(v.schema);
2855
2877
  const secret = v.schema["x-secret"] === true;
2856
2878
  if (!risks.length && !secret) return;
2857
- const add = (path, value) => {
2879
+ const add2 = (path, value) => {
2858
2880
  if (isObj3(value) || Array.isArray(value)) return;
2859
2881
  const ptr = toPointer(path);
2860
2882
  const prev = out.get(ptr);
@@ -2870,8 +2892,8 @@ function annotatedValues(config2, schema2) {
2870
2892
  ...v.parent && isObj3(v.parent.value) ? { holder: v.parent.schema } : prev?.holder ? { holder: prev.holder } : {}
2871
2893
  });
2872
2894
  };
2873
- if (Array.isArray(v.value)) v.value.forEach((x, i) => add([...v.path, i], x));
2874
- else add(v.path, v.value);
2895
+ if (Array.isArray(v.value)) v.value.forEach((x, i) => add2([...v.path, i], x));
2896
+ else add2(v.path, v.value);
2875
2897
  });
2876
2898
  return [...out.values()];
2877
2899
  }
@@ -3002,10 +3024,10 @@ function mergeSecrets(incoming, current, schema2) {
3002
3024
  if (!restored.has(parentKey)) {
3003
3025
  if (incContainers.has(parentKey)) continue;
3004
3026
  const holder = incContainers.get(stableKey(current, parentPath.slice(0, -1)));
3005
- const name = parentPath[parentPath.length - 1];
3006
- if (!holder || !isObj3(getAt(out, holder)) || typeof name !== "string") continue;
3007
- setAt(out, [...holder, name], clone2(getAt(current, parentPath)));
3008
- incContainers.set(parentKey, [...holder, name]);
3027
+ const name2 = parentPath[parentPath.length - 1];
3028
+ if (!holder || !isObj3(getAt(out, holder)) || typeof name2 !== "string") continue;
3029
+ setAt(out, [...holder, name2], clone2(getAt(current, parentPath)));
3030
+ incContainers.set(parentKey, [...holder, name2]);
3009
3031
  restored.add(parentKey);
3010
3032
  }
3011
3033
  kept.push({ a: { ...c, path: [...incContainers.get(parentKey), last2] }, from: c });
@@ -3029,24 +3051,24 @@ var CARRIED = ["locale", "timeFormat", "theme", "location", "workday", "plugins"
3029
3051
  function planImport(incoming, current, plugins, schema2 = configSchema(plugins)) {
3030
3052
  const report = validateConfig(incoming, plugins, schema2);
3031
3053
  const { config: merged2, ...secrets } = mergeSecrets(incoming, current, schema2);
3032
- const raw = isObj3(merged2) ? { ...merged2 } : {};
3054
+ const raw2 = isObj3(merged2) ? { ...merged2 } : {};
3033
3055
  const carried = [];
3034
3056
  for (const k of CARRIED) {
3035
- if (raw[k] === void 0 && current[k] !== void 0) {
3036
- raw[k] = clone2(current[k]);
3057
+ if (raw2[k] === void 0 && current[k] !== void 0) {
3058
+ raw2[k] = clone2(current[k]);
3037
3059
  carried.push(k);
3038
3060
  }
3039
3061
  }
3040
- if (raw.$schema === void 0 && current.$schema) raw.$schema = current.$schema;
3041
- const sources = isObj3(raw.sources) ? { ...raw.sources } : {};
3062
+ if (raw2.$schema === void 0 && current.$schema) raw2.$schema = current.$schema;
3063
+ const sources = isObj3(raw2.sources) ? { ...raw2.sources } : {};
3042
3064
  for (const [k, v] of Object.entries(current.sources)) {
3043
3065
  if (sources[k] === void 0) {
3044
3066
  sources[k] = clone2(v);
3045
3067
  carried.push(`sources[${JSON.stringify(k)}]`);
3046
3068
  }
3047
3069
  }
3048
- raw.sources = sources;
3049
- const config2 = normalize(raw);
3070
+ raw2.sources = sources;
3071
+ const config2 = normalize(raw2);
3050
3072
  return { report, config: config2, carried, diff: diffConfigs(current, config2), risks: listRisks(config2, schema2, current), secrets };
3051
3073
  }
3052
3074
 
@@ -3103,23 +3125,23 @@ function starterPage(has, o) {
3103
3125
  page.grid = { cols: 24, rows: 6, gap: 10, padding: 10 };
3104
3126
  page.gravity = "left";
3105
3127
  const tiles = [];
3106
- const add = (r, types2, title) => {
3128
+ const add2 = (r, types2, title) => {
3107
3129
  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));
3108
3130
  if (ws.length) tiles.push(newTile(r, ws));
3109
3131
  };
3110
3132
  const lead = "agents/sessions";
3111
3133
  const agents = o.agents !== false && ok(lead);
3112
3134
  if (agents) {
3113
- add({ x: 0, y: 0, w: 11, h: 6 }, [lead]);
3114
- add({ x: 11, y: 0, w: 5, h: 4 }, ["core/clock"]);
3135
+ add2({ x: 0, y: 0, w: 11, h: 6 }, [lead]);
3136
+ add2({ x: 11, y: 0, w: 5, h: 4 }, ["core/clock"]);
3115
3137
  } else {
3116
- add({ x: 0, y: 0, w: 11, h: 6 }, [["core/clock", { showDate: true }]]);
3117
- add({ x: 11, y: 0, w: 5, h: 4 }, ["core/date"]);
3138
+ add2({ x: 0, y: 0, w: 11, h: 6 }, [["core/clock", { showDate: true }]]);
3139
+ add2({ x: 11, y: 0, w: 5, h: 4 }, ["core/date"]);
3118
3140
  }
3119
- add({ x: 11, y: 4, w: 5, h: 2 }, ["weather/forecast", "mirror/compliments"]);
3120
- add({ x: 16, y: 0, w: 8, h: 6 }, ["vitals/vitals", "system/health", "usage/rail", "mirror/countdown"].filter(ok).slice(0, 3));
3141
+ add2({ x: 11, y: 4, w: 5, h: 2 }, ["weather/forecast", "mirror/compliments"]);
3142
+ add2({ x: 16, y: 0, w: 8, h: 6 }, ["vitals/vitals", "system/health", "usage/rail", "mirror/countdown"].filter(ok).slice(0, 3));
3121
3143
  if (!tiles.length) {
3122
- add({ 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
+ 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" }));
3123
3145
  const welcome = tiles[0]?.widgets[0];
3124
3146
  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 };
3125
3147
  }
@@ -3139,7 +3161,7 @@ var STARTER_TYPES = /* @__PURE__ */ new Set(["agents/sessions", "core/text", "co
3139
3161
  function looksLikeStarter(c) {
3140
3162
  if (c.screens.length !== 1) return false;
3141
3163
  const s = c.screens[0];
3142
- const named = (name, names) => Object.values(names).includes(name);
3164
+ const named = (name2, names) => Object.values(names).includes(name2);
3143
3165
  if (s.device.driver !== "virtual" || !named(s.name, STARTER_NAMES.screen) || s.pages.length !== 1) return false;
3144
3166
  const p = s.pages[0];
3145
3167
  return named(p.name, STARTER_NAMES.page) && p.tiles.length <= 4 && p.tiles.every((t2) => t2.widgets.every((w) => STARTER_TYPES.has(w.type)));
@@ -3460,7 +3482,7 @@ var PROBE = "\u9AD4";
3460
3482
  var missingPixels = /* @__PURE__ */ new Map();
3461
3483
  var available = /* @__PURE__ */ new Map();
3462
3484
  var probeCanvas = null;
3463
- function pixelsOf(font, probe = PROBE) {
3485
+ function pixelsOf(font, probe2 = PROBE) {
3464
3486
  probeCanvas ??= createCanvas4(40, 40);
3465
3487
  const g = probeCanvas.getContext("2d");
3466
3488
  g.clearRect(0, 0, 40, 40);
@@ -3468,16 +3490,16 @@ function pixelsOf(font, probe = PROBE) {
3468
3490
  else g.font = font;
3469
3491
  g.fillStyle = "#000";
3470
3492
  g.textBaseline = "top";
3471
- g.fillText(probe, 4, 4);
3493
+ g.fillText(probe2, 4, 4);
3472
3494
  return Buffer.from(g.getImageData(0, 0, 40, 40).data.buffer).toString("base64");
3473
3495
  }
3474
- function hasFontFamily(family, probe = PROBE) {
3475
- const key = `${family}\0${probe}`;
3496
+ function hasFontFamily(family, probe2 = PROBE) {
3497
+ const key = `${family}\0${probe2}`;
3476
3498
  let yes = available.get(key);
3477
3499
  if (yes === void 0) {
3478
- let missing = missingPixels.get(probe);
3479
- if (missing === void 0) missingPixels.set(probe, missing = pixelsOf('28px "Kiosko Missing Font"', probe));
3480
- yes = pixelsOf(`28px "${family.replace(/"/g, "")}"`, probe) !== missing;
3500
+ let missing = missingPixels.get(probe2);
3501
+ if (missing === void 0) missingPixels.set(probe2, missing = pixelsOf('28px "Kiosko Missing Font"', probe2));
3502
+ yes = pixelsOf(`28px "${family.replace(/"/g, "")}"`, probe2) !== missing;
3481
3503
  available.set(key, yes);
3482
3504
  }
3483
3505
  return yes;
@@ -3929,7 +3951,7 @@ var AnimationScheduler = class {
3929
3951
  };
3930
3952
 
3931
3953
  // packages/core/src/runtime.ts
3932
- import { EventEmitter } from "node:events";
3954
+ import { EventEmitter as EventEmitter2 } from "node:events";
3933
3955
  import { availableParallelism as availableParallelism2 } from "node:os";
3934
3956
 
3935
3957
  // packages/core/src/alerts.ts
@@ -3956,9 +3978,9 @@ function text(x, locale) {
3956
3978
  if (x && typeof x === "object" && typeof x.en === "string") return oneLine(localize(x, locale));
3957
3979
  return "";
3958
3980
  }
3959
- function parseAlert(raw, now, locale) {
3960
- if (!raw || typeof raw !== "object") throw new AlertError("an alert is an object", "badAlert");
3961
- const a = raw;
3981
+ function parseAlert(raw2, now, locale) {
3982
+ if (!raw2 || typeof raw2 !== "object") throw new AlertError("an alert is an object", "badAlert");
3983
+ const a = raw2;
3962
3984
  const id = typeof a.id === "string" ? a.id.trim() : "";
3963
3985
  if (!id || id.length > 120) throw new AlertError("an alert needs an id", "badAlert");
3964
3986
  if (!ALERT_LEVELS.includes(a.level)) throw new AlertError(`level must be one of ${ALERT_LEVELS.join(", ")}`, "badAlert");
@@ -4021,8 +4043,8 @@ var AlertBoard = class {
4021
4043
  this.fromPlugins = next;
4022
4044
  }
4023
4045
  /** An alert from outside (`POST /api/alerts`). The same id again replaces it, and it shows again. */
4024
- post(raw, now, locale, screenIds = []) {
4025
- const body2 = raw && typeof raw === "object" ? { ...raw } : raw;
4046
+ post(raw2, now, locale, screenIds = []) {
4047
+ const body2 = raw2 && typeof raw2 === "object" ? { ...raw2 } : raw2;
4026
4048
  if (body2 && typeof body2 === "object" && !body2.id) body2.id = `alert-${now.toString(36)}${Math.floor(Math.random() * 1296).toString(36)}`;
4027
4049
  for (const k of ["source", "detail"]) {
4028
4050
  const v = body2 && typeof body2 === "object" ? body2[k] : void 0;
@@ -4030,7 +4052,7 @@ var AlertBoard = class {
4030
4052
  }
4031
4053
  const a = parseAlert(body2, now, locale);
4032
4054
  if (!EXTERNAL_ID.test(a.id)) throw new AlertError('the id may have only letters, digits, ".", "_" and "-" (up to 80)', "badAlert");
4033
- const screens = raw.screens;
4055
+ const screens = raw2.screens;
4034
4056
  let only;
4035
4057
  if (screens !== void 0) {
4036
4058
  if (!Array.isArray(screens) || !screens.every((s) => typeof s === "string")) throw new AlertError("screens is a list of screen ids", "badAlert");
@@ -4101,9 +4123,9 @@ var AlertBoard = class {
4101
4123
  * settings let through (level, quiet hours; only `critical` while `off`),
4102
4124
  * with the count of the others. Its test alert always does.
4103
4125
  */
4104
- forScreen(screen, now, off = false) {
4126
+ forScreen(screen, now, off2 = false) {
4105
4127
  const cfg = screenAlerts(screen);
4106
- const onlyCritical = off || inQuietHours(cfg.quiet, now);
4128
+ const onlyCritical = off2 || inQuietHours(cfg.quiet, now);
4107
4129
  const min = Math.max(levelRank(cfg.minLevel), onlyCritical ? levelRank("critical") : 0);
4108
4130
  const here = this.list(now).filter((a) => !a.snoozedUntil && (!a.screens || a.screens.includes(screen.id)) && (a.origin === "test" || levelRank(a.level) >= min));
4109
4131
  return here.length ? { top: here[0], more: here.length - 1 } : null;
@@ -4408,12 +4430,12 @@ function parseHandshake(resp, pid) {
4408
4430
  const at = (i) => resp.length > i ? String(resp[i]) : "N/A";
4409
4431
  throw new UnrecognisedReply(`handshake validation failed (length ${resp.length}, [0]=${at(0)}, [1]=${at(1)}, [8]=${at(8)})`);
4410
4432
  }
4411
- const raw = resp.subarray(0, Math.min(resp.length, 64));
4433
+ const raw2 = resp.subarray(0, Math.min(resp.length, 64));
4412
4434
  if (variantOf(pid) === "ly") {
4413
4435
  const r = resp[20] <= 3 ? 1 : resp[20];
4414
- return { pm: 64 + r, sub: (resp[22] ?? 0) + 1, raw };
4436
+ return { pm: 64 + r, sub: (resp[22] ?? 0) + 1, raw: raw2 };
4415
4437
  }
4416
- return { pm: 49 + resp[20], sub: resp[22] ?? 0, raw };
4438
+ return { pm: 49 + resp[20], sub: resp[22] ?? 0, raw: raw2 };
4417
4439
  }
4418
4440
  var ANGLES_1920 = [180, 180, 0, 0, 0, 180, 180, 180, 180];
4419
4441
  var MODELS = {
@@ -4473,9 +4495,9 @@ var UsbUnavailable = class extends Error {
4473
4495
  async function loadUsb() {
4474
4496
  try {
4475
4497
  const m = await import("usb");
4476
- const mod = m.getDeviceList ? m : m.default?.getDeviceList ? m.default : m.usb;
4477
- if (!mod?.getDeviceList) throw new Error("the usb module has no getDeviceList");
4478
- return mod;
4498
+ const mod2 = m.getDeviceList ? m : m.default?.getDeviceList ? m.default : m.usb;
4499
+ if (!mod2?.getDeviceList) throw new Error("the usb module has no getDeviceList");
4500
+ return mod2;
4479
4501
  } catch (err) {
4480
4502
  throw new UsbUnavailable(`cannot load the "usb" package (libusb): ${err instanceof Error ? err.message : String(err)}. Install it with: npm install usb`);
4481
4503
  }
@@ -4643,10 +4665,10 @@ function usbPathForSerial(serial, root = "/sys/bus/usb/devices") {
4643
4665
  } catch {
4644
4666
  return null;
4645
4667
  }
4646
- for (const name of entries) {
4647
- if (!/^\d+-[\d.]+$/.test(name)) continue;
4668
+ for (const name2 of entries) {
4669
+ if (!/^\d+-[\d.]+$/.test(name2)) continue;
4648
4670
  try {
4649
- if (readFileSync2(`${root}/${name}/serial`, "utf8").trim() === serial) return name;
4671
+ if (readFileSync2(`${root}/${name2}/serial`, "utf8").trim() === serial) return name2;
4650
4672
  } catch {
4651
4673
  }
4652
4674
  }
@@ -4819,6 +4841,1002 @@ function pinFrame(o, key, intervalS, onError) {
4819
4841
  };
4820
4842
  }
4821
4843
 
4844
+ // packages/core/src/remote/crypto.ts
4845
+ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual } from "node:crypto";
4846
+
4847
+ // packages/core/src/remote/p256.ts
4848
+ var P = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn;
4849
+ var N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
4850
+ var B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn;
4851
+ var GX = 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n;
4852
+ var GY = 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n;
4853
+ var G = { x: GX, y: GY };
4854
+ var mod = (a, m = P) => (a % m + m) % m;
4855
+ function pow(a, e, m = P) {
4856
+ let r = 1n;
4857
+ a = mod(a, m);
4858
+ while (e > 0n) {
4859
+ if (e & 1n) r = r * a % m;
4860
+ a = a * a % m;
4861
+ e >>= 1n;
4862
+ }
4863
+ return r;
4864
+ }
4865
+ var inv = (a, m = P) => pow(a, m - 2n, m);
4866
+ function onCurve(p) {
4867
+ if (!p) return false;
4868
+ if (p.x < 0n || p.x >= P || p.y < 0n || p.y >= P) return false;
4869
+ return mod(p.y * p.y - (p.x * p.x * p.x - 3n * p.x + B)) === 0n;
4870
+ }
4871
+ var toJac = (p) => p ? { x: p.x, y: p.y, z: 1n } : { x: 1n, y: 1n, z: 0n };
4872
+ function toAffine(j) {
4873
+ if (j.z === 0n) return null;
4874
+ const zi = inv(j.z);
4875
+ const zi2 = zi * zi % P;
4876
+ return { x: mod(j.x * zi2), y: mod(j.y * zi2 * zi) };
4877
+ }
4878
+ function dbl(p) {
4879
+ if (p.z === 0n || p.y === 0n) return { x: 1n, y: 1n, z: 0n };
4880
+ const z2 = mod(p.z * p.z);
4881
+ const m = mod(3n * (p.x - z2) * (p.x + z2));
4882
+ const y2 = mod(p.y * p.y);
4883
+ const s = mod(4n * p.x * y2);
4884
+ const x = mod(m * m - 2n * s);
4885
+ const y = mod(m * (s - x) - 8n * y2 * y2);
4886
+ return { x, y, z: mod(2n * p.y * p.z) };
4887
+ }
4888
+ function add(p, q3) {
4889
+ if (p.z === 0n) return q3;
4890
+ if (q3.z === 0n) return p;
4891
+ const z1 = mod(p.z * p.z), z2 = mod(q3.z * q3.z);
4892
+ const u1 = mod(p.x * z2), u2 = mod(q3.x * z1);
4893
+ const s1 = mod(p.y * z2 * q3.z), s2 = mod(q3.y * z1 * p.z);
4894
+ if (u1 === u2) return s1 === s2 ? dbl(p) : { x: 1n, y: 1n, z: 0n };
4895
+ const h = mod(u2 - u1), r = mod(s2 - s1);
4896
+ const h2 = mod(h * h), h3 = mod(h2 * h);
4897
+ const x = mod(r * r - h3 - 2n * u1 * h2);
4898
+ const y = mod(r * (u1 * h2 - x) - s1 * h3);
4899
+ return { x, y, z: mod(h * p.z * q3.z) };
4900
+ }
4901
+ function pointAdd(a, b) {
4902
+ return toAffine(add(toJac(a), toJac(b)));
4903
+ }
4904
+ function pointNeg(a) {
4905
+ return a ? { x: a.x, y: mod(-a.y) } : null;
4906
+ }
4907
+ function mul(k, p) {
4908
+ k = mod(k, N);
4909
+ let r = { x: 1n, y: 1n, z: 0n };
4910
+ let q3 = toJac(p);
4911
+ let r1 = q3;
4912
+ for (let i = 255; i >= 0; i--) {
4913
+ if (k >> BigInt(i) & 1n) {
4914
+ r = add(r, r1);
4915
+ r1 = dbl(r1);
4916
+ } else {
4917
+ r1 = add(r, r1);
4918
+ r = dbl(r);
4919
+ }
4920
+ }
4921
+ q3 = r;
4922
+ return toAffine(q3);
4923
+ }
4924
+ var hex32 = (n) => n.toString(16).padStart(64, "0");
4925
+ function encodePoint(p) {
4926
+ if (!p) throw new Error("cannot encode the point at infinity");
4927
+ return Buffer.from("04" + hex32(p.x) + hex32(p.y), "hex");
4928
+ }
4929
+ function decodePoint(b) {
4930
+ const buf = Buffer.from(b);
4931
+ let p;
4932
+ if (buf.length === 65 && buf[0] === 4) {
4933
+ p = { x: BigInt("0x" + buf.subarray(1, 33).toString("hex")), y: BigInt("0x" + buf.subarray(33).toString("hex")) };
4934
+ } else if (buf.length === 33 && (buf[0] === 2 || buf[0] === 3)) {
4935
+ const x = BigInt("0x" + buf.subarray(1).toString("hex"));
4936
+ const rhs = mod(x * x * x - 3n * x + B);
4937
+ let y = pow(rhs, (P + 1n) / 4n);
4938
+ if (mod(y * y) !== rhs) throw new Error("not a point of P-256");
4939
+ if ((y & 1n) !== BigInt(buf[0] - 2)) y = mod(-y);
4940
+ p = { x, y };
4941
+ } else throw new Error("bad point encoding");
4942
+ if (!onCurve(p)) throw new Error("not a point of P-256");
4943
+ return p;
4944
+ }
4945
+ var scalarFrom = (b) => BigInt("0x" + (Buffer.from(b).toString("hex") || "0"));
4946
+ var scalarBytes = (n) => Buffer.from(hex32(n), "hex");
4947
+
4948
+ // packages/core/src/remote/crypto.ts
4949
+ var PROTO = 1;
4950
+ var PORT = 7428;
4951
+ var NONCE_LEN = 32;
4952
+ var KEY_LEN = 32;
4953
+ var TAG_LEN = 16;
4954
+ var ID_A = "kiosko";
4955
+ var mn = null;
4956
+ function spakePoints() {
4957
+ mn ??= {
4958
+ M: decodePoint(Buffer.from("02886e2f97ace46e55ba9dd7242579f2993b64e16ef3dcab95afd497333d8fa12f", "hex")),
4959
+ N: decodePoint(Buffer.from("03d8bbd6c639c62937b04d997f38c3770719c629d7014d49a24b4f98baa1292b49", "hex"))
4960
+ };
4961
+ return mn;
4962
+ }
4963
+ var LABEL_AUTH_K = "KSv1 auth kiosko";
4964
+ var LABEL_AUTH_D = "KSv1 auth screen";
4965
+ var hkdf = (ikm, salt, info, len) => Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from(info), len));
4966
+ var hmac = (key, ...parts) => {
4967
+ const h = createHmac("sha256", key);
4968
+ for (const p of parts) h.update(p);
4969
+ return h.digest();
4970
+ };
4971
+ function equal2(a, b) {
4972
+ return a.length === b.length && timingSafeEqual(a, b);
4973
+ }
4974
+ function authMac(key, label, nk, nd, uid) {
4975
+ return hmac(key, label, nk, nd, uid);
4976
+ }
4977
+ function sessionKeys(key, nk, nd, side) {
4978
+ const okm = hkdf(key, Buffer.concat([nk, nd]), "KSv1 session", 64);
4979
+ const k2d = okm.subarray(0, 32), d2k = okm.subarray(32);
4980
+ 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 } };
4981
+ }
4982
+ function nonceOf(seq) {
4983
+ const n = Buffer.alloc(12);
4984
+ n.writeBigUInt64BE(seq, 4);
4985
+ return n;
4986
+ }
4987
+ function seal(d, type, payload) {
4988
+ const len = 1 + payload.length + TAG_LEN;
4989
+ const hdr = Buffer.alloc(4);
4990
+ hdr.writeUInt32BE(len);
4991
+ const c = createCipheriv("chacha20-poly1305", d.key, nonceOf(d.seq), { authTagLength: TAG_LEN });
4992
+ c.setAAD(hdr, { plaintextLength: len - TAG_LEN });
4993
+ const out = Buffer.concat([hdr, c.update(Buffer.from([type])), c.update(payload), c.final(), c.getAuthTag()]);
4994
+ d.seq++;
4995
+ return out;
4996
+ }
4997
+ function open(d, hdr, body2) {
4998
+ if (body2.length < TAG_LEN + 1) throw new Error("sealed message too short");
4999
+ const dc = createDecipheriv("chacha20-poly1305", d.key, nonceOf(d.seq), { authTagLength: TAG_LEN });
5000
+ dc.setAAD(hdr, { plaintextLength: body2.length - TAG_LEN });
5001
+ dc.setAuthTag(body2.subarray(body2.length - TAG_LEN));
5002
+ const pt = Buffer.concat([dc.update(body2.subarray(0, body2.length - TAG_LEN)), dc.final()]);
5003
+ d.seq++;
5004
+ return { type: pt[0], payload: pt.subarray(1) };
5005
+ }
5006
+ function spakeW(uid, code) {
5007
+ const h = createHash("sha256").update("KSv1 pake w").update(uid).update(":").update(code).digest();
5008
+ return scalarFrom(h) % N;
5009
+ }
5010
+ function le64(n) {
5011
+ const b = Buffer.alloc(8);
5012
+ b.writeBigUInt64LE(BigInt(n));
5013
+ return b;
5014
+ }
5015
+ function transcript(uid, X, Y, K, w) {
5016
+ const parts = [Buffer.from(ID_A), Buffer.from(uid), X, Y, K, scalarBytes(w)];
5017
+ return Buffer.concat(parts.flatMap((p) => [le64(p.length), p]));
5018
+ }
5019
+ function spakeKeys(tt) {
5020
+ const h = createHash("sha256").update(tt).digest();
5021
+ const kc = hkdf(h, Buffer.alloc(0), "KSv1 confirm", 64);
5022
+ return { key: hkdf(h, Buffer.alloc(0), "KSv1 pair key", 32), cA: hmac(kc.subarray(0, 32), tt), cB: hmac(kc.subarray(32), tt) };
5023
+ }
5024
+ var randomScalar = () => {
5025
+ for (; ; ) {
5026
+ const k = scalarFrom(randomBytes(32));
5027
+ if (k > 0n && k < N) return k;
5028
+ }
5029
+ };
5030
+ var SpakeA = class {
5031
+ X;
5032
+ x;
5033
+ w;
5034
+ uid;
5035
+ constructor(uid, code, x) {
5036
+ this.uid = uid;
5037
+ this.w = spakeW(uid, code);
5038
+ this.x = x ?? randomScalar();
5039
+ this.X = encodePoint(pointAdd(mul(this.x, G), mul(this.w, spakePoints().M)));
5040
+ }
5041
+ finish(Yb) {
5042
+ const Y = decodePoint(Yb);
5043
+ const K = mul(this.x, pointAdd(Y, pointNeg(mul(this.w, spakePoints().N))));
5044
+ if (!K) throw new Error("bad Y");
5045
+ const Kb = encodePoint(K);
5046
+ return { ...spakeKeys(transcript(this.uid, this.X, encodePoint(Y), Kb, this.w)), K: Kb };
5047
+ }
5048
+ };
5049
+
5050
+ // packages/core/src/remote/link.ts
5051
+ import { connect } from "node:net";
5052
+ import { randomBytes as randomBytes2 } from "node:crypto";
5053
+ var T = {
5054
+ HELLO: 1,
5055
+ INFO: 2,
5056
+ AUTH: 3,
5057
+ AUTH_OK: 4,
5058
+ ERROR: 5,
5059
+ PAIR_START: 6,
5060
+ PAIR_READY: 7,
5061
+ PAIR_X: 8,
5062
+ PAIR_Y: 9,
5063
+ PAIR_CONFIRM: 10,
5064
+ PAIR_OK: 11,
5065
+ FRAME: 16,
5066
+ ACK: 17,
5067
+ SET: 18,
5068
+ STATE: 19,
5069
+ LED: 20,
5070
+ PING: 21,
5071
+ PONG: 22,
5072
+ UNPAIR: 23,
5073
+ OTA_BEGIN: 24,
5074
+ OTA_ACK: 25,
5075
+ OTA_DATA: 26,
5076
+ OTA_END: 27,
5077
+ OTA_DONE: 28,
5078
+ LOGS: 29
5079
+ };
5080
+ var ScreenError = class extends Error {
5081
+ code;
5082
+ constructor(code, message) {
5083
+ super(message);
5084
+ this.code = code;
5085
+ this.name = "ScreenError";
5086
+ }
5087
+ };
5088
+ var MAX_MSG = 1 << 20;
5089
+ var Wire = class _Wire {
5090
+ buf = Buffer.alloc(0);
5091
+ waiting = null;
5092
+ queue = [];
5093
+ ended = null;
5094
+ sock;
5095
+ constructor(sock) {
5096
+ this.sock = sock;
5097
+ sock.setNoDelay(true);
5098
+ sock.on("data", (d) => this.onData(d));
5099
+ const end = (e) => this.fail(e ?? new Error("connection closed"));
5100
+ sock.on("error", end);
5101
+ sock.on("close", () => end());
5102
+ }
5103
+ static open(host, port = PORT, timeoutMs = 4e3) {
5104
+ return new Promise((resolve8, reject) => {
5105
+ const s = connect({ host, port });
5106
+ const t2 = setTimeout(() => {
5107
+ s.destroy();
5108
+ reject(Object.assign(new Error(`no answer from ${host}:${port}`), { code: "ETIMEDOUT" }));
5109
+ }, timeoutMs);
5110
+ s.once("connect", () => {
5111
+ clearTimeout(t2);
5112
+ s.setKeepAlive(true, 1e4);
5113
+ resolve8(new _Wire(s));
5114
+ });
5115
+ s.once("error", (e) => {
5116
+ clearTimeout(t2);
5117
+ reject(e);
5118
+ });
5119
+ });
5120
+ }
5121
+ onData(d) {
5122
+ this.buf = this.buf.length ? Buffer.concat([this.buf, d]) : d;
5123
+ while (this.buf.length >= 4) {
5124
+ const len = this.buf.readUInt32BE(0);
5125
+ if (len < 1 || len > MAX_MSG) return this.fail(new Error(`bad message length ${len}`));
5126
+ if (this.buf.length < 4 + len) break;
5127
+ const m = { hdr: Buffer.from(this.buf.subarray(0, 4)), body: Buffer.from(this.buf.subarray(4, 4 + len)) };
5128
+ this.buf = this.buf.subarray(4 + len);
5129
+ if (this.waiting) {
5130
+ const w = this.waiting;
5131
+ this.waiting = null;
5132
+ w.resolve(m);
5133
+ } else this.queue.push(m);
5134
+ }
5135
+ }
5136
+ fail(e) {
5137
+ if (this.ended) return;
5138
+ this.ended = e;
5139
+ this.sock.destroy();
5140
+ const w = this.waiting;
5141
+ this.waiting = null;
5142
+ w?.reject(e);
5143
+ }
5144
+ get closed() {
5145
+ return !!this.ended;
5146
+ }
5147
+ /** The next message, raw; rejects on close or after `timeoutMs`. */
5148
+ next(timeoutMs = 1e4) {
5149
+ const q3 = this.queue.shift();
5150
+ if (q3) return Promise.resolve(q3);
5151
+ if (this.ended) return Promise.reject(this.ended);
5152
+ return new Promise((resolve8, reject) => {
5153
+ const t2 = setTimeout(() => {
5154
+ this.waiting = null;
5155
+ reject(Object.assign(new Error("the screen stopped answering"), { code: "ETIMEDOUT" }));
5156
+ }, timeoutMs);
5157
+ this.waiting = {
5158
+ resolve: (m) => {
5159
+ clearTimeout(t2);
5160
+ resolve8(m);
5161
+ },
5162
+ reject: (e) => {
5163
+ clearTimeout(t2);
5164
+ reject(e);
5165
+ }
5166
+ };
5167
+ });
5168
+ }
5169
+ write(b) {
5170
+ if (!this.ended) this.sock.write(b);
5171
+ }
5172
+ sendPlain(type, obj) {
5173
+ const p = Buffer.from(JSON.stringify(obj));
5174
+ const h = Buffer.alloc(5);
5175
+ h.writeUInt32BE(p.length + 1);
5176
+ h[4] = type;
5177
+ this.write(Buffer.concat([h, p]));
5178
+ }
5179
+ /** A plain message of type `want` (JSON); an ERROR from the screen becomes a ScreenError. */
5180
+ async plain(want, timeoutMs = 1e4) {
5181
+ const { body: body2 } = await this.next(timeoutMs);
5182
+ let j;
5183
+ try {
5184
+ j = JSON.parse(body2.subarray(1).toString("utf8"));
5185
+ } catch {
5186
+ throw new Error("the screen sent something unreadable");
5187
+ }
5188
+ if (body2[0] === T.ERROR) throw new ScreenError(String(j.code ?? "error"), String(j.msg ?? "refused"));
5189
+ if (body2[0] !== want) throw new Error(`unexpected message 0x${body2[0].toString(16)} from the screen`);
5190
+ return j;
5191
+ }
5192
+ close() {
5193
+ this.fail(new Error("closed"));
5194
+ }
5195
+ };
5196
+ function toInfo(j) {
5197
+ const num = (v, d = 0) => typeof v === "number" && Number.isFinite(v) ? v : d;
5198
+ 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) };
5199
+ }
5200
+ async function hello(w, want) {
5201
+ const nk = randomBytes2(NONCE_LEN);
5202
+ w.sendPlain(T.HELLO, { proto: PROTO, nonce: nk.toString("hex"), want });
5203
+ const j = await w.plain(T.INFO);
5204
+ const nd = Buffer.from(String(j.nonce ?? ""), "hex");
5205
+ if (nd.length !== NONCE_LEN) throw new Error("the screen sent no nonce");
5206
+ const info = toInfo(j);
5207
+ if (info.proto !== PROTO) {
5208
+ throw new ScreenError("proto", `the screen speaks protocol ${info.proto}, this Kiosko ${PROTO}: update one of them`);
5209
+ }
5210
+ return { info, nk, nd };
5211
+ }
5212
+ async function probe(host, port = PORT) {
5213
+ const w = await Wire.open(host, port);
5214
+ try {
5215
+ return (await hello(w, "info")).info;
5216
+ } finally {
5217
+ w.close();
5218
+ }
5219
+ }
5220
+ async function openSession(host, port, key, expectUid) {
5221
+ if (key.length !== KEY_LEN) throw new ScreenError("notPaired", "no pairing key for this screen");
5222
+ const wire = await Wire.open(host, port);
5223
+ try {
5224
+ const { info, nk, nd } = await hello(wire, "session");
5225
+ if (expectUid && info.uid !== expectUid) throw new ScreenError("otherScreen", `another screen (${info.id}, ${info.uid}) answers at ${host}`);
5226
+ wire.sendPlain(T.AUTH, { mac: authMac(key, LABEL_AUTH_K, nk, nd, info.uid).toString("hex") });
5227
+ const ok = await wire.plain(T.AUTH_OK);
5228
+ const want = authMac(key, LABEL_AUTH_D, nk, nd, info.uid);
5229
+ 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");
5230
+ return { wire, info, session: sessionKeys(key, nk, nd, "kiosko") };
5231
+ } catch (err) {
5232
+ wire.close();
5233
+ throw err;
5234
+ }
5235
+ }
5236
+ function sendSealed(wire, s, type, payload = {}) {
5237
+ wire.write(seal(s.tx, type, Buffer.isBuffer(payload) ? payload : Buffer.from(JSON.stringify(payload))));
5238
+ }
5239
+ async function nextSealed(wire, s, timeoutMs = 15e3) {
5240
+ const { hdr, body: body2 } = await wire.next(timeoutMs);
5241
+ const m = open(s.rx, hdr, body2);
5242
+ return { ...m, json: () => JSON.parse(m.payload.toString("utf8") || "{}") };
5243
+ }
5244
+ var Pairing = class _Pairing {
5245
+ info;
5246
+ ttl;
5247
+ wire;
5248
+ done = false;
5249
+ constructor(wire, info, ttl) {
5250
+ this.wire = wire;
5251
+ this.info = info;
5252
+ this.ttl = ttl;
5253
+ }
5254
+ static async start(host, port, name2) {
5255
+ const wire = await Wire.open(host, port);
5256
+ try {
5257
+ const { info } = await hello(wire, "pair");
5258
+ wire.sendPlain(T.PAIR_START, { name: name2.slice(0, 40) });
5259
+ const r = await wire.plain(T.PAIR_READY);
5260
+ return new _Pairing(wire, info, typeof r.ttl === "number" ? r.ttl : 120);
5261
+ } catch (err) {
5262
+ wire.close();
5263
+ throw err;
5264
+ }
5265
+ }
5266
+ async finish(code) {
5267
+ if (this.done) throw new ScreenError("pairingOver", "this pairing is over: start again");
5268
+ this.done = true;
5269
+ try {
5270
+ const clean = code.replace(/\D/g, "");
5271
+ if (clean.length !== 6) throw new ScreenError("badCode", "the code has 6 digits");
5272
+ const a = new SpakeA(this.info.uid, clean);
5273
+ this.wire.sendPlain(T.PAIR_X, { X: a.X.toString("hex") });
5274
+ const y = await this.wire.plain(T.PAIR_Y, 15e3);
5275
+ const k = a.finish(Buffer.from(String(y.Y ?? ""), "hex"));
5276
+ if (!equal2(Buffer.from(String(y.c ?? ""), "hex"), k.cB)) {
5277
+ this.wire.sendPlain(T.PAIR_CONFIRM, { c: "00".repeat(32) });
5278
+ throw new ScreenError("badCode", "the code does not match the one on the screen");
5279
+ }
5280
+ this.wire.sendPlain(T.PAIR_CONFIRM, { c: k.cA.toString("hex") });
5281
+ await this.wire.plain(T.PAIR_OK, 15e3);
5282
+ return k.key;
5283
+ } finally {
5284
+ this.wire.close();
5285
+ }
5286
+ }
5287
+ cancel() {
5288
+ this.done = true;
5289
+ this.wire.close();
5290
+ }
5291
+ };
5292
+
5293
+ // packages/core/src/remote/mdns.ts
5294
+ import { createSocket } from "node:dgram";
5295
+ import { EventEmitter } from "node:events";
5296
+ import { networkInterfaces } from "node:os";
5297
+ var SERVICE = "_kiosko-screen._tcp.local";
5298
+ var service = SERVICE;
5299
+ var GROUP = "224.0.0.251";
5300
+ var MDNS_PORT = 5353;
5301
+ var TYPE = { A: 1, PTR: 12, TXT: 16, SRV: 33, ANY: 255 };
5302
+ function encodeName(name2) {
5303
+ const parts = name2.replace(/\.$/, "").split(".");
5304
+ return Buffer.concat([...parts.map((p) => Buffer.concat([Buffer.from([Buffer.byteLength(p)]), Buffer.from(p)])), Buffer.from([0])]);
5305
+ }
5306
+ function buildQuery(name2, type, unicast = false) {
5307
+ const h = Buffer.alloc(12);
5308
+ h.writeUInt16BE(1, 4);
5309
+ const q3 = Buffer.alloc(4);
5310
+ q3.writeUInt16BE(type, 0);
5311
+ q3.writeUInt16BE(unicast ? 32769 : 1, 2);
5312
+ return Buffer.concat([h, encodeName(name2), q3]);
5313
+ }
5314
+ function readName(b, at) {
5315
+ const labels = [];
5316
+ let next = -1;
5317
+ for (let hops = 0; hops < 32; hops++) {
5318
+ if (at >= b.length) throw new Error("truncated name");
5319
+ const len = b[at];
5320
+ if (len === 0) {
5321
+ if (next < 0) next = at + 1;
5322
+ return { name: labels.join("."), next };
5323
+ }
5324
+ if ((len & 192) === 192) {
5325
+ if (next < 0) next = at + 2;
5326
+ at = (len & 63) << 8 | b[at + 1];
5327
+ continue;
5328
+ }
5329
+ labels.push(b.toString("utf8", at + 1, at + 1 + len));
5330
+ at += 1 + len;
5331
+ }
5332
+ throw new Error("name loop");
5333
+ }
5334
+ function parseResponse(b) {
5335
+ if (b.length < 12) return [];
5336
+ const flags = b.readUInt16BE(2);
5337
+ if (!(flags & 32768)) return [];
5338
+ const qd = b.readUInt16BE(4);
5339
+ const total = b.readUInt16BE(6) + b.readUInt16BE(8) + b.readUInt16BE(10);
5340
+ let at = 12;
5341
+ for (let i = 0; i < qd; i++) at = readName(b, at).next + 4;
5342
+ const out = [];
5343
+ for (let i = 0; i < total && at < b.length; i++) {
5344
+ const { name: name2, next } = readName(b, at);
5345
+ at = next;
5346
+ if (at + 10 > b.length) break;
5347
+ const type = b.readUInt16BE(at);
5348
+ const ttl = b.readUInt32BE(at + 4);
5349
+ const len = b.readUInt16BE(at + 8);
5350
+ const rd = at + 10;
5351
+ at = rd + len;
5352
+ if (at > b.length) break;
5353
+ const r = { name: name2.toLowerCase(), type, ttl, data: {} };
5354
+ if (type === TYPE.PTR) r.data.ptr = readName(b, rd).name;
5355
+ else if (type === TYPE.SRV) r.data.srv = { port: b.readUInt16BE(rd + 4), target: readName(b, rd + 6).name.toLowerCase() };
5356
+ else if (type === TYPE.A && len === 4) r.data.a = `${b[rd]}.${b[rd + 1]}.${b[rd + 2]}.${b[rd + 3]}`;
5357
+ else if (type === TYPE.TXT) {
5358
+ const txt = {};
5359
+ for (let p = rd; p < rd + len; ) {
5360
+ const l = b[p];
5361
+ const s = b.toString("utf8", p + 1, p + 1 + l);
5362
+ const eq = s.indexOf("=");
5363
+ if (eq > 0) txt[s.slice(0, eq).toLowerCase()] = s.slice(eq + 1);
5364
+ p += 1 + l;
5365
+ }
5366
+ r.data.txt = txt;
5367
+ } else continue;
5368
+ out.push(r);
5369
+ }
5370
+ return out;
5371
+ }
5372
+ var ScreenBrowser = class extends EventEmitter {
5373
+ sock = null;
5374
+ starting = null;
5375
+ instances = /* @__PURE__ */ new Map();
5376
+ hosts = /* @__PURE__ */ new Map();
5377
+ found = /* @__PURE__ */ new Map();
5378
+ timer = null;
5379
+ users = 0;
5380
+ shared = true;
5381
+ /** Starts listening (idempotent). */
5382
+ start() {
5383
+ this.starting ??= new Promise((resolve8) => {
5384
+ const s = createSocket({ type: "udp4", reuseAddr: true });
5385
+ let bound = false;
5386
+ s.on("message", (m) => this.onMessage(m));
5387
+ s.on("error", () => void 0);
5388
+ s.once("error", () => {
5389
+ if (bound) return;
5390
+ s.close();
5391
+ this.shared = false;
5392
+ const e = createSocket({ type: "udp4" });
5393
+ e.on("message", (m) => this.onMessage(m));
5394
+ e.on("error", () => void 0);
5395
+ e.bind(0, () => {
5396
+ e.unref();
5397
+ this.sock = e;
5398
+ resolve8();
5399
+ });
5400
+ });
5401
+ s.bind(MDNS_PORT, () => {
5402
+ bound = true;
5403
+ s.unref();
5404
+ try {
5405
+ let joined = false;
5406
+ for (const list2 of Object.values(networkInterfaces())) {
5407
+ for (const i of list2 ?? []) {
5408
+ if (i.family !== "IPv4" || i.internal) continue;
5409
+ try {
5410
+ s.addMembership(GROUP, i.address);
5411
+ joined = true;
5412
+ } catch {
5413
+ }
5414
+ }
5415
+ }
5416
+ if (!joined) s.addMembership(GROUP);
5417
+ s.setMulticastTTL(255);
5418
+ } catch {
5419
+ }
5420
+ this.sock = s;
5421
+ resolve8();
5422
+ });
5423
+ });
5424
+ return this.starting;
5425
+ }
5426
+ send(name2, type) {
5427
+ if (!this.sock) return;
5428
+ try {
5429
+ this.sock.send(buildQuery(name2, type, !this.shared), MDNS_PORT, GROUP);
5430
+ } catch {
5431
+ }
5432
+ }
5433
+ /** Asks the LAN for screens now; answers come as `found`. */
5434
+ query() {
5435
+ this.send(service, TYPE.PTR);
5436
+ }
5437
+ onMessage(m) {
5438
+ let recs;
5439
+ try {
5440
+ recs = parseResponse(m);
5441
+ } catch {
5442
+ return;
5443
+ }
5444
+ if (!recs.length) return;
5445
+ const now = Date.now();
5446
+ const touched = /* @__PURE__ */ new Set();
5447
+ for (const r of recs) {
5448
+ if (r.type === TYPE.PTR && r.name === service && r.data.ptr) {
5449
+ const inst = r.data.ptr.toLowerCase();
5450
+ if (!this.instances.has(inst)) this.instances.set(inst, { instance: inst });
5451
+ touched.add(inst);
5452
+ } else if (r.type === TYPE.SRV && r.name.endsWith(`.${service}`)) {
5453
+ const p = this.instances.get(r.name) ?? { instance: r.name };
5454
+ p.srv = r.data.srv;
5455
+ this.instances.set(r.name, p);
5456
+ touched.add(r.name);
5457
+ } else if (r.type === TYPE.TXT && r.name.endsWith(`.${service}`)) {
5458
+ const p = this.instances.get(r.name) ?? { instance: r.name };
5459
+ p.txt = r.data.txt;
5460
+ this.instances.set(r.name, p);
5461
+ touched.add(r.name);
5462
+ } else if (r.type === TYPE.A && r.data.a) {
5463
+ this.hosts.set(r.name, { a: r.data.a, at: now });
5464
+ for (const [k, p] of this.instances) if (p.srv?.target === r.name) touched.add(k);
5465
+ }
5466
+ }
5467
+ for (const k of touched) {
5468
+ const p = this.instances.get(k);
5469
+ if (!p) continue;
5470
+ if (!p.srv || !p.txt) this.send(k, TYPE.ANY);
5471
+ else if (!this.hosts.has(p.srv.target)) this.send(p.srv.target, TYPE.A);
5472
+ const s = this.complete(p, now);
5473
+ if (!s) continue;
5474
+ const before = this.found.get(s.uid);
5475
+ this.found.set(s.uid, s);
5476
+ this.emit("found", s, before);
5477
+ }
5478
+ }
5479
+ complete(p, now) {
5480
+ const t2 = p.txt;
5481
+ if (!t2?.uid || !p.srv) return null;
5482
+ const host = this.hosts.get(p.srv.target);
5483
+ if (!host) return null;
5484
+ const n = (v) => v && /^\d+$/.test(v) ? Number(v) : 0;
5485
+ 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 };
5486
+ }
5487
+ /** The screen with this uid, if heard of in the last `maxAgeMs`. */
5488
+ get(uid, maxAgeMs = 30 * 6e4) {
5489
+ const s = this.found.get(uid);
5490
+ return s && Date.now() - s.seenAt <= maxAgeMs ? s : void 0;
5491
+ }
5492
+ /** Screens heard of recently. */
5493
+ list(maxAgeMs = 10 * 6e4) {
5494
+ const now = Date.now();
5495
+ return [...this.found.values()].filter((s) => now - s.seenAt <= maxAgeMs).sort((a, b) => a.id.localeCompare(b.id));
5496
+ }
5497
+ /** Asks, waits `ms` for answers, and gives what it heard in that time (and before). */
5498
+ async browse(ms = 1500) {
5499
+ await this.start();
5500
+ const since = Date.now();
5501
+ this.query();
5502
+ await new Promise((r) => setTimeout(r, ms / 2));
5503
+ this.query();
5504
+ await new Promise((r) => setTimeout(r, ms / 2));
5505
+ return this.list().filter((s) => s.seenAt >= since - 6e4);
5506
+ }
5507
+ /** A remote screen holds it: asks again every minute while someone does. */
5508
+ retain() {
5509
+ this.users++;
5510
+ void this.start().then(() => this.query());
5511
+ if (!this.timer) {
5512
+ this.timer = setInterval(() => this.query(), 6e4);
5513
+ this.timer.unref();
5514
+ }
5515
+ }
5516
+ release() {
5517
+ if (--this.users > 0) return;
5518
+ this.users = 0;
5519
+ if (this.timer) clearInterval(this.timer);
5520
+ this.timer = null;
5521
+ }
5522
+ close() {
5523
+ this.release();
5524
+ this.sock?.close();
5525
+ this.sock = null;
5526
+ this.starting = null;
5527
+ }
5528
+ };
5529
+ var shared = null;
5530
+ function browser() {
5531
+ shared ??= new ScreenBrowser();
5532
+ shared.setMaxListeners(64);
5533
+ return shared;
5534
+ }
5535
+
5536
+ // packages/core/src/remote/device.ts
5537
+ var ROTATIONS = [0, 90, 180, 270];
5538
+ function brightnessOf(v) {
5539
+ return typeof v === "number" && Number.isFinite(v) ? Math.min(100, Math.max(0, Math.round(v))) : null;
5540
+ }
5541
+ var RemoteDevice = class {
5542
+ status;
5543
+ cfg;
5544
+ log;
5545
+ rotate;
5546
+ rotDirty = false;
5547
+ deps;
5548
+ key;
5549
+ mdns;
5550
+ latest = null;
5551
+ latestNum = 0;
5552
+ fresh = false;
5553
+ led = null;
5554
+ ledDirty = false;
5555
+ closed = false;
5556
+ paused = 0;
5557
+ wire = null;
5558
+ failures = 0;
5559
+ lastSay = "";
5560
+ frameTimes = [];
5561
+ running = null;
5562
+ idle = [];
5563
+ connected = false;
5564
+ waiters = /* @__PURE__ */ new Set();
5565
+ onFound = (s) => {
5566
+ if (s.uid === this.cfg.uid) this.notify("found");
5567
+ };
5568
+ constructor(cfg, log, rotate = 0, deps = {}) {
5569
+ this.cfg = cfg;
5570
+ this.log = log;
5571
+ this.rotate = ROTATIONS.includes(rotate) ? rotate : 0;
5572
+ this.deps = { retryMs: 1e3, maxRetryMs: 3e4, pingMs: 5e3, ...deps };
5573
+ this.key = /^[0-9a-f]{64}$/i.test(cfg.key ?? "") ? Buffer.from(cfg.key, "hex") : null;
5574
+ this.mdns = deps.browser ?? browser();
5575
+ this.status = {
5576
+ driver: "remote",
5577
+ ok: false,
5578
+ message: "connecting\u2026",
5579
+ code: "connecting",
5580
+ framesSent: 0,
5581
+ lastSentAt: null,
5582
+ 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, tempC: null, bright: null }
5583
+ };
5584
+ this.mdns.retain();
5585
+ this.mdns.on("found", this.onFound);
5586
+ if (!this.key) this.say(`${this.name()}: not paired yet (pair it in the editor: Screens \u2192 Detect panels)`, false, "remoteNotPaired", { id: this.name() });
5587
+ else this.running = this.run();
5588
+ }
5589
+ name() {
5590
+ return this.status?.remote.id || this.cfg.id || this.cfg.uid;
5591
+ }
5592
+ say(message, ok, code, params) {
5593
+ Object.assign(this.status, { ok, message, code, params });
5594
+ if (code !== this.lastSay) {
5595
+ this.lastSay = code;
5596
+ this.log(message);
5597
+ }
5598
+ }
5599
+ notify(why2) {
5600
+ for (const w of [...this.waiters]) w(why2);
5601
+ }
5602
+ /** Waits up to `ms` for one of `on` (or close). */
5603
+ wait(ms, on) {
5604
+ return new Promise((resolve8) => {
5605
+ const done2 = (why2) => {
5606
+ clearTimeout(t2);
5607
+ this.waiters.delete(hook);
5608
+ resolve8(why2);
5609
+ };
5610
+ const hook = (why2) => {
5611
+ if (why2 === "close" || on.includes(why2)) done2(why2);
5612
+ };
5613
+ const t2 = setTimeout(() => done2("time"), Math.max(0, ms));
5614
+ this.waiters.add(hook);
5615
+ if (this.closed) done2("close");
5616
+ });
5617
+ }
5618
+ /** JPEG of the logical (unrotated) picture: the screen turns it. Returns at once. */
5619
+ async send(frame) {
5620
+ if (this.latest && this.fresh) this.status.remote.dropped++;
5621
+ this.latest = frame;
5622
+ this.latestNum = this.latestNum + 1 >>> 0;
5623
+ this.fresh = true;
5624
+ this.notify("frame");
5625
+ }
5626
+ /** The screen's rotation changed in Kiosko's config: the screen turns at once (and on every reconnection). */
5627
+ setRotation(rotate) {
5628
+ const r = ROTATIONS.includes(rotate) ? rotate : 0;
5629
+ if (r === this.rotate) return;
5630
+ this.rotate = r;
5631
+ this.rotDirty = true;
5632
+ this.notify("frame");
5633
+ }
5634
+ /** Lights the screen's LED (`rgb` "rrggbb", "000000" off), e.g. for a full-screen alert. */
5635
+ setLed(rgb, blinkMs = 0) {
5636
+ const next = { rgb: /^[0-9a-f]{6}$/i.test(rgb) ? rgb.toLowerCase() : "000000", blink: Math.max(0, Math.round(blinkMs)) };
5637
+ if (this.led && this.led.rgb === next.rgb && this.led.blink === next.blink) return;
5638
+ this.led = next;
5639
+ this.ledDirty = true;
5640
+ this.notify("frame");
5641
+ }
5642
+ close() {
5643
+ if (this.closed) return;
5644
+ this.closed = true;
5645
+ this.mdns.off("found", this.onFound);
5646
+ this.mdns.release();
5647
+ this.wire?.close();
5648
+ this.notify("close");
5649
+ }
5650
+ /** Resolves when the loop is done (tests). */
5651
+ async closed_() {
5652
+ await this.running;
5653
+ }
5654
+ where() {
5655
+ if (this.cfg.host) return { host: this.cfg.host, port: this.cfg.port ?? PORT };
5656
+ const f = this.mdns.get(this.cfg.uid);
5657
+ return f ? { host: f.address, port: f.port || PORT } : null;
5658
+ }
5659
+ async run() {
5660
+ while (!this.closed) {
5661
+ if (this.paused) {
5662
+ for (const f of this.idle.splice(0)) f();
5663
+ await this.wait(6e4, ["resume"]);
5664
+ continue;
5665
+ }
5666
+ const at = this.where();
5667
+ if (!at) {
5668
+ this.offline(`${this.name()} is not on the network (no mDNS announcement yet)`, "remoteOffline");
5669
+ this.mdns.query();
5670
+ await this.backoff();
5671
+ continue;
5672
+ }
5673
+ let conn;
5674
+ try {
5675
+ conn = await (this.deps.open ?? openSession)(at.host, at.port, this.key, this.cfg.uid);
5676
+ } catch (err) {
5677
+ this.failed(err, at.host);
5678
+ await this.backoff(err);
5679
+ continue;
5680
+ }
5681
+ this.failures = 0;
5682
+ this.connected = true;
5683
+ try {
5684
+ await this.serve(conn, at.host);
5685
+ } catch (err) {
5686
+ if (!this.closed && !this.paused) this.failed(err, at.host);
5687
+ } finally {
5688
+ conn.wire.close();
5689
+ this.wire = null;
5690
+ this.connected = false;
5691
+ this.status.remote.online = false;
5692
+ this.status.remote.fps = 0;
5693
+ }
5694
+ if (!this.closed && !this.paused) await this.backoff();
5695
+ }
5696
+ for (const f of this.idle.splice(0)) f();
5697
+ }
5698
+ failed(err, host) {
5699
+ const e = err;
5700
+ const why2 = e?.message ?? String(err);
5701
+ if (err instanceof ScreenError && (e.code === "badKey" || e.code === "notPaired")) this.offline(`${this.name()} refuses this Kiosko's key: pair it again`, "remoteBadKey");
5702
+ else if (err instanceof ScreenError && e.code === "otherScreen") this.offline(`${host}: ${why2}`, "remoteOtherScreen", { host });
5703
+ else if (err instanceof ScreenError && e.code === "busy") this.offline(`${this.name()} is busy (updating?)`, "remoteBusy");
5704
+ else if (err instanceof ScreenError && e.code === "proto") this.offline(why2, "remoteProto", { why: why2 });
5705
+ else this.offline(`${this.name()} is offline (${why2})`, "remoteOffline");
5706
+ }
5707
+ offline(message, code, params = {}) {
5708
+ this.status.remote.online = false;
5709
+ this.status.remote.since = null;
5710
+ this.say(message, false, code, { id: this.name(), ...params });
5711
+ }
5712
+ /** A growing pause (with a little jitter); the screen announcing itself cuts it short. */
5713
+ async backoff(err) {
5714
+ this.failures++;
5715
+ const hopeless = err instanceof ScreenError && ["badKey", "notPaired", "proto"].includes(err.code);
5716
+ const base3 = hopeless ? 6e4 : Math.min(this.deps.maxRetryMs, this.deps.retryMs * 2 ** Math.min(this.failures - 1, 8));
5717
+ await this.wait(Math.round(base3 * (0.85 + Math.random() * 0.3)), ["found", "resume", "pause"]);
5718
+ }
5719
+ async serve(conn, host) {
5720
+ const { wire, info, session: session2 } = conn;
5721
+ this.wire = wire;
5722
+ const r = this.status.remote;
5723
+ 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() });
5724
+ const st = await nextSealed(wire, session2);
5725
+ if (st.type !== T.STATE) throw new Error("the screen did not say its state");
5726
+ this.applyState(st.json());
5727
+ const extra = this.deps.settings?.() ?? {};
5728
+ const bright = brightnessOf(this.cfg.brightness);
5729
+ sendSealed(wire, session2, T.SET, { rot: this.rotate, ...extra, ...bright !== null ? { bright } : {} });
5730
+ this.rotDirty = false;
5731
+ this.ledDirty = !!this.led;
5732
+ this.fresh = !!this.latest;
5733
+ r.online = true;
5734
+ this.say(`${r.id}: online at ${host} (${info.model} ${info.fw})`, true, "remoteOnline", { id: r.id, host });
5735
+ let inflight = null;
5736
+ let lastTx = Date.now();
5737
+ let lastRx = Date.now();
5738
+ let reply = null;
5739
+ while (!this.closed && !wire.closed && !this.paused) {
5740
+ if (this.rotDirty) {
5741
+ this.rotDirty = false;
5742
+ sendSealed(wire, session2, T.SET, { rot: this.rotate });
5743
+ lastTx = Date.now();
5744
+ }
5745
+ if (this.ledDirty && this.led) {
5746
+ this.ledDirty = false;
5747
+ sendSealed(wire, session2, T.LED, this.led);
5748
+ lastTx = Date.now();
5749
+ }
5750
+ if (!inflight && this.fresh && this.latest) {
5751
+ const frame = this.latest;
5752
+ if (frame.length + 64 > info.max) {
5753
+ this.fresh = false;
5754
+ 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) });
5755
+ } else {
5756
+ this.fresh = false;
5757
+ const num = this.latestNum;
5758
+ const head = Buffer.alloc(4);
5759
+ head.writeUInt32BE(num);
5760
+ sendSealed(wire, session2, T.FRAME, Buffer.concat([head, frame]));
5761
+ inflight = { num, at: Date.now() };
5762
+ lastTx = inflight.at;
5763
+ }
5764
+ }
5765
+ if (Date.now() - lastTx >= this.deps.pingMs) {
5766
+ sendSealed(wire, session2, T.PING, {});
5767
+ lastTx = Date.now();
5768
+ }
5769
+ if (Date.now() - lastRx > 3 * this.deps.pingMs + 1e3) throw Object.assign(new Error("the screen stopped answering"), { code: "ETIMEDOUT" });
5770
+ reply ??= nextSealed(wire, session2, 3 * this.deps.pingMs + 1e3);
5771
+ const waitMs = Math.max(10, this.deps.pingMs - (Date.now() - lastTx));
5772
+ const got = await Promise.race([reply.then((m2) => ({ m: m2 })), this.wait(waitMs, inflight ? ["pause"] : ["frame", "pause"]).then(() => null)]);
5773
+ if (this.paused) return;
5774
+ if (!got) continue;
5775
+ reply = null;
5776
+ lastRx = Date.now();
5777
+ const { m } = got;
5778
+ if (m.type === T.ACK) {
5779
+ const a = m.json();
5780
+ if (inflight && a.n === inflight.num) {
5781
+ const now = Date.now();
5782
+ r.rttMs = now - inflight.at;
5783
+ r.decodeMs = typeof a.dec === "number" ? a.dec : null;
5784
+ if (a.ok !== false) {
5785
+ this.status.framesSent++;
5786
+ this.status.lastSentAt = now;
5787
+ r.lastFrameAt = now;
5788
+ this.frameTimes.push(now);
5789
+ while (this.frameTimes.length && now - this.frameTimes[0] > 5e3) this.frameTimes.shift();
5790
+ r.fps = this.frameTimes.length > 1 ? Math.round((this.frameTimes.length - 1) * 1e4 / (now - this.frameTimes[0])) / 10 : 0;
5791
+ } else this.log(`${r.id}: the screen could not show frame ${a.n}`);
5792
+ inflight = null;
5793
+ }
5794
+ } else if (m.type === T.STATE) {
5795
+ const j = m.json();
5796
+ this.applyState(j);
5797
+ if (j.resend === true && this.latest) this.fresh = true;
5798
+ } else if (m.type === T.PING) {
5799
+ sendSealed(wire, session2, T.PONG, {});
5800
+ }
5801
+ }
5802
+ }
5803
+ applyState(j) {
5804
+ const r = this.status.remote;
5805
+ if (typeof j.id === "string" && j.id) r.id = j.id;
5806
+ if (typeof j.rot === "number") r.rot = j.rot;
5807
+ if (typeof j.fw === "string") r.fw = j.fw;
5808
+ if (typeof j.w === "number") r.w = j.w;
5809
+ if (typeof j.h === "number") r.h = j.h;
5810
+ if (typeof j.tempC === "number" && Number.isFinite(j.tempC)) r.tempC = j.tempC;
5811
+ if (typeof j.bright === "number" && Number.isFinite(j.bright)) r.bright = j.bright;
5812
+ }
5813
+ /**
5814
+ * Runs `fn` while this driver stands aside: its session is closed and it
5815
+ * doesn't reconnect until `fn` is done (an update, the logs, unpairing open
5816
+ * their own session; the screen takes one at a time).
5817
+ */
5818
+ async exclusive(fn) {
5819
+ const at = this.where();
5820
+ if (!at) throw new ScreenError("offline", `${this.name()} is not on the network`);
5821
+ this.paused++;
5822
+ try {
5823
+ if (this.running) {
5824
+ const idle2 = new Promise((r) => this.idle.push(r));
5825
+ this.wire?.close();
5826
+ this.notify("pause");
5827
+ await idle2;
5828
+ }
5829
+ return await fn(at.host, at.port);
5830
+ } finally {
5831
+ this.paused--;
5832
+ this.notify("resume");
5833
+ }
5834
+ }
5835
+ get isConnected() {
5836
+ return this.connected;
5837
+ }
5838
+ };
5839
+
4822
5840
  // packages/core/src/devices.ts
4823
5841
  function coded(message, code, params) {
4824
5842
  return Object.assign(new Error(message), { code, params });
@@ -4834,7 +5852,7 @@ function statusOfError(err) {
4834
5852
  }
4835
5853
  function encodeFor(device, jpegQuality) {
4836
5854
  if (device.driver === "file") return device.format ?? "jpeg";
4837
- if (device.driver === "usb") return "jpeg";
5855
+ if (device.driver === "usb" || device.driver === "remote") return "jpeg";
4838
5856
  return jpegQuality > 0 ? "jpeg" : "png";
4839
5857
  }
4840
5858
  var VirtualDevice = class {
@@ -5060,8 +6078,10 @@ async function discoverUsb() {
5060
6078
  return [];
5061
6079
  }
5062
6080
  }
5063
- function openDevice(cfg, log, rotate) {
6081
+ function openDevice(cfg, log, rotate, remote) {
5064
6082
  switch (cfg.driver) {
6083
+ case "remote":
6084
+ return new RemoteDevice(cfg, log, rotate ?? 0, remote);
5065
6085
  case "trcc":
5066
6086
  return new TrccDevice(cfg, log);
5067
6087
  case "usb":
@@ -5082,6 +6102,73 @@ async function discoverTrcc(url2 = "http://127.0.0.1:8099", tokenFile) {
5082
6102
  return [];
5083
6103
  }
5084
6104
  }
6105
+ async function discoverRemote(ms = 1500) {
6106
+ try {
6107
+ const found = await browser().browse(ms);
6108
+ 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 }));
6109
+ } catch {
6110
+ return [];
6111
+ }
6112
+ }
6113
+ function ledFor(level) {
6114
+ if (level === "critical") return ["ff0000", 400];
6115
+ if (level === "warn") return ["ffa000", 1e3];
6116
+ if (level === "info") return ["0060ff", 0];
6117
+ return ["000000", 0];
6118
+ }
6119
+
6120
+ // packages/core/src/remote/tz.ts
6121
+ var formats = /* @__PURE__ */ new Map();
6122
+ function offsetMinutes(tz, at) {
6123
+ let f = formats.get(tz);
6124
+ 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" }));
6125
+ const p = Object.fromEntries(f.formatToParts(new Date(at)).map((x) => [x.type, x.value]));
6126
+ const local = Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour), Number(p.minute));
6127
+ return Math.round((local - Math.floor(at / 6e4) * 6e4) / 6e4);
6128
+ }
6129
+ var name = (min) => {
6130
+ const s = min < 0 ? "-" : "+";
6131
+ const a = Math.abs(min);
6132
+ return `<${s}${String(Math.floor(a / 60)).padStart(2, "0")}${a % 60 ? String(a % 60).padStart(2, "0") : ""}>`;
6133
+ };
6134
+ var off = (min) => {
6135
+ const a = Math.abs(min);
6136
+ return `${min > 0 ? "-" : ""}${Math.floor(a / 60)}${a % 60 ? `:${String(a % 60).padStart(2, "0")}` : ""}`;
6137
+ };
6138
+ function rule(localMs) {
6139
+ const d = new Date(localMs);
6140
+ const day = d.getUTCDate();
6141
+ const days = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0)).getUTCDate();
6142
+ const week = day + 7 > days ? 5 : Math.ceil(day / 7);
6143
+ const mins = d.getUTCHours() * 60 + d.getUTCMinutes();
6144
+ return `M${d.getUTCMonth() + 1}.${week}.${d.getUTCDay()}${mins === 120 ? "" : `/${Math.floor(mins / 60)}${mins % 60 ? `:${String(mins % 60).padStart(2, "0")}` : ""}`}`;
6145
+ }
6146
+ function posixTz(tz = Intl.DateTimeFormat().resolvedOptions().timeZone, year = (/* @__PURE__ */ new Date()).getUTCFullYear()) {
6147
+ try {
6148
+ const start = Date.UTC(year, 0, 1);
6149
+ const changes = [];
6150
+ let prev = offsetMinutes(tz, start);
6151
+ const DAY = 864e5;
6152
+ for (let t2 = start + DAY; t2 <= Date.UTC(year + 1, 0, 1); t2 += DAY) {
6153
+ const o = offsetMinutes(tz, t2);
6154
+ if (o === prev) continue;
6155
+ let lo = t2 - DAY, hi = t2;
6156
+ while (hi - lo > 6e4) {
6157
+ const mid = Math.floor((lo + hi) / 12e4) * 6e4;
6158
+ if (offsetMinutes(tz, mid) === prev) lo = mid;
6159
+ else hi = mid;
6160
+ }
6161
+ changes.push({ at: hi, from: prev, to: o });
6162
+ prev = o;
6163
+ }
6164
+ if (changes.length !== 2) return `${name(prev)}${off(prev)}`;
6165
+ const on = changes.find((c) => c.to > c.from), offc = changes.find((c) => c.to < c.from);
6166
+ const std = on.from, dst = on.to;
6167
+ return `${name(std)}${off(std)}${name(dst)}${dst - std === 60 ? "" : off(dst)},${rule(on.at + std * 6e4)},${rule(offc.at + dst * 6e4)}`;
6168
+ } catch {
6169
+ return "UTC0";
6170
+ }
6171
+ }
5085
6172
 
5086
6173
  // packages/core/src/screen-runner.ts
5087
6174
  init_src();
@@ -5138,11 +6225,11 @@ var ALERT_ICONS = {
5138
6225
  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"]
5139
6226
  };
5140
6227
  var paths2 = /* @__PURE__ */ new Map();
5141
- function iconPaths(name) {
5142
- const d = ALERT_ICONS[name];
6228
+ function iconPaths(name2) {
6229
+ const d = ALERT_ICONS[name2];
5143
6230
  if (!d) return null;
5144
- let p = paths2.get(name);
5145
- if (!p) paths2.set(name, p = d.map((x) => new Path2D(x)));
6231
+ let p = paths2.get(name2);
6232
+ if (!p) paths2.set(name2, p = d.map((x) => new Path2D(x)));
5146
6233
  return p;
5147
6234
  }
5148
6235
  function iconFor(a) {
@@ -5443,7 +6530,7 @@ function paintCard(g, w, h, look) {
5443
6530
  const chip = Math.max(9, Math.round(k2 * 0.5));
5444
6531
  const hint = Math.max(8, Math.round(k2 * 0.34));
5445
6532
  const title = wrapLines(g, tx.running, bw, 2, { size: k2, family: bold2 });
5446
- const open = wrapLines(g, tx.open, bw, 3, { size: body2, family: sans });
6533
+ const open2 = wrapLines(g, tx.open, bw, 3, { size: body2, family: sans });
5447
6534
  const cmd2 = "kiosko editor";
5448
6535
  const cmdW = measureTracked(g, cmd2, { size: chip, family: mono }) + chip * 1.1;
5449
6536
  const orW = measureTracked(g, tx.or, { size: body2, family: sans });
@@ -5451,9 +6538,9 @@ function paintCard(g, w, h, look) {
5451
6538
  const oneLine2 = cmdW + body2 * 0.6 + orW + body2 * 0.6 + urlW <= bw;
5452
6539
  const hints = hint >= 10 ? wrapLines(g, tx.hint, bw, 2, { size: hint, family: sans }) : [];
5453
6540
  const lineH = (s) => Math.round(s * 1.3);
5454
- const height = title.length * lineH(k2) + k2 * 0.25 + open.length * lineH(body2) + body2 * 0.35 + (oneLine2 ? chip * 1.9 : chip * 1.9 * 2 + lineH(body2)) + hint * 0.6 + hints.length * lineH(hint);
6541
+ 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);
5455
6542
  const fits = urlW <= bw && cmdW <= bw && title.length === 1;
5456
- return { k: k2, body: body2, chip, hint, title, open, cmd: cmd2, cmdW, orW, urlW, oneLine: oneLine2, hints, height, fits, lineH };
6543
+ return { k: k2, body: body2, chip, hint, title, open: open2, cmd: cmd2, cmdW, orW, urlW, oneLine: oneLine2, hints, height, fits, lineH };
5457
6544
  };
5458
6545
  let k = Math.round(shape === "wide" ? h * 0.17 : shape === "tall" ? w * 0.12 : Math.min(w * 0.085, h * 0.11));
5459
6546
  let L = layout(k);
@@ -5737,7 +6824,7 @@ var ScreenRunner = class {
5737
6824
  log: this.rt.log,
5738
6825
  demo: this.rt.demoMode,
5739
6826
  cache: this.tiles,
5740
- rotate: screen.rotate
6827
+ rotate: paintTurn(screen)
5741
6828
  });
5742
6829
  canvas = result.canvas;
5743
6830
  this.animatable = result.animatable;
@@ -5748,7 +6835,8 @@ var ScreenRunner = class {
5748
6835
  this.rt.paintTime(t2.shown, type, t2.renderMs, now);
5749
6836
  }
5750
6837
  } else {
5751
- const swap = screen.rotate === 90 || screen.rotate === 270;
6838
+ const turn = paintTurn(screen);
6839
+ const swap = turn === 90 || turn === 270;
5752
6840
  canvas = CANVAS.createCanvas(swap ? screen.height : screen.width, swap ? screen.width : screen.height);
5753
6841
  this.animatable = [];
5754
6842
  this.nextAt = now + 6e4;
@@ -5764,7 +6852,7 @@ var ScreenRunner = class {
5764
6852
  }
5765
6853
  const kind = encodeFor(screen.device, screen.jpegQuality);
5766
6854
  const out = await this.fit(canvas, kind, screen.jpegQuality, screen, performance.now() - t0);
5767
- this.lastInfo = { screenId: screen.id, pageId: page?.id ?? null, at: now, image: lazyJpeg(canvas, screen.rotate), tiles: result?.tiles ?? [], interlude: null, sleeping };
6855
+ this.lastInfo = { screenId: screen.id, pageId: page?.id ?? null, at: now, image: lazyJpeg(canvas, paintTurn(screen)), tiles: result?.tiles ?? [], interlude: null, sleeping };
5768
6856
  this.rt.frame(this.lastInfo);
5769
6857
  if (this.last?.equals(out)) return;
5770
6858
  this.last = out;
@@ -5793,7 +6881,7 @@ var ScreenRunner = class {
5793
6881
  const canvas = CANVAS.createCanvas(screen.width, screen.height);
5794
6882
  paintAlert(canvas.getContext("2d"), screen.width, screen.height, shown, { intensity, fonts: this.rt.theme().fonts, minPx, sinceText, shift });
5795
6883
  const kind = encodeFor(screen.device, screen.jpegQuality || 85);
5796
- const turned = rotateCanvas(canvas, screen.rotate);
6884
+ const turned = rotateCanvas(canvas, paintTurn(screen));
5797
6885
  const out = await this.fit(turned, kind, screen.jpegQuality || 85, screen, performance.now() - t0);
5798
6886
  this.lastInfo = { screenId: screen.id, pageId: this.page?.id ?? null, at: now, image: lazyJpeg(canvas), tiles: [], interlude: null, alert: a.id, sleeping: false };
5799
6887
  this.rt.frame(this.lastInfo);
@@ -5859,7 +6947,7 @@ var ScreenRunner = class {
5859
6947
  g.save();
5860
6948
  paintBoot(g, screen.width, screen.height, ms, look);
5861
6949
  g.restore();
5862
- const out = await this.fit(rotateCanvas(canvas, screen.rotate), kind, screen.jpegQuality || 85, screen, performance.now() - t0);
6950
+ const out = await this.fit(rotateCanvas(canvas, paintTurn(screen)), kind, screen.jpegQuality || 85, screen, performance.now() - t0);
5863
6951
  await this.send(out);
5864
6952
  if (i % 4 === 0) {
5865
6953
  const snap = CANVAS.createCanvas(canvas.width, canvas.height);
@@ -5884,7 +6972,7 @@ var ScreenRunner = class {
5884
6972
  const canvas = CANVAS.createCanvas(screen.width, screen.height);
5885
6973
  paintCard(canvas.getContext("2d"), screen.width, screen.height, look);
5886
6974
  const kind = encodeFor(screen.device, screen.jpegQuality || 85);
5887
- const out = await this.fit(rotateCanvas(canvas, screen.rotate), kind, screen.jpegQuality || 85, screen, performance.now() - t0);
6975
+ const out = await this.fit(rotateCanvas(canvas, paintTurn(screen)), kind, screen.jpegQuality || 85, screen, performance.now() - t0);
5888
6976
  this.lastInfo = { screenId: screen.id, pageId: this.page?.id ?? null, at: now, image: lazyJpeg(canvas), tiles: [], interlude: "kiosko/welcome", sleeping: false };
5889
6977
  this.rt.frame(this.lastInfo);
5890
6978
  this.last = out;
@@ -5960,7 +7048,7 @@ var ScreenRunner = class {
5960
7048
  } finally {
5961
7049
  g.restore();
5962
7050
  }
5963
- const turned = rotateCanvas(canvas, this.screen.rotate);
7051
+ const turned = rotateCanvas(canvas, paintTurn(this.screen));
5964
7052
  const out = await this.fit(turned, kind, this.screen.jpegQuality || 85, this.screen, performance.now() - t0);
5965
7053
  await this.send(out);
5966
7054
  if (i % 3 === 0) {
@@ -6058,7 +7146,7 @@ var ScreenRunner = class {
6058
7146
  demo: this.rt.demoMode,
6059
7147
  cache: this.tiles,
6060
7148
  animate,
6061
- rotate: screen.rotate
7149
+ rotate: paintTurn(screen)
6062
7150
  });
6063
7151
  sent.push({ out: this.fit(result.canvas, kind, screen.jpegQuality || 85, screen, performance.now() - t02), snap: s % 3 === 1 ? result.canvas : null });
6064
7152
  await new Promise((r) => setImmediate(r));
@@ -6075,7 +7163,7 @@ var ScreenRunner = class {
6075
7163
  await this.send(outs[k]);
6076
7164
  const snap = sent[k].snap;
6077
7165
  if (snap) {
6078
- 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 };
7166
+ 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 };
6079
7167
  this.rt.frame(this.lastInfo);
6080
7168
  }
6081
7169
  if (hold && k === holdAt) {
@@ -6119,9 +7207,9 @@ var ScreenRunner = class {
6119
7207
  this.pinned = pageId;
6120
7208
  this.dirty = true;
6121
7209
  }
6122
- setOff(off) {
6123
- this.off = off;
6124
- if (off) this.stopInterlude();
7210
+ setOff(off2) {
7211
+ this.off = off2;
7212
+ if (off2) this.stopInterlude();
6125
7213
  this.dirty = true;
6126
7214
  }
6127
7215
  /** A button from the Play page, for the interlude being played; false when none is. */
@@ -6176,8 +7264,8 @@ var Unclonable = class extends Error {
6176
7264
  };
6177
7265
  function what(v) {
6178
7266
  if (typeof v === "function") return "a function";
6179
- const name = Object.getPrototypeOf(v)?.constructor?.name;
6180
- return name ? `a ${name} (an object of a class)` : "an object of a class";
7267
+ const name2 = Object.getPrototypeOf(v)?.constructor?.name;
7268
+ return name2 ? `a ${name2} (an object of a class)` : "an object of a class";
6181
7269
  }
6182
7270
  var CLONED_AS_IS = [Date, RegExp, ArrayBuffer, Error, DataView];
6183
7271
  function isCanvas(v) {
@@ -6474,10 +7562,10 @@ var ThreadRunner = class {
6474
7562
  this.pinned = pageId;
6475
7563
  this.post({ t: "pin", page: pageId });
6476
7564
  }
6477
- setOff(off) {
6478
- this.off = off;
6479
- if (off) this.state = { ...this.state, interlude: null };
6480
- this.post({ t: "off", off });
7565
+ setOff(off2) {
7566
+ this.off = off2;
7567
+ if (off2) this.state = { ...this.state, interlude: null };
7568
+ this.post({ t: "off", off: off2 });
6481
7569
  }
6482
7570
  async playNow(slotId, play = false) {
6483
7571
  if (this.off || this.alert) return;
@@ -6537,7 +7625,7 @@ var TEST_ALERT_TEXT = {
6537
7625
  "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",
6538
7626
  "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"
6539
7627
  };
6540
- var Runtime = class extends EventEmitter {
7628
+ var Runtime = class extends EventEmitter2 {
6541
7629
  config;
6542
7630
  hub;
6543
7631
  fetches;
@@ -6626,7 +7714,7 @@ var Runtime = class extends EventEmitter {
6626
7714
  this.refreshWanted();
6627
7715
  }
6628
7716
  openDevice(screen, log) {
6629
- return openDevice(screen.device, log, screen.rotate);
7717
+ return openDevice(screen.device, log, screen.rotate, { settings: () => ({ lang: resolveLocale(this.config).slice(0, 5), tz: posixTz() }) });
6630
7718
  }
6631
7719
  onData(change) {
6632
7720
  this.alertsDirty = true;
@@ -6700,6 +7788,7 @@ var Runtime = class extends EventEmitter {
6700
7788
  this.runners.get(s.id)?.reconfigure(s);
6701
7789
  }
6702
7790
  this.placeRunners();
7791
+ for (const s of config2.screens) this.runners.get(s.id)?.device.setRotation?.(s.rotate);
6703
7792
  this.refreshWanted();
6704
7793
  this.emit("config", config2);
6705
7794
  }
@@ -6736,6 +7825,10 @@ var Runtime = class extends EventEmitter {
6736
7825
  }
6737
7826
  return r;
6738
7827
  }
7828
+ /** The device a screen sends to now (its remote screen, for pairing, updates, logs). */
7829
+ deviceOf(screenId) {
7830
+ return this.runners.get(screenId)?.device;
7831
+ }
6739
7832
  threadFailed(screenId, reason) {
6740
7833
  const s = this.config.screens.find((x) => x.id === screenId);
6741
7834
  const r = this.runners.get(screenId);
@@ -6784,11 +7877,11 @@ var Runtime = class extends EventEmitter {
6784
7877
  this.runners.get(screenId)?.stopInterlude();
6785
7878
  }
6786
7879
  /** Switches a screen's picture off (black) or back on, until the next restart. */
6787
- setOff(screenId, off) {
7880
+ setOff(screenId, off2) {
6788
7881
  const r = this.runners.get(screenId);
6789
- if (!r || r.off === off) return;
6790
- r.setOff(off);
6791
- this.emit("screen", { screenId, off });
7882
+ if (!r || r.off === off2) return;
7883
+ r.setOff(off2);
7884
+ this.emit("screen", { screenId, off: off2 });
6792
7885
  }
6793
7886
  refreshWidget(instanceId) {
6794
7887
  this.fetches.refresh(instanceId);
@@ -6838,7 +7931,11 @@ var Runtime = class extends EventEmitter {
6838
7931
  refreshAlerts(now = Date.now()) {
6839
7932
  this.alerts.prune(now);
6840
7933
  const list2 = this.alerts.list(now);
6841
- for (const r of this.runners.values()) r.setAlert(r.screen.enabled ? this.alerts.forScreen(r.screen, now, r.off) : null, now);
7934
+ for (const r of this.runners.values()) {
7935
+ const shown = r.screen.enabled ? this.alerts.forScreen(r.screen, now, r.off) : null;
7936
+ r.setAlert(shown, now);
7937
+ r.device.setLed?.(...ledFor(shown?.top.level ?? null));
7938
+ }
6842
7939
  const sig = JSON.stringify(list2);
6843
7940
  if (sig === this.alertsSig) return;
6844
7941
  this.alertsSig = sig;
@@ -6849,9 +7946,9 @@ var Runtime = class extends EventEmitter {
6849
7946
  return this.alerts.list(now);
6850
7947
  }
6851
7948
  /** An alert from outside (`POST /api/alerts`); throws `AlertError` if it is not one. */
6852
- postAlert(raw) {
7949
+ postAlert(raw2) {
6853
7950
  const now = Date.now();
6854
- const a = this.alerts.post(raw, now, resolveLocale(this.config), this.config.screens.map((s) => s.id));
7951
+ const a = this.alerts.post(raw2, now, resolveLocale(this.config), this.config.screens.map((s) => s.id));
6855
7952
  this.log("alerts", `${a.level}: ${a.title} (${a.id})`);
6856
7953
  this.refreshAlerts(now);
6857
7954
  return a;
@@ -7166,14 +8263,14 @@ function installSdkResolver() {
7166
8263
  if (installed) return;
7167
8264
  installed = true;
7168
8265
  const urls = /* @__PURE__ */ new Map();
7169
- for (const name of SHARED) {
7170
- const local = BUNDLED[name] ? join5(import.meta.dirname, BUNDLED[name]) : null;
8266
+ for (const name2 of SHARED) {
8267
+ const local = BUNDLED[name2] ? join5(import.meta.dirname, BUNDLED[name2]) : null;
7171
8268
  if (local && existsSync5(local)) {
7172
- urls.set(name, pathToFileURL(local).href);
8269
+ urls.set(name2, pathToFileURL(local).href);
7173
8270
  continue;
7174
8271
  }
7175
8272
  try {
7176
- urls.set(name, import.meta.resolve(name));
8273
+ urls.set(name2, import.meta.resolve(name2));
7177
8274
  } catch {
7178
8275
  }
7179
8276
  }
@@ -7339,16 +8436,16 @@ var Registry = class {
7339
8436
  }
7340
8437
  }
7341
8438
  const candidates = [];
7342
- for (const name of readdirSync3(dir)) {
7343
- if (name === "node_modules" || name.startsWith(".")) continue;
7344
- candidates.push(join6(dir, name));
8439
+ for (const name2 of readdirSync3(dir)) {
8440
+ if (name2 === "node_modules" || name2.startsWith(".")) continue;
8441
+ candidates.push(join6(dir, name2));
7345
8442
  }
7346
8443
  const nm = join6(dir, "node_modules");
7347
8444
  if (existsSync6(nm)) {
7348
- for (const name of readdirSync3(nm)) {
7349
- if (name.startsWith("@")) {
7350
- for (const sub of readdirSync3(join6(nm, name))) if (sub.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name, sub));
7351
- } else if (name.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name));
8445
+ for (const name2 of readdirSync3(nm)) {
8446
+ if (name2.startsWith("@")) {
8447
+ for (const sub of readdirSync3(join6(nm, name2))) if (sub.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name2, sub));
8448
+ } else if (name2.startsWith("kiosko-plugin-")) candidates.push(join6(nm, name2));
7352
8449
  }
7353
8450
  }
7354
8451
  for (const folder of candidates) await this.loadFolder(folder);
@@ -7380,15 +8477,15 @@ var Registry = class {
7380
8477
  }
7381
8478
  async loadEntry(entry, origin, version) {
7382
8479
  const url2 = pathToFileURL2(entry).href + (version ? `?v=${version}` : "");
7383
- const mod = await import(url2);
7384
- if (!mod.default) {
8480
+ const mod2 = await import(url2);
8481
+ if (!mod2.default) {
7385
8482
  this.problems.push({ origin, message: "the module has no default export (use `export default definePlugin({...})`)" });
7386
8483
  return void 0;
7387
8484
  }
7388
8485
  const before = this.plugins.size;
7389
- this.add(mod.default, origin, url2);
7390
- if (this.plugins.size > before) this.entries.set(mod.default.id, { entry, origin });
7391
- return mod.default;
8486
+ this.add(mod2.default, origin, url2);
8487
+ if (this.plugins.size > before) this.entries.set(mod2.default.id, { entry, origin });
8488
+ return mod2.default;
7392
8489
  }
7393
8490
  /**
7394
8491
  * The values a source offers for an option (see `SourceDefinition.choices`),
@@ -7566,34 +8663,34 @@ function* fieldsOf(f, prefix = "") {
7566
8663
  }
7567
8664
  }
7568
8665
  var last = (path) => path.split(/[.[\]]+/).filter(Boolean).pop() ?? path;
7569
- function lintOptions(where, f, kind) {
8666
+ function lintOptions(where2, f, kind) {
7570
8667
  const out = [];
7571
- const warn = (path, message) => out.push({ level: "warn", where: `${where} options.${path}`, message });
7572
- const err = (path, message) => out.push({ level: "error", where: `${where} options.${path}`, message });
8668
+ const warn = (path, message) => out.push({ level: "warn", where: `${where2} options.${path}`, message });
8669
+ const err = (path, message) => out.push({ level: "error", where: `${where2} options.${path}`, message });
7573
8670
  const names = new Set([...fieldsOf(f)].map(([p]) => p));
7574
8671
  for (const [path, x] of fieldsOf(f)) {
7575
- const name = last(path);
7576
- if (x.kind === "number" && x.unit === "ms" && !/Ms$/.test(name)) warn(path, "a duration: name it \u2026Ms (rotateMs, maxAgeMs)");
7577
- if (x.kind === "number" && /Ms$/.test(name) && x.unit !== "ms") warn(path, "named \u2026Ms but not a duration: use t.duration()");
7578
- 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");
7579
- if (/(Crit|Critical)$/.test(name)) warn(path, "thresholds are \u2026Warn (amber) and \u2026Alert (red), never \u2026Crit");
7580
- if (/Warn$/.test(name) && !names.has(path.replace(/Warn$/, "Alert"))) warn(path, `thresholds come in pairs: add ${name.replace(/Warn$/, "Alert")}`);
7581
- if (/Alert$/.test(name) && !names.has(path.replace(/Alert$/, "Warn"))) warn(path, `thresholds come in pairs: add ${name.replace(/Alert$/, "Warn")}`);
8672
+ const name2 = last(path);
8673
+ if (x.kind === "number" && x.unit === "ms" && !/Ms$/.test(name2)) warn(path, "a duration: name it \u2026Ms (rotateMs, maxAgeMs)");
8674
+ if (x.kind === "number" && /Ms$/.test(name2) && x.unit !== "ms") warn(path, "named \u2026Ms but not a duration: use t.duration()");
8675
+ 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");
8676
+ if (/(Crit|Critical)$/.test(name2)) warn(path, "thresholds are \u2026Warn (amber) and \u2026Alert (red), never \u2026Crit");
8677
+ if (/Warn$/.test(name2) && !names.has(path.replace(/Warn$/, "Alert"))) warn(path, `thresholds come in pairs: add ${name2.replace(/Warn$/, "Alert")}`);
8678
+ if (/Alert$/.test(name2) && !names.has(path.replace(/Alert$/, "Warn"))) warn(path, `thresholds come in pairs: add ${name2.replace(/Alert$/, "Warn")}`);
7582
8679
  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: "%" })');
7583
8680
  if (x.kind === "number" && x.unit === "\xB0C" && !x.integer) warn(path, "temperatures are integer \xB0C");
7584
- if (x.kind === "boolean" && /Only$/.test(name)) warn(path, "no \u2026Only suffix: only<Condition> (onlyLatest)");
7585
- 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)}`);
7586
- if (name === "takeOver") err(path, "takeOver is the instance's switch, not an option: declare `takeOver` on the definition");
7587
- if (name === "hideWhenEmpty") err(path, "hideWhenEmpty is the instance's switch: declare `empty(ctx)` (and `hideWhenEmpty` on the definition)");
7588
- if (kind === "source" && (name === "intervalMs" || name === "timeoutMs") && !path.includes(".")) err(path, "refresh and timeout are not options: declare intervalMs / timeoutMs on the source");
7589
- 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");
7590
- if (name === "max" || name === "count") warn(path, "a cap is max<Things> (maxProcesses); a list length is `rows` through listOptions()");
7591
- if ((name === "latitude" || name === "longitude") && !(x.kind === "number" && x.advanced)) warn(path, "use ctx.location, with locationOptions() as an advanced override");
8681
+ if (x.kind === "boolean" && /Only$/.test(name2)) warn(path, "no \u2026Only suffix: only<Condition> (onlyLatest)");
8682
+ 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)}`);
8683
+ if (name2 === "takeOver") err(path, "takeOver is the instance's switch, not an option: declare `takeOver` on the definition");
8684
+ if (name2 === "hideWhenEmpty") err(path, "hideWhenEmpty is the instance's switch: declare `empty(ctx)` (and `hideWhenEmpty` on the definition)");
8685
+ if (kind === "source" && (name2 === "intervalMs" || name2 === "timeoutMs") && !path.includes(".")) err(path, "refresh and timeout are not options: declare intervalMs / timeoutMs on the source");
8686
+ 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");
8687
+ if (name2 === "max" || name2 === "count") warn(path, "a cap is max<Things> (maxProcesses); a list length is `rows` through listOptions()");
8688
+ if ((name2 === "latitude" || name2 === "longitude") && !(x.kind === "number" && x.advanced)) warn(path, "use ctx.location, with locationOptions() as an advanced override");
7592
8689
  if (x.kind === "string") {
7593
- 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);
8690
+ 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);
7594
8691
  if (looks && !x.risk && !x.secret) warn(path, "its value contacts a host, runs a program or reads a path: mark it with `risk`");
7595
8692
  }
7596
- 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");
8693
+ 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");
7597
8694
  }
7598
8695
  return out;
7599
8696
  }
@@ -7613,53 +8710,53 @@ function knownLanguage(tag) {
7613
8710
  var bare = (x) => ({ ...x, options: void 0 });
7614
8711
  function lintPlugin(def) {
7615
8712
  const out = [];
7616
- const add = (level, where, message) => out.push({ level, where, message });
7617
- if (!ID2.test(def.id ?? "")) add("error", "plugin", `id ${JSON.stringify(def.id)}: lowercase letters, digits and dashes`);
7618
- if (!/^\d+\.\d+\.\d+/.test(def.version ?? "")) add("error", "plugin", `version ${JSON.stringify(def.version)} is not semver`);
7619
- 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)');
8713
+ const add2 = (level, where2, message) => out.push({ level, where: where2, message });
8714
+ if (!ID2.test(def.id ?? "")) add2("error", "plugin", `id ${JSON.stringify(def.id)}: lowercase letters, digits and dashes`);
8715
+ if (!/^\d+\.\d+\.\d+/.test(def.version ?? "")) add2("error", "plugin", `version ${JSON.stringify(def.version)} is not semver`);
8716
+ 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)');
7620
8717
  const reaches = (def.sources ?? []).length > 0 || (def.widgets ?? []).some((w) => w.fetch);
7621
- if (reaches && !def.permissions) add("warn", "plugin", "it reads data: declare `permissions` (hosts, programs, files, devices) so people know before installing");
7622
- if (!def.description) add("warn", "plugin", "a description, for the Plugins page and the store");
8718
+ if (reaches && !def.permissions) add2("warn", "plugin", "it reads data: declare `permissions` (hosts, programs, files, devices) so people know before installing");
8719
+ if (!def.description) add2("warn", "plugin", "a description, for the Plugins page and the store");
7623
8720
  if (def.license) {
7624
8721
  try {
7625
8722
  const lic = parseLicense(def.license);
7626
- for (const f of lic.fix) add("warn", "plugin", `license: write "${f.from}" as "${f.to}" (SPDX identifiers are case-sensitive)`);
7627
- 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"`);
8723
+ for (const f of lic.fix) add2("warn", "plugin", `license: write "${f.from}" as "${f.to}" (SPDX identifiers are case-sensitive)`);
8724
+ 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"`);
7628
8725
  } catch (err) {
7629
- add("error", "plugin", `license ${JSON.stringify(def.license)}: ${err.message}`);
8726
+ add2("error", "plugin", `license ${JSON.stringify(def.license)}: ${err.message}`);
7630
8727
  }
7631
8728
  }
7632
8729
  for (const k of ["only", "without"]) {
7633
- 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`);
8730
+ 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`);
7634
8731
  }
7635
- if (def.markets?.only?.length && def.markets.without?.length) add("warn", "plugin", "markets: `only` and `without` together; `only` alone says it");
7636
- 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)`);
7637
- if (def.category && (def.widgets ?? []).length) add("warn", "plugin", "`category` is for plugins without widgets: the store takes the widgets' own");
7638
- 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`);
7639
- 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`);
8732
+ if (def.markets?.only?.length && def.markets.without?.length) add2("warn", "plugin", "markets: `only` and `without` together; `only` alone says it");
8733
+ 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)`);
8734
+ if (def.category && (def.widgets ?? []).length) add2("warn", "plugin", "`category` is for plugins without widgets: the store takes the widgets' own");
8735
+ 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`);
8736
+ 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`);
7640
8737
  const used = languagesOf(def);
7641
8738
  const declared = def.languages;
7642
- 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)`);
8739
+ 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)`);
7643
8740
  else {
7644
8741
  for (const tag of declared) {
7645
8742
  let canon;
7646
8743
  try {
7647
8744
  canon = Intl.getCanonicalLocales(tag)[0];
7648
8745
  } catch {
7649
- add("error", "plugin", `languages: "${tag}" is not a language tag (en, es, zh-Hant\u2026)`);
8746
+ add2("error", "plugin", `languages: "${tag}" is not a language tag (en, es, zh-Hant\u2026)`);
7650
8747
  continue;
7651
8748
  }
7652
- if (canon !== tag) add("warn", "plugin", `languages: write "${tag}" as "${canon}"`);
7653
- else if (!knownLanguage(tag)) add("warn", "plugin", `languages: "${tag}" is not a language Intl knows`);
8749
+ if (canon !== tag) add2("warn", "plugin", `languages: write "${tag}" as "${canon}"`);
8750
+ else if (!knownLanguage(tag)) add2("warn", "plugin", `languages: "${tag}" is not a language Intl knows`);
7654
8751
  }
7655
- 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");
7656
- if (new Set(declared).size !== declared.length) add("warn", "plugin", "languages: a language is listed twice");
8752
+ 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");
8753
+ if (new Set(declared).size !== declared.length) add2("warn", "plugin", "languages: a language is listed twice");
7657
8754
  const own = languagesOf({ ...def, widgets: def.widgets?.map(bare), sources: def.sources?.map(bare), interludes: def.interludes?.map(bare) });
7658
8755
  const unlisted = own.filter((l) => !declared.includes(l));
7659
- if (unlisted.length) add("warn", "plugin", `its texts come in ${unlisted.join(", ")} too, which \`languages\` doesn't list`);
8756
+ if (unlisted.length) add2("warn", "plugin", `its texts come in ${unlisted.join(", ")} too, which \`languages\` doesn't list`);
7660
8757
  }
7661
8758
  const langs = declared?.length ? declared : used;
7662
- 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)");
8759
+ 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)");
7663
8760
  const valid = langs.filter((l) => {
7664
8761
  try {
7665
8762
  return Intl.getCanonicalLocales(l)[0] === l && knownLanguage(l);
@@ -7667,60 +8764,60 @@ function lintPlugin(def) {
7667
8764
  return false;
7668
8765
  }
7669
8766
  });
7670
- const texts = (where, ...ts) => {
8767
+ const texts = (where2, ...ts) => {
7671
8768
  for (const tx of ts) {
7672
8769
  const miss = missingLanguages(tx, valid);
7673
- if (miss.length) add("warn", where, `"${typeof tx === "string" ? tx : tx?.en}" has no ${miss.join(", ")} (the plugin speaks ${langs.join(", ")})`);
8770
+ if (miss.length) add2("warn", where2, `"${typeof tx === "string" ? tx : tx?.en}" has no ${miss.join(", ")} (the plugin speaks ${langs.join(", ")})`);
7674
8771
  }
7675
8772
  };
7676
8773
  texts("plugin", def.name, def.description);
7677
8774
  const ids2 = /* @__PURE__ */ new Set();
7678
8775
  const part = (kind, x) => {
7679
- const where = `${def.id}/${x.id}`;
7680
- if (!PART_ID.test(x.id ?? "")) add("error", where, `${kind} id ${JSON.stringify(x.id)}`);
7681
- if (ids2.has(`${kind}:${x.id}`)) add("error", where, `two ${kind}s with the id "${x.id}"`);
8776
+ const where2 = `${def.id}/${x.id}`;
8777
+ if (!PART_ID.test(x.id ?? "")) add2("error", where2, `${kind} id ${JSON.stringify(x.id)}`);
8778
+ if (ids2.has(`${kind}:${x.id}`)) add2("error", where2, `two ${kind}s with the id "${x.id}"`);
7682
8779
  ids2.add(`${kind}:${x.id}`);
7683
- texts(where, x.name, x.description);
7684
- if (!x.description) add("warn", where, "a description, for the library and the store");
7685
- return where;
8780
+ texts(where2, x.name, x.description);
8781
+ if (!x.description) add2("warn", where2, "a description, for the library and the store");
8782
+ return where2;
7686
8783
  };
7687
- const optionTexts = (where, f) => {
8784
+ const optionTexts = (where2, f) => {
7688
8785
  for (const [path, x] of fieldsOf(f)) {
7689
8786
  const o = x;
7690
- texts(`${where} options.${path}`, ...[o.label, o.help, ...Object.values(o.labels ?? {})].filter((x2) => typeof x2 !== "string"));
8787
+ texts(`${where2} options.${path}`, ...[o.label, o.help, ...Object.values(o.labels ?? {})].filter((x2) => typeof x2 !== "string"));
7691
8788
  }
7692
8789
  };
7693
8790
  for (const w of def.widgets ?? []) optionTexts(`${def.id}/${w.id}`, w.options);
7694
8791
  for (const s of def.sources ?? []) optionTexts(`${def.id}/${s.id}`, s.options);
7695
8792
  for (const i of def.interludes ?? []) optionTexts(`${def.id}/${i.id}`, i.options);
7696
8793
  for (const w of def.widgets ?? []) {
7697
- const where = part("widget", w);
7698
- out.push(...lintOptions(where, w.options, "widget"));
7699
- if (!w.demo) add("warn", where, "no `demo`: the gallery, the editor and the store show it empty");
7700
- if (!w.icon) add("warn", where, "an icon (a Lucide name)");
8794
+ const where2 = part("widget", w);
8795
+ out.push(...lintOptions(where2, w.options, "widget"));
8796
+ if (!w.demo) add2("warn", where2, "no `demo`: the gallery, the editor and the store show it empty");
8797
+ if (!w.icon) add2("warn", where2, "an icon (a Lucide name)");
7701
8798
  const min = w.size?.min, pref = w.size?.preferred;
7702
- 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}`);
7703
- if (!pref) add("warn", where, "a size.preferred, what it is dropped at");
8799
+ 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}`);
8800
+ if (!pref) add2("warn", where2, "a size.preferred, what it is dropped at");
7704
8801
  for (const s of w.sources ?? []) {
7705
8802
  const [pid] = s.split("/");
7706
- 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)`);
8803
+ 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)`);
7707
8804
  }
7708
8805
  }
7709
8806
  for (const s of def.sources ?? []) {
7710
- const where = part("source", s);
7711
- out.push(...lintOptions(where, s.options, "source"));
7712
- if (!s.read && !s.watch) add("error", where, "a source needs `read` or `watch`");
7713
- if (!s.demo) add("warn", where, "no `demo`: widgets using it show nothing in the gallery");
7714
- if (s.background && !s.alerts) add("warn", where, "`background` without `alerts`: it would run for nothing, so Kiosko offers no switch");
8807
+ const where2 = part("source", s);
8808
+ out.push(...lintOptions(where2, s.options, "source"));
8809
+ if (!s.read && !s.watch) add2("error", where2, "a source needs `read` or `watch`");
8810
+ if (!s.demo) add2("warn", where2, "no `demo`: widgets using it show nothing in the gallery");
8811
+ if (s.background && !s.alerts) add2("warn", where2, "`background` without `alerts`: it would run for nothing, so Kiosko offers no switch");
7715
8812
  }
7716
8813
  for (const i of def.interludes ?? []) {
7717
- const where = part("interlude", i);
7718
- out.push(...lintOptions(where, i.options, "interlude"));
8814
+ const where2 = part("interlude", i);
8815
+ out.push(...lintOptions(where2, i.options, "interlude"));
7719
8816
  }
7720
8817
  for (const tp of def.templates ?? []) {
7721
- const where = `${def.id}/${tp.id} template`;
8818
+ const where2 = `${def.id}/${tp.id} template`;
7722
8819
  for (const tile of [...tp.wide, ...tp.square ?? [], ...tp.tall ?? []]) {
7723
- 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");
8820
+ 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");
7724
8821
  }
7725
8822
  }
7726
8823
  return out;
@@ -7736,7 +8833,7 @@ var GITHUB_REPO = "kiosko-lcd/kiosko";
7736
8833
  var GITHUB_API = "https://api.github.com";
7737
8834
  var releasePage = (version) => `https://github.com/${GITHUB_REPO}/releases/tag/v${version}`;
7738
8835
  var windowsInstallerName = (version) => `Kiosko-Setup-${version}-x64.exe`;
7739
- var releaseAsset = (version, name) => `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${name}`;
8836
+ var releaseAsset = (version, name2) => `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${name2}`;
7740
8837
  var NOTES_MAX_CHARS = 3e3;
7741
8838
  var NOTES_MAX_RELEASES = 10;
7742
8839
  var stable = (v) => {
@@ -7780,12 +8877,12 @@ async function kioskoReleaseNotes(current, latest, o) {
7780
8877
  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 } : {} };
7781
8878
  });
7782
8879
  const newest = byVersion.get(latest);
7783
- const name = windowsInstallerName(latest);
8880
+ const name2 = windowsInstallerName(latest);
7784
8881
  const asset = (n) => newest?.assets?.find((a) => a.name === n)?.browser_download_url;
7785
- const exe = asset(name);
7786
- const sha = asset(`${name}.sha256`);
8882
+ const exe = asset(name2);
8883
+ const sha = asset(`${name2}.sha256`);
7787
8884
  const ours = (u) => !!u && u.startsWith(`https://github.com/${GITHUB_REPO}/releases/download/`);
7788
- return { from: "github", releases: releases2, ...ours(exe) && ours(sha) ? { windows: { name, exe, sha256: sha } } : {} };
8885
+ return { from: "github", releases: releases2, ...ours(exe) && ours(sha) ? { windows: { name: name2, exe, sha256: sha } } : {} };
7789
8886
  }
7790
8887
 
7791
8888
  // packages/core/src/plugin-updates.ts
@@ -7867,6 +8964,71 @@ function addedPermissions(before, after) {
7867
8964
  // packages/core/src/store/tar.ts
7868
8965
  var MAX_TARBALL_BYTES = 20 * 1024 * 1024;
7869
8966
 
8967
+ // packages/core/src/remote/ops.ts
8968
+ import { createHash as createHash2 } from "node:crypto";
8969
+ var CHUNK = 16 * 1024;
8970
+ async function session(host, port, key, uid) {
8971
+ const s = await openSession(host, port, key, uid);
8972
+ const st = await nextSealed(s.wire, s.session);
8973
+ if (st.type !== T.STATE) throw new Error("the screen did not say its state");
8974
+ return s;
8975
+ }
8976
+ async function otaUpdate(host, port, key, uid, image2, progress) {
8977
+ if (image2[0] !== 233) throw new ScreenError("notFirmware", "not an ESP32 firmware image (.bin)");
8978
+ const { wire, session: s } = await session(host, port, key, uid);
8979
+ try {
8980
+ sendSealed(wire, s, T.OTA_BEGIN, { size: image2.length, sha256: createHash2("sha256").update(image2).digest("hex") });
8981
+ const next = async () => {
8982
+ for (; ; ) {
8983
+ const m = await nextSealed(wire, s, 3e4);
8984
+ if (m.type === T.OTA_ACK) return m.json().off;
8985
+ if (m.type === T.OTA_DONE) {
8986
+ const j = m.json();
8987
+ if (!j.ok) throw new ScreenError("otaFailed", `the screen refused the update: ${j.err ?? "error"}`);
8988
+ return -1;
8989
+ }
8990
+ if (m.type === T.PING) sendSealed(wire, s, T.PONG, {});
8991
+ }
8992
+ };
8993
+ let off2 = await next();
8994
+ while (off2 >= 0 && off2 < image2.length) {
8995
+ sendSealed(wire, s, T.OTA_DATA, image2.subarray(off2, off2 + CHUNK));
8996
+ const got = await next();
8997
+ if (got !== Math.min(image2.length, off2 + CHUNK)) throw new ScreenError("otaFailed", `the screen lost the update at ${off2}`);
8998
+ off2 = got;
8999
+ progress?.(off2, image2.length);
9000
+ }
9001
+ sendSealed(wire, s, T.OTA_END, {});
9002
+ if (await next() !== -1) throw new ScreenError("otaFailed", "the screen did not confirm the update");
9003
+ } finally {
9004
+ wire.close();
9005
+ }
9006
+ }
9007
+ async function screenLogs(host, port, key, uid) {
9008
+ const { wire, session: s } = await session(host, port, key, uid);
9009
+ try {
9010
+ sendSealed(wire, s, T.LOGS, {});
9011
+ for (; ; ) {
9012
+ const m = await nextSealed(wire, s);
9013
+ if (m.type === T.LOGS) return String(m.json().text ?? "");
9014
+ }
9015
+ } finally {
9016
+ wire.close();
9017
+ }
9018
+ }
9019
+ async function unpairScreen(host, port, key, uid) {
9020
+ const { wire, session: s } = await session(host, port, key, uid);
9021
+ try {
9022
+ sendSealed(wire, s, T.UNPAIR, {});
9023
+ for (; ; ) {
9024
+ const m = await nextSealed(wire, s).catch(() => null);
9025
+ if (!m || m.type === T.UNPAIR) return;
9026
+ }
9027
+ } finally {
9028
+ wire.close();
9029
+ }
9030
+ }
9031
+
7870
9032
  // plugins/core/src/index.ts
7871
9033
  import { readdir, readFile, stat } from "node:fs/promises";
7872
9034
  import { join as join8 } from "node:path";
@@ -8231,7 +9393,7 @@ var image = defineWidget({
8231
9393
  var src_default = definePlugin({
8232
9394
  id: "core",
8233
9395
  name: { en: "Essentials", es: "B\xE1sicos", de: "Grundlagen", "zh-Hant": "\u57FA\u672C\u5DE5\u5177", "zh-Hans": "\u57FA\u7840\u7EC4\u4EF6" },
8234
- version: "0.2.9",
9396
+ version: "0.2.11",
8235
9397
  languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
8236
9398
  sdk: "^0.2.0",
8237
9399
  // The picture widget reads the image (or folder, or URL) you give it.
@@ -8248,8 +9410,8 @@ import { existsSync as existsSync7, statSync as statSync2 } from "node:fs";
8248
9410
  import { isAbsolute, join as join9 } from "node:path";
8249
9411
  import { pathToFileURL as pathToFileURL3 } from "node:url";
8250
9412
  var loaded = /* @__PURE__ */ new Map();
8251
- function resolveModule(name, dir) {
8252
- const expanded = expandPath(name);
9413
+ function resolveModule(name2, dir) {
9414
+ const expanded = expandPath(name2);
8253
9415
  const base3 = isAbsolute(expanded) ? expanded : join9(expandPath(dir), expanded);
8254
9416
  for (const p of [base3, `${base3}.mjs`, `${base3}.js`, join9(base3, "index.mjs"), join9(base3, "index.js")]) {
8255
9417
  if (existsSync7(p) && statSync2(p).isFile()) return p;
@@ -8276,14 +9438,14 @@ var optionsSchema = t.object({
8276
9438
  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" } }),
8277
9439
  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 })
8278
9440
  });
8279
- function moduleConfig(mod, o) {
9441
+ function moduleConfig(mod2, o) {
8280
9442
  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]));
8281
9443
  let js = {};
8282
9444
  try {
8283
9445
  js = o.json.trim() ? JSON.parse(o.json) : {};
8284
9446
  } catch {
8285
9447
  }
8286
- return { ...mod?.defaults ?? {}, ...kv, ...js };
9448
+ return { ...mod2?.defaults ?? {}, ...kv, ...js };
8287
9449
  }
8288
9450
  var module2 = defineWidget({
8289
9451
  id: "module",
@@ -8298,36 +9460,36 @@ var module2 = defineWidget({
8298
9460
  if (!options2.module) throw new Error("no module set");
8299
9461
  const path = resolveModule(options2.module, options2.dir);
8300
9462
  if (!path) throw new Error(`module "${options2.module}" not found in ${options2.dir}`);
8301
- const mod = await load2(path);
9463
+ const mod2 = await load2(path);
8302
9464
  if (options2.json.trim()) JSON.parse(options2.json);
8303
- const data = mod.fetch ? await mod.fetch({ config: moduleConfig(mod, options2), now, log, canvas }) : void 0;
9465
+ const data = mod2.fetch ? await mod2.fetch({ config: moduleConfig(mod2, options2), now, log, canvas }) : void 0;
8304
9466
  return { path, data };
8305
9467
  },
8306
9468
  // The module's own `updateMs`, as in aimonitor.
8307
9469
  intervalOf: ({ data }) => data ? loaded.get(data.path)?.updateMs : void 0,
8308
9470
  render(g, ctx) {
8309
- const mod = ctx.data ? loaded.get(ctx.data.path) : void 0;
8310
- if (!mod) {
9471
+ const mod2 = ctx.data ? loaded.get(ctx.data.path) : void 0;
9472
+ if (!mod2) {
8311
9473
  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 });
8312
9474
  return;
8313
9475
  }
8314
9476
  const box = ctx.box;
8315
- 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 });
9477
+ 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 });
8316
9478
  },
8317
9479
  redraw: "minute",
8318
9480
  visible({ options: options2, data, now }) {
8319
- const mod = data ? loaded.get(data.path) : void 0;
8320
- return mod?.visible?.({ config: moduleConfig(mod, options2), data: data?.data, now }) ?? true;
9481
+ const mod2 = data ? loaded.get(data.path) : void 0;
9482
+ return mod2?.visible?.({ config: moduleConfig(mod2, options2), data: data?.data, now }) ?? true;
8321
9483
  },
8322
9484
  urgent({ options: options2, data, now }) {
8323
- const mod = data ? loaded.get(data.path) : void 0;
8324
- return mod?.urgent?.({ config: moduleConfig(mod, options2), data: data?.data, now }) ?? false;
9485
+ const mod2 = data ? loaded.get(data.path) : void 0;
9486
+ return mod2?.urgent?.({ config: moduleConfig(mod2, options2), data: data?.data, now }) ?? false;
8325
9487
  }
8326
9488
  });
8327
9489
  var src_default2 = definePlugin({
8328
9490
  id: "legacy",
8329
9491
  name: { en: "aimonitor compatibility", es: "Compatibilidad aimonitor", de: "aimonitor-Kompatibilit\xE4t", "zh-Hant": "aimonitor \u76F8\u5BB9\u6027", "zh-Hans": "aimonitor \u517C\u5BB9" },
8330
- version: "0.2.9",
9492
+ version: "0.2.11",
8331
9493
  languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
8332
9494
  sdk: "^0.2.0",
8333
9495
  // Runs the aimonitor modules you point it at, and reads their folder.
@@ -8341,7 +9503,7 @@ var src_default2 = definePlugin({
8341
9503
 
8342
9504
  // packages/server/src/official.ts
8343
9505
  var BUNDLED_PLUGIN_IDS = ["agents", "cats", "system", "vitals", "usage", "weather", "calendar", "news", "mirror", "gitlab", "github", "calls", "timesheet", "llm", "gpu", "homeassistant"];
8344
- var OPTIONAL_PLUGIN_IDS = ["doom", "video", "fractals", "gaming", "logs", "hazards", "batteries"];
9506
+ var OPTIONAL_PLUGIN_IDS = ["doom", "video", "fractals", "gaming", "logs", "hazards", "batteries", "switchbot"];
8345
9507
  var OFFICIAL_PLUGINS = [
8346
9508
  ...BUNDLED_PLUGIN_IDS.map((id) => ({ id, npm: `kiosko-plugin-${id}`, bundled: true })),
8347
9509
  ...OPTIONAL_PLUGIN_IDS.map((id) => ({ id, npm: `kiosko-plugin-${id}`, bundled: false }))
@@ -8432,9 +9594,9 @@ function readConfigText(text3) {
8432
9594
  }
8433
9595
  }
8434
9596
  function readInput(file) {
8435
- const name = file === "-" ? "(stdin)" : file;
8436
- if (file !== "-" && !existsSync9(file)) return { error: `not found: ${file}`, notes: [], name };
8437
- return { ...readConfigText(readFileSync5(file === "-" ? 0 : file, "utf8")), name };
9597
+ const name2 = file === "-" ? "(stdin)" : file;
9598
+ if (file !== "-" && !existsSync9(file)) return { error: `not found: ${file}`, notes: [], name: name2 };
9599
+ return { ...readConfigText(readFileSync5(file === "-" ? 0 : file, "utf8")), name: name2 };
8438
9600
  }
8439
9601
  var pluginDefs = (r) => r.list().map((p) => p.def);
8440
9602
  async function findRunning(cfg, configPath, o) {
@@ -8677,7 +9839,7 @@ async function runningAt(url2, timeoutMs = 1500) {
8677
9839
  return null;
8678
9840
  }
8679
9841
  }
8680
- async function editorCommand({ server, flags, open, log }) {
9842
+ async function editorCommand({ server, flags, open: open2, log }) {
8681
9843
  const url2 = editorUrl2(server, flags);
8682
9844
  const version = await runningAt(url2);
8683
9845
  if (!version) {
@@ -8687,7 +9849,7 @@ async function editorCommand({ server, flags, open, log }) {
8687
9849
  return 1;
8688
9850
  }
8689
9851
  log(`Kiosko ${version} \u2014 editor at ${url2}`);
8690
- if (!flags.print) open(url2);
9852
+ if (!flags.print) open2(url2);
8691
9853
  return 0;
8692
9854
  }
8693
9855
 
@@ -8717,12 +9879,12 @@ async function loadPluginDir(dir, o = {}) {
8717
9879
  const entry = (o.src || !built) && existsSync10(src) ? src : built;
8718
9880
  if (!entry) throw new Error(`no plugin in ${root}: no package.json "kiosko.plugin", index.js or src/index.ts`);
8719
9881
  installSdkResolver();
8720
- const mod = await import(`${pathToFileURL4(entry).href}?v=${Date.now()}`);
8721
- if (!mod.default) throw new Error(`${entry} has no default export (export default definePlugin({...}))`);
8722
- return { def: mod.default, pkg, entry };
9882
+ const mod2 = await import(`${pathToFileURL4(entry).href}?v=${Date.now()}`);
9883
+ if (!mod2.default) throw new Error(`${entry} has no default export (export default definePlugin({...}))`);
9884
+ return { def: mod2.default, pkg, entry };
8723
9885
  }
8724
- var flagOf = (argv2, name) => argv2.includes(name);
8725
- var optOf = (argv2, name) => argv2.includes(name) ? argv2[argv2.indexOf(name) + 1] : void 0;
9886
+ var flagOf = (argv2, name2) => argv2.includes(name2);
9887
+ var optOf = (argv2, name2) => argv2.includes(name2) ? argv2[argv2.indexOf(name2) + 1] : void 0;
8726
9888
  var positional = (argv2) => argv2.filter((a, i) => !a.startsWith("--") && !["--out", "--port"].includes(argv2[i - 1] ?? ""));
8727
9889
  function lookList(looks) {
8728
9890
  const parts = looks.map((l) => l.split(" "));
@@ -8794,11 +9956,11 @@ async function dev(dir, argv2) {
8794
9956
  }
8795
9957
  function newPluginFiles(id) {
8796
9958
  const sdk = `^${SDK_VERSION.split(".").slice(0, 2).join(".")}.0`;
8797
- const name = id.replace(/(^|-)(\w)/g, (_m, _d, c) => ` ${c.toUpperCase()}`).trim();
9959
+ const name2 = id.replace(/(^|-)(\w)/g, (_m, _d, c) => ` ${c.toUpperCase()}`).trim();
8798
9960
  const pkg = {
8799
9961
  name: `kiosko-plugin-${id}`,
8800
9962
  version: "0.1.0",
8801
- description: `${name} for Kiosko.`,
9963
+ description: `${name2} for Kiosko.`,
8802
9964
  type: "module",
8803
9965
  license: "MIT",
8804
9966
  keywords: ["kiosko", "kiosko-plugin", "lcd", "widgets"],
@@ -8823,7 +9985,7 @@ function newPluginFiles(id) {
8823
9985
  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" }
8824
9986
  };
8825
9987
  const index = `/**
8826
- * ${name}: a widget fed by a shared source. Rename, then fill in \`read\` and \`render\`.
9988
+ * ${name2}: a widget fed by a shared source. Rename, then fill in \`read\` and \`render\`.
8827
9989
  * The guide: https://github.com/kiosko-lcd/kiosko/blob/main/docs/plugins.md
8828
9990
  */
8829
9991
  import { createHttp, definePlugin, defineSource, defineWidget, t } from '@kiosko/sdk';
@@ -8837,7 +9999,7 @@ export interface Reading {
8837
9999
 
8838
10000
  export const reading = defineSource({
8839
10001
  id: 'reading',
8840
- name: { en: '${name}', es: '${name}' },
10002
+ name: { en: '${name2}', es: '${name2}' },
8841
10003
  description: { en: 'What the widgets show, read once for all of them.', es: 'Lo que muestran los widgets, le\xEDdo una vez para todos.' },
8842
10004
  options: t.object({
8843
10005
  url: t.string({ format: 'url', risk: 'network', placeholder: 'https://api.example.com/value', label: { en: 'Address', es: 'Direcci\xF3n' } }),
@@ -8853,14 +10015,14 @@ export const reading = defineSource({
8853
10015
 
8854
10016
  export const card = defineWidget({
8855
10017
  id: 'card',
8856
- name: { en: '${name}', es: '${name}' },
10018
+ name: { en: '${name2}', es: '${name2}' },
8857
10019
  description: { en: 'The latest value, in big.', es: 'El \xFAltimo valor, en grande.' },
8858
10020
  icon: 'gauge',
8859
10021
  category: 'info',
8860
10022
  size: { min: { w: 160, h: 80 }, preferred: { w: 320, h: 160 } },
8861
10023
  sources: ['${id}/reading'],
8862
10024
  options: t.object({
8863
- label: t.string({ default: '${name}', label: { en: 'Label', es: 'Etiqueta' } }),
10025
+ label: t.string({ default: '${name2}', label: { en: 'Label', es: 'Etiqueta' } }),
8864
10026
  }),
8865
10027
  redraw: 'minute',
8866
10028
  render(g, { box, options, sources, theme, kit, fmt }) {
@@ -8881,9 +10043,9 @@ export const card = defineWidget({
8881
10043
 
8882
10044
  export default definePlugin({
8883
10045
  id: '${id}',
8884
- name: { en: '${name}', es: '${name}' },
10046
+ name: { en: '${name2}', es: '${name2}' },
8885
10047
  version: '0.1.0',
8886
- description: { en: '${name} for Kiosko.', es: '${name} para Kiosko.' },
10048
+ description: { en: '${name2} for Kiosko.', es: '${name2} para Kiosko.' },
8887
10049
  sdk: '${sdk}',
8888
10050
  // The languages its texts come in (Chinese by script: 'zh-Hant', 'zh-Hans').
8889
10051
  languages: ['en', 'es'],
@@ -8900,7 +10062,7 @@ import plugin, { card } from './index.ts';
8900
10062
 
8901
10063
  test('the card shows the label and the value', () => {
8902
10064
  const r = renderWidget(card, { size: { w: 320, h: 160 } });
8903
- assert.deepEqual(r.texts.slice(0, 2), ['${name}', '42']);
10065
+ assert.deepEqual(r.texts.slice(0, 2), ['${name2}', '42']);
8904
10066
  assert.equal(r.outside, 0);
8905
10067
  });
8906
10068
 
@@ -8927,7 +10089,7 @@ console.log('dist/index.js');
8927
10089
  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"] };
8928
10090
  const readme = `# kiosko-plugin-${id}
8929
10091
 
8930
- ${name} for [Kiosko](https://github.com/kiosko-lcd/kiosko).
10092
+ ${name2} for [Kiosko](https://github.com/kiosko-lcd/kiosko).
8931
10093
 
8932
10094
  \`\`\`sh
8933
10095
  npm install
@@ -8997,9 +10159,9 @@ async function pluginsCommand(argv2, registry2) {
8997
10159
  case "dev":
8998
10160
  return dev(positional(names)[0] ?? ".", names);
8999
10161
  case "new": {
9000
- const [id, where] = positional(names);
10162
+ const [id, where2] = positional(names);
9001
10163
  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)");
9002
- const dir = resolve4(where ?? `kiosko-plugin-${id}`);
10164
+ const dir = resolve4(where2 ?? `kiosko-plugin-${id}`);
9003
10165
  if (existsSync10(dir) && readdirSync4(dir).length) throw new Error(`${dir} is not empty`);
9004
10166
  for (const [file, body2] of Object.entries(newPluginFiles(id))) {
9005
10167
  mkdirSync6(join12(dir, file, ".."), { recursive: true });
@@ -9007,7 +10169,7 @@ async function pluginsCommand(argv2, registry2) {
9007
10169
  }
9008
10170
  console.log(`${dir}
9009
10171
 
9010
- cd ${where ?? `kiosko-plugin-${id}`} && npm install && npm test
10172
+ cd ${where2 ?? `kiosko-plugin-${id}`} && npm install && npm test
9011
10173
  npm run kiosko:check then: npm run build && npm run dev`);
9012
10174
  return;
9013
10175
  }
@@ -9083,13 +10245,267 @@ plugins folder: ${paths.plugins}`);
9083
10245
  }
9084
10246
  }
9085
10247
 
10248
+ // packages/server/src/remote-cli.ts
10249
+ import { readFileSync as readFileSync7 } from "node:fs";
10250
+ import { hostname as hostname2 } from "node:os";
10251
+ import { createInterface } from "node:readline/promises";
10252
+
10253
+ // packages/server/src/remote-api.ts
10254
+ import { randomBytes as randomBytes3 } from "node:crypto";
10255
+ import { hostname } from "node:os";
10256
+ var PAIR_TTL_MS = 3 * 6e4;
10257
+ async function raw(req, limit) {
10258
+ const chunks = [];
10259
+ let size = 0;
10260
+ for await (const c of req) {
10261
+ size += c.length;
10262
+ if (size > limit) throw new ScreenError("tooBig", "body too large");
10263
+ chunks.push(c);
10264
+ }
10265
+ return Buffer.concat(chunks);
10266
+ }
10267
+ function remoteScreen(registry2, info, key, locale, host) {
10268
+ const rot = [0, 90, 180, 270].includes(info.rot) ? info.rot : 0;
10269
+ const quarter = rot === 90 || rot === 270;
10270
+ const width = (quarter ? info.h : info.w) || 320, height = (quarter ? info.w : info.h) || 172;
10271
+ const s = newScreen(info.id || "Remote screen", width, height, { driver: "remote", uid: info.uid, ...info.id ? { id: info.id } : {}, key, ...host ? { host } : {} });
10272
+ s.rotate = rot;
10273
+ s.jpegQuality = 85;
10274
+ s.maxBytes = Math.max(16 * 1024, Math.min(info.max - 1024, 90 * 1024));
10275
+ s.pages = [starterPage((t2) => !!registry2.widget(t2), { width, height, locale, agents: false })];
10276
+ return s;
10277
+ }
10278
+ function remoteApi(ctx) {
10279
+ const pending2 = /* @__PURE__ */ new Map();
10280
+ const locate = async (uid, host, port) => {
10281
+ if (host) return { host, port: port ?? 7428 };
10282
+ const t2 = ctx.locate?.(uid);
10283
+ if (t2) return t2;
10284
+ const b = browser();
10285
+ const f = b.get(uid) ?? (uid ? (await b.browse(2500)).find((x) => x.uid === uid) : void 0);
10286
+ return f ? { host: f.address, port: f.port } : void 0;
10287
+ };
10288
+ const fail = (res, err) => {
10289
+ if (err instanceof ScreenError) return ctx.json(res, err.code === "offline" ? 404 : 409, { error: err.message, code: `remote.${err.code}` });
10290
+ const e = err;
10291
+ return ctx.json(res, 502, { error: e?.message ?? String(err), code: "remote.unreachable" });
10292
+ };
10293
+ const screenOf = (id) => ctx.runtime.config.screens.find((s) => s.id === id);
10294
+ const remoteOf = (id) => {
10295
+ const s = screenOf(id);
10296
+ if (!s || s.device.driver !== "remote") return null;
10297
+ const d = ctx.runtime.deviceOf(id);
10298
+ return { screen: s, device: s.device, driver: d instanceof RemoteDevice ? d : null };
10299
+ };
10300
+ return async function handle(req, res, p, m) {
10301
+ if (p === "/api/remote/pair" && m === "POST") {
10302
+ const b = await ctx.body(req, 4096);
10303
+ const uid = String(b.uid ?? "");
10304
+ const at = await locate(uid, b.host, b.port);
10305
+ if (!at) return ctx.json(res, 404, { error: "that screen is not on the network", code: "remote.offline" }), true;
10306
+ try {
10307
+ const pairing = await Pairing.start(at.host, at.port, `Kiosko on ${hostname()}`.slice(0, 40));
10308
+ if (uid && pairing.info.uid !== uid) {
10309
+ pairing.cancel();
10310
+ return ctx.json(res, 409, { error: "another screen answers there", code: "remote.otherScreen" }), true;
10311
+ }
10312
+ const pairId = randomBytes3(12).toString("hex");
10313
+ const timer = setTimeout(() => {
10314
+ pending2.get(pairId)?.pairing.cancel();
10315
+ pending2.delete(pairId);
10316
+ }, PAIR_TTL_MS);
10317
+ timer.unref();
10318
+ pending2.set(pairId, { pairing, uid: pairing.info.uid, host: at.host, port: at.port, timer });
10319
+ ctx.json(res, 200, { pairId, ttl: pairing.ttl, screen: pairing.info });
10320
+ } catch (err) {
10321
+ fail(res, err);
10322
+ }
10323
+ return true;
10324
+ }
10325
+ let mm = /^\/api\/remote\/pair\/([0-9a-f]{24})$/.exec(p);
10326
+ if (mm && (m === "POST" || m === "DELETE")) {
10327
+ const job = pending2.get(mm[1]);
10328
+ if (!job) return ctx.json(res, 404, { error: "no such pairing (it expired?)", code: "remote.pairingOver" }), true;
10329
+ pending2.delete(mm[1]);
10330
+ clearTimeout(job.timer);
10331
+ if (m === "DELETE") {
10332
+ job.pairing.cancel();
10333
+ return ctx.json(res, 200, { ok: true }), true;
10334
+ }
10335
+ const b = await ctx.body(req, 4096);
10336
+ let key;
10337
+ try {
10338
+ key = await job.pairing.finish(String(b.code ?? ""));
10339
+ } catch (err) {
10340
+ return fail(res, err), true;
10341
+ }
10342
+ const info = job.pairing.info;
10343
+ const cfg = structuredClone(ctx.runtime.config);
10344
+ 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);
10345
+ const hex2 = key.toString("hex");
10346
+ if (s) {
10347
+ const keepHost = s.device.driver === "remote" ? s.device.host : void 0;
10348
+ const keepPort = s.device.driver === "remote" ? s.device.port : void 0;
10349
+ const keepBright = s.device.driver === "remote" ? s.device.brightness : void 0;
10350
+ s.device = { driver: "remote", uid: info.uid, id: info.id, key: hex2, ...keepHost ? { host: keepHost } : {}, ...keepPort ? { port: keepPort } : {}, ...keepBright !== void 0 ? { brightness: keepBright } : {} };
10351
+ } else {
10352
+ s = remoteScreen(ctx.runtime.registry, info, hex2, ctx.runtime.config.locale === "auto" ? "en" : ctx.runtime.config.locale);
10353
+ cfg.screens.push(s);
10354
+ }
10355
+ ctx.commit(cfg);
10356
+ return ctx.json(res, 200, { ok: true, screenId: s.id }), true;
10357
+ }
10358
+ mm = /^\/api\/screens\/([^/]+)\/remote\/(unpair|ota|logs)$/.exec(p);
10359
+ if (mm) {
10360
+ const id = decodeURIComponent(mm[1]);
10361
+ const r = remoteOf(id);
10362
+ if (!r) return ctx.json(res, 404, { error: "not a remote screen", code: "unknownScreen" }), true;
10363
+ const key = /^[0-9a-f]{64}$/.test(r.device.key ?? "") ? Buffer.from(r.device.key, "hex") : null;
10364
+ const run = async (fn) => {
10365
+ if (r.driver) return r.driver.exclusive(fn);
10366
+ const at = await locate(r.device.uid, r.device.host, r.device.port);
10367
+ if (!at) throw new ScreenError("offline", "that screen is not on the network");
10368
+ return fn(at.host, at.port);
10369
+ };
10370
+ try {
10371
+ if (mm[2] === "unpair" && m === "POST") {
10372
+ let told = false;
10373
+ if (key) {
10374
+ try {
10375
+ await run((h, port) => unpairScreen(h, port, key, r.device.uid));
10376
+ told = true;
10377
+ } catch {
10378
+ }
10379
+ }
10380
+ const cfg = structuredClone(ctx.runtime.config);
10381
+ const s = cfg.screens.find((x) => x.id === id);
10382
+ if (s.device.driver === "remote") delete s.device.key;
10383
+ ctx.commit(cfg);
10384
+ return ctx.json(res, 200, { ok: true, told }), true;
10385
+ }
10386
+ if (!key) return ctx.json(res, 409, { error: "not paired", code: "remote.notPaired" }), true;
10387
+ if (mm[2] === "logs" && m === "GET") return ctx.json(res, 200, { text: await run((h, port) => screenLogs(h, port, key, r.device.uid)) }), true;
10388
+ if (mm[2] === "ota" && m === "POST") {
10389
+ const image2 = await raw(req, 4 * 1024 * 1024);
10390
+ await run((h, port) => otaUpdate(h, port, key, r.device.uid, image2));
10391
+ return ctx.json(res, 200, { ok: true }), true;
10392
+ }
10393
+ } catch (err) {
10394
+ return fail(res, err), true;
10395
+ }
10396
+ }
10397
+ return false;
10398
+ };
10399
+ }
10400
+
10401
+ // packages/server/src/remote-cli.ts
10402
+ var say = (s) => console.log(s);
10403
+ function screenArg(cfg, q3) {
10404
+ const s = cfg.screens.find((x) => x.id === q3 || x.name === q3 || x.device.driver === "remote" && (x.device.uid === q3 || x.device.id === q3));
10405
+ if (!s || s.device.driver !== "remote") throw new Error(`no remote screen "${q3 ?? ""}" in the config (kiosko remote list)`);
10406
+ return s;
10407
+ }
10408
+ async function where(d) {
10409
+ if (d.host) return { host: d.host, port: d.port ?? PORT };
10410
+ const b = browser();
10411
+ const f = b.get(d.uid) ?? (await b.browse(2500)).find((x) => x.uid === d.uid);
10412
+ if (!f) throw new Error(`screen ${d.uid} is not on the network (no mDNS answer)`);
10413
+ return { host: f.address, port: f.port };
10414
+ }
10415
+ async function viaServer(port, path, init) {
10416
+ try {
10417
+ return await fetch(`http://127.0.0.1:${port}${path}`, { ...init, headers: { "x-kiosko": "1", ...init.headers ?? {} } });
10418
+ } catch {
10419
+ return null;
10420
+ }
10421
+ }
10422
+ async function remoteCommand(args, o) {
10423
+ const [sub = "list", a, b] = args.filter((x, i, all) => !x.startsWith("--") && !(i > 0 && all[i - 1].startsWith("--")));
10424
+ const opt2 = (n) => {
10425
+ const i = args.indexOf(n);
10426
+ return i >= 0 ? args[i + 1] : void 0;
10427
+ };
10428
+ const { config: cfg } = loadConfig(o.configPath);
10429
+ try {
10430
+ if (sub === "list") {
10431
+ const found = await browser().browse(2500);
10432
+ if (!found.length) say("no Kiosko remote screen answered on this network (mDNS _kiosko-screen._tcp)");
10433
+ for (const f of found) {
10434
+ const used = cfg.screens.find((s) => s.device.driver === "remote" && s.device.uid === f.uid);
10435
+ 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}"` : ""}`);
10436
+ }
10437
+ 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)`);
10438
+ return 0;
10439
+ }
10440
+ if (sub === "pair") {
10441
+ if (!a) throw new Error("usage: kiosko remote pair <uid|host> [--screen id]");
10442
+ const isUid = /^[0-9a-f]{12}$/i.test(a);
10443
+ const at = isUid ? await where({ uid: a.toLowerCase() }) : { host: a, port: Number(opt2("--port-screen")) || PORT };
10444
+ const info = await probe(at.host, at.port);
10445
+ say(`${info.id} (${info.model}, uid ${info.uid}) at ${at.host}`);
10446
+ const p = await Pairing.start(at.host, at.port, `Kiosko on ${hostname2()}`.slice(0, 40));
10447
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
10448
+ const code = await rl.question("Code shown on the screen: ");
10449
+ rl.close();
10450
+ const key = (await p.finish(code)).toString("hex");
10451
+ const next = structuredClone(cfg);
10452
+ 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);
10453
+ if (target) target.device = { driver: "remote", uid: info.uid, id: info.id, key, ...isUid ? {} : { host: at.host } };
10454
+ else next.screens.push(remoteScreen(await o.registry(), info, key, "en", isUid ? void 0 : at.host));
10455
+ saveConfig(normalize(next), o.configPath);
10456
+ say(`paired; saved in ${o.configPath}${target ? ` (screen "${target.name}")` : " as a new screen"}. A Kiosko running here picks it up when it restarts.`);
10457
+ return 0;
10458
+ }
10459
+ if (sub === "ota" || sub === "logs" || sub === "unpair") {
10460
+ const s = screenArg(cfg, a);
10461
+ const id = encodeURIComponent(s.id);
10462
+ const image2 = sub === "ota" ? readFileSync7(b ?? "") : null;
10463
+ if (sub === "ota" && !b) throw new Error("usage: kiosko remote ota <screen> <firmware.bin>");
10464
+ const r = await viaServer(o.port, `/api/screens/${id}/remote/${sub}`, sub === "logs" ? {} : { method: "POST", ...image2 ? { body: new Uint8Array(image2) } : {} });
10465
+ if (r && r.status !== 404) {
10466
+ const j = await r.json();
10467
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
10468
+ 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");
10469
+ return 0;
10470
+ }
10471
+ const key = /^[0-9a-f]{64}$/.test(s.device.key ?? "") ? Buffer.from(s.device.key, "hex") : null;
10472
+ if (!key) throw new Error(`screen "${s.name}" is not paired`);
10473
+ const at = await where(s.device);
10474
+ if (sub === "logs") say(await screenLogs(at.host, at.port, key, s.device.uid));
10475
+ else if (sub === "ota") {
10476
+ let last2 = -1;
10477
+ await otaUpdate(at.host, at.port, key, s.device.uid, image2, (sent, total) => {
10478
+ const pct = Math.floor(sent * 100 / total);
10479
+ if (pct >= last2 + 10) process.stdout.write(`${last2 = pct}% `);
10480
+ });
10481
+ say("\nupdated: the screen restarts into it (and goes back by itself if this Kiosko cannot talk to it)");
10482
+ } else {
10483
+ await unpairScreen(at.host, at.port, key, s.device.uid);
10484
+ const next = structuredClone(cfg);
10485
+ const t2 = next.screens.find((x) => x.id === s.id);
10486
+ if (t2.device.driver === "remote") delete t2.device.key;
10487
+ saveConfig(normalize(next), o.configPath);
10488
+ say("unpaired");
10489
+ }
10490
+ return 0;
10491
+ }
10492
+ say("usage: kiosko remote [list] | pair <uid|host> [--screen id] | ota <screen> <file.bin> | logs <screen> | unpair <screen>");
10493
+ return 2;
10494
+ } catch (err) {
10495
+ console.error(`\u2717 ${err instanceof Error ? err.message : String(err)}`);
10496
+ return 1;
10497
+ } finally {
10498
+ browser().close();
10499
+ }
10500
+ }
10501
+
9086
10502
  // packages/server/src/gallery.ts
9087
10503
  import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync8 } from "node:fs";
9088
10504
  import { join as join13 } from "node:path";
9089
10505
  var HOME_URL = "https://kioskolcd.dev/";
9090
10506
  var RELEASES_URL = "https://github.com/kiosko-lcd/kiosko/releases/latest";
9091
10507
  var MADRID = { latitude: 40.4168, longitude: -3.7038, name: "Madrid" };
9092
- var T = {
10508
+ var T2 = {
9093
10509
  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" },
9094
10510
  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" },
9095
10511
  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" },
@@ -9149,7 +10565,7 @@ function buildGallery(registry2, o) {
9149
10565
  mkdirSync7(join13(o.out, folder(lang.id)), { recursive: true });
9150
10566
  writeFileSync8(
9151
10567
  join13(o.out, folder(lang.id), "index.html"),
9152
- `<!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>
10568
+ `<!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>
9153
10569
  <style>
9154
10570
  :root{color-scheme:dark;--bg:#0a0d13;--panel:#121722;--line:rgba(255,255,255,.08);--text:#e7ecf4;--dim:#a3adbf}
9155
10571
  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}
@@ -9166,15 +10582,15 @@ figcaption code{color:#22d3ee;font-size:12px}figcaption span{flex-basis:100%;col
9166
10582
  a{color:#22d3ee}
9167
10583
  p.os{margin-top:14px}p.os b{color:var(--text)}
9168
10584
  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}
9169
- </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>`
10585
+ </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>`
9170
10586
  );
9171
10587
  }
9172
10588
  if (o.pages) {
9173
10589
  const sample = normalize(o.pages);
9174
10590
  const screen = [...sample.screens].sort((a, b) => b.width / b.height - a.width / a.height)[0];
9175
10591
  for (const page of screen?.pages.filter((p) => p.enabled !== false) ?? []) {
9176
- const name = `img/page-${slug2(page.name || page.id)}`;
9177
- 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 });
10592
+ const name2 = `img/page-${slug2(page.name || page.id)}`;
10593
+ 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 });
9178
10594
  }
9179
10595
  for (const l of langs) {
9180
10596
  const local = normalize({ ...localizeSample(sample, l.locale), locale: l.locale });
@@ -9244,7 +10660,7 @@ function widgetFor(m, reg, notes, modulesDir) {
9244
10660
  }
9245
10661
  return { ...base3, type: "legacy/module", options: { module: m.module, dir: modulesDir, json: m.config ? JSON.stringify(m.config, null, 2) : "" } };
9246
10662
  }
9247
- function columnsPage(name, width, height, mods, rotateMs, reg, notes, modulesDir) {
10663
+ function columnsPage(name2, width, height, mods, rotateMs, reg, notes, modulesDir) {
9248
10664
  const groups = [];
9249
10665
  const byColumn = /* @__PURE__ */ new Map();
9250
10666
  for (const m of mods) {
@@ -9266,7 +10682,7 @@ function columnsPage(name, width, height, mods, rotateMs, reg, notes, modulesDir
9266
10682
  x += w;
9267
10683
  return t2;
9268
10684
  });
9269
- return { id: newId("page"), name, enabled: true, durationMs: 10 * 6e4, when: "always", grid, gravity: "left", background: {}, tiles };
10685
+ return { id: newId("page"), name: name2, enabled: true, durationMs: 10 * 6e4, when: "always", grid, gravity: "left", background: {}, tiles };
9270
10686
  }
9271
10687
  function importAimonitor(old, reg, modeOverride, o = {}) {
9272
10688
  const notes = [];
@@ -9277,19 +10693,19 @@ function importAimonitor(old, reg, modeOverride, o = {}) {
9277
10693
  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 } : {} };
9278
10694
  const grid = { cols: 24, rows: 6, gap: 10, padding: 10 };
9279
10695
  const W = (type, options2 = {}, title) => ({ id: newId("w"), type, options: options2, ...title ? { title } : {} });
9280
- const T2 = (x, y, w, h, widgets, chrome = "auto", rotateMs = 3e4) => ({ id: newId("tile"), x, y, w, h, widgets, rotateMs, chrome });
10696
+ const T3 = (x, y, w, h, widgets, chrome = "auto", rotateMs = 3e4) => ({ id: newId("tile"), x, y, w, h, widgets, rotateMs, chrome });
9281
10697
  const railOn = old.rail?.enabled !== false && old.usage?.enabled !== false;
9282
10698
  const sysOn = old.system?.enabled !== false;
9283
10699
  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 } : {} };
9284
- 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")];
9285
- if (sysOn) dashTiles.push(T2(railOn ? 13 : 18, 1, 6, 5, [W("vitals/vitals")], "bare"));
9286
- if (railOn) dashTiles.push(T2(19, 1, 5, 5, [W("usage/rail")], "bare"));
10700
+ 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")];
10701
+ if (sysOn) dashTiles.push(T3(railOn ? 13 : 18, 1, 6, 5, [W("vitals/vitals")], "bare"));
10702
+ if (railOn) dashTiles.push(T3(19, 1, 5, 5, [W("usage/rail")], "bare"));
9287
10703
  const dashboard = { id: newId("page"), name: "Dashboard", enabled: true, durationMs: old.scene?.alternateMs ?? 10 * 6e4, when: "always", grid, gravity: "none", background: {}, tiles: dashTiles };
9288
10704
  const cardWidgets = (old.modules ?? []).map((m) => widgetFor(m, reg, notes, modulesDir)).filter((w) => !!w);
9289
10705
  if (railOn) cardWidgets.push(W("usage/rail", {}, "Consumo"));
9290
10706
  const side = old.scene?.side === "izquierda" ? "left" : "right";
9291
- 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")];
9292
- if (cardWidgets.length) catsTiles.push(T2(side === "right" ? 17 : 0, 0, 7, 6, cardWidgets, "card", old.timesheet?.alternateMs || 3e4));
10707
+ 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")];
10708
+ if (cardWidgets.length) catsTiles.push(T3(side === "right" ? 17 : 0, 0, 7, 6, cardWidgets, "card", old.timesheet?.alternateMs || 3e4));
9293
10709
  const cats = { id: newId("page"), name: "Cats", enabled: true, durationMs: old.scene?.alternateMs ?? 10 * 6e4, when: "always", grid, gravity: "none", background: {}, tiles: catsTiles };
9294
10710
  const override = (modeOverride ?? "").trim().toLowerCase();
9295
10711
  const mode = ["gatos", "tablero", "alternar"].includes(override) ? override : old.scene?.mode ?? "tablero";
@@ -9478,8 +10894,8 @@ function runService(action, plan) {
9478
10894
 
9479
10895
  // packages/server/src/server.ts
9480
10896
  import { spawn as spawn2 } from "node:child_process";
9481
- import { randomBytes } from "node:crypto";
9482
- import { existsSync as existsSync16, openSync, readFileSync as readFileSync11, statSync as statSync3 } from "node:fs";
10897
+ import { randomBytes as randomBytes4 } from "node:crypto";
10898
+ import { existsSync as existsSync16, openSync, readFileSync as readFileSync12, statSync as statSync3 } from "node:fs";
9483
10899
  import { createServer } from "node:http";
9484
10900
  import { tmpdir as tmpdir2 } from "node:os";
9485
10901
  import { createRequire as createRequire3 } from "node:module";
@@ -9487,7 +10903,7 @@ import { dirname as dirname8, extname, join as join18, normalize as normPath, re
9487
10903
 
9488
10904
  // packages/server/src/plugins-manage.ts
9489
10905
  import { execFile } from "node:child_process";
9490
- import { existsSync as existsSync12, lstatSync as lstatSync2, mkdirSync as mkdirSync9, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "node:fs";
10906
+ import { existsSync as existsSync12, lstatSync as lstatSync2, mkdirSync as mkdirSync9, readFileSync as readFileSync8, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "node:fs";
9491
10907
  import { join as join15, relative as relative2, resolve as resolve6, sep } from "node:path";
9492
10908
  var NPM_NAME = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(@[\w.^~<>=*-]+)?$/i;
9493
10909
  var packageName = (spec) => spec.startsWith("@") ? `@${spec.slice(1).split("@")[0]}` : spec.split("@")[0];
@@ -9504,10 +10920,10 @@ var realNpm = (args, cwd) => new Promise((ok, fail) => {
9504
10920
  const npm2 = process.platform === "win32" ? "npm.cmd" : "npm";
9505
10921
  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)));
9506
10922
  });
9507
- function installedIntegrity(dir, name) {
10923
+ function installedIntegrity(dir, name2) {
9508
10924
  try {
9509
- const lock = JSON.parse(readFileSync7(join15(dir, "node_modules", ".package-lock.json"), "utf8"));
9510
- return lock.packages?.[`node_modules/${name}`]?.integrity;
10925
+ const lock = JSON.parse(readFileSync8(join15(dir, "node_modules", ".package-lock.json"), "utf8"));
10926
+ return lock.packages?.[`node_modules/${name2}`]?.integrity;
9511
10927
  } catch {
9512
10928
  return void 0;
9513
10929
  }
@@ -9519,7 +10935,7 @@ async function installPlugin(spec, o) {
9519
10935
  const npm2 = o.npm ?? realNpm;
9520
10936
  const r = o.registry;
9521
10937
  const folder = join15(dir, "node_modules", packageName(spec));
9522
- const readPkg = () => existsSync12(join15(folder, "package.json")) ? JSON.parse(readFileSync7(join15(folder, "package.json"), "utf8")) : null;
10938
+ const readPkg = () => existsSync12(join15(folder, "package.json")) ? JSON.parse(readFileSync8(join15(folder, "package.json"), "utf8")) : null;
9523
10939
  const beforePkg = readPkg();
9524
10940
  const beforeId = beforePkg ? packageMeta(beforePkg).id : void 0;
9525
10941
  const output = await npm2(["install", "--no-audit", "--no-fund", "--ignore-scripts", "--save-exact", spec], dir);
@@ -9572,8 +10988,8 @@ async function removePlugin(id, o) {
9572
10988
  if (rel.startsWith("..") || rel === "") return { removed: false, reason: `it was loaded from ${origin}, outside the plugins folder` };
9573
10989
  const parts = rel.split(sep);
9574
10990
  if (parts[0] === "node_modules") {
9575
- const name = parts[1].startsWith("@") ? `${parts[1]}/${parts[2]}` : parts[1];
9576
- await (o.npm ?? realNpm)(["uninstall", "--no-audit", "--no-fund", name], dir);
10991
+ const name2 = parts[1].startsWith("@") ? `${parts[1]}/${parts[2]}` : parts[1];
10992
+ await (o.npm ?? realNpm)(["uninstall", "--no-audit", "--no-fund", name2], dir);
9577
10993
  } else {
9578
10994
  const top = join15(dir, parts[0]);
9579
10995
  if (!lstatSync2(top).isSymbolicLink()) return { removed: false, reason: `${top} is a folder you put there: delete it yourself if you mean it` };
@@ -9590,7 +11006,7 @@ async function reloadPlugin(id, o) {
9590
11006
  }
9591
11007
 
9592
11008
  // packages/server/src/store.ts
9593
- import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync8, renameSync as renameSync4, writeFileSync as writeFileSync11 } from "node:fs";
11009
+ import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync9, renameSync as renameSync4, writeFileSync as writeFileSync11 } from "node:fs";
9594
11010
  import { dirname as dirname6, join as join16 } from "node:path";
9595
11011
  var STORE_URL = "https://kioskolcd.dev/store/v1/";
9596
11012
  function shipped(...candidates) {
@@ -9600,7 +11016,7 @@ function shipped(...candidates) {
9600
11016
  function snapshotIndex() {
9601
11017
  const file = shipped(join16(import.meta.dirname, "../assets/store-index.json"), join16(import.meta.dirname, "assets/store-index.json"));
9602
11018
  try {
9603
- return file ? JSON.parse(readFileSync8(file, "utf8")) : null;
11019
+ return file ? JSON.parse(readFileSync9(file, "utf8")) : null;
9604
11020
  } catch {
9605
11021
  return null;
9606
11022
  }
@@ -9609,7 +11025,7 @@ var schema;
9609
11025
  function indexSchema() {
9610
11026
  if (schema !== void 0) return schema;
9611
11027
  const file = shipped(join16(import.meta.dirname, "../../core/schema/store-index.json"), join16(import.meta.dirname, "assets/store-index.schema.json"));
9612
- schema = file ? JSON.parse(readFileSync8(file, "utf8")) : null;
11028
+ schema = file ? JSON.parse(readFileSync9(file, "utf8")) : null;
9613
11029
  return schema;
9614
11030
  }
9615
11031
  function indexProblem(x) {
@@ -9641,7 +11057,7 @@ var StoreCatalog = class {
9641
11057
  }
9642
11058
  readCache() {
9643
11059
  try {
9644
- const c = JSON.parse(readFileSync8(this.file, "utf8"));
11060
+ const c = JSON.parse(readFileSync9(this.file, "utf8"));
9645
11061
  return indexProblem(c.index) ? null : c;
9646
11062
  } catch {
9647
11063
  return null;
@@ -9706,10 +11122,10 @@ var StoreCatalog = class {
9706
11122
  };
9707
11123
 
9708
11124
  // packages/server/src/homeassistant.ts
9709
- import { hostname } from "node:os";
11125
+ import { hostname as hostname3 } from "node:os";
9710
11126
 
9711
11127
  // packages/server/src/mqtt.ts
9712
- import { EventEmitter as EventEmitter2 } from "node:events";
11128
+ import { EventEmitter as EventEmitter3 } from "node:events";
9713
11129
  import { connect as tcp } from "node:net";
9714
11130
  import { connect as tls } from "node:tls";
9715
11131
  var RETRY_MS2 = [2e3, 5e3, 1e4, 3e4, 6e4];
@@ -9782,7 +11198,7 @@ var CONNACK_ERRORS = {
9782
11198
  4: "wrong user name or password",
9783
11199
  5: "not authorised"
9784
11200
  };
9785
- var MqttClient = class extends EventEmitter2 {
11201
+ var MqttClient = class extends EventEmitter3 {
9786
11202
  state = "connecting";
9787
11203
  error = null;
9788
11204
  sock = null;
@@ -9923,10 +11339,10 @@ function pageOptions(screen, auto) {
9923
11339
  const byName = /* @__PURE__ */ new Map([[auto, null]]);
9924
11340
  const nameOf = /* @__PURE__ */ new Map();
9925
11341
  for (const p of screen.pages.filter((x) => x.enabled)) {
9926
- let name = p.name.trim() || p.id;
9927
- for (let i = 2; byName.has(name); i++) name = `${p.name} (${i})`;
9928
- byName.set(name, p.id);
9929
- nameOf.set(p.id, name);
11342
+ let name2 = p.name.trim() || p.id;
11343
+ for (let i = 2; byName.has(name2); i++) name2 = `${p.name} (${i})`;
11344
+ byName.set(name2, p.id);
11345
+ nameOf.set(p.id, name2);
9930
11346
  }
9931
11347
  return { options: [...byName.keys()], byName, nameOf };
9932
11348
  }
@@ -9989,7 +11405,7 @@ var HomeAssistantBridge = class {
9989
11405
  const base3 = `kiosko/${want.nodeId}`;
9990
11406
  const c = this.makeClient({
9991
11407
  url: want.broker,
9992
- clientId: `kiosko-${want.nodeId}-${hostname().slice(0, 20)}`.slice(0, 23),
11408
+ clientId: `kiosko-${want.nodeId}-${hostname3().slice(0, 20)}`.slice(0, 23),
9993
11409
  ...want.username ? { username: want.username } : {},
9994
11410
  ...want.password ? { password: want.password } : {},
9995
11411
  keepalive: 30,
@@ -10089,9 +11505,9 @@ var HomeAssistantBridge = class {
10089
11505
  });
10090
11506
  for (const slot of screen.interludes) {
10091
11507
  const def = this.runtime.registry.interlude(slot.type);
10092
- const name = def ? this.loc(def.name) || slot.type : slot.type;
11508
+ const name2 = def ? this.loc(def.name) || slot.type : slot.type;
10093
11509
  put("button", `${sid}_${slug3(slot.id)}`, {
10094
- name: `${this.loc(NAMES.interlude)}: ${name}`,
11510
+ name: `${this.loc(NAMES.interlude)}: ${name2}`,
10095
11511
  unique_id: id(slug3(slot.id)),
10096
11512
  icon: "mdi:play-circle-outline",
10097
11513
  command_topic: `${this.base}/${sid}/interlude/${slot.id}/press`,
@@ -10167,42 +11583,42 @@ var HomeAssistantBridge = class {
10167
11583
  };
10168
11584
 
10169
11585
  // packages/server/src/install-kind.ts
10170
- import { existsSync as existsSync14, readFileSync as readFileSync9, realpathSync } from "node:fs";
11586
+ import { existsSync as existsSync14, readFileSync as readFileSync10, realpathSync } from "node:fs";
10171
11587
  import { posix, win32 as win323 } from "node:path";
10172
11588
  function detectInstall(i) {
10173
11589
  const exists = i.exists ?? existsSync14;
10174
- const read = i.readFile ?? ((p) => readFileSync9(p, "utf8"));
11590
+ const read = i.readFile ?? ((p) => readFileSync10(p, "utf8"));
10175
11591
  const win = i.platform === "win32";
10176
- const P = win ? win323 : posix;
11592
+ const P2 = win ? win323 : posix;
10177
11593
  const cli = i.cli;
10178
- const service = detectService(i.platform, i.env, read);
10179
- const base3 = { cli, service, platform: i.platform };
11594
+ const service2 = detectService(i.platform, i.env, read);
11595
+ const base3 = { cli, service: service2, platform: i.platform };
10180
11596
  const norm = (p) => win ? p.toLowerCase() : p;
10181
11597
  const gitUp = (from) => {
10182
11598
  for (let d = from, n = 0; n < 8; n++) {
10183
- if (exists(P.join(d, ".git"))) return d;
10184
- const up = P.dirname(d);
11599
+ if (exists(P2.join(d, ".git"))) return d;
11600
+ const up = P2.dirname(d);
10185
11601
  if (up === d) break;
10186
11602
  d = up;
10187
11603
  }
10188
11604
  return null;
10189
11605
  };
10190
- if (cli.endsWith(".ts")) return { ...base3, kind: "source", dir: gitUp(P.dirname(cli)) ?? P.resolve(P.dirname(cli), "..", "..", "..") };
10191
- const dir = P.dirname(cli);
10192
- if (win && P.basename(dir).toLowerCase() === "app") {
10193
- const app = P.dirname(dir);
10194
- if (exists(P.join(app, "kiosko.cmd")) && exists(P.join(app, "unins000.exe")) && norm(i.execPath) === norm(P.join(app, "node.exe"))) {
10195
- const local = i.env.LOCALAPPDATA && norm(app).startsWith(norm(P.join(i.env.LOCALAPPDATA, "Programs") + P.sep));
11606
+ if (cli.endsWith(".ts")) return { ...base3, kind: "source", dir: gitUp(P2.dirname(cli)) ?? P2.resolve(P2.dirname(cli), "..", "..", "..") };
11607
+ const dir = P2.dirname(cli);
11608
+ if (win && P2.basename(dir).toLowerCase() === "app") {
11609
+ const app = P2.dirname(dir);
11610
+ if (exists(P2.join(app, "kiosko.cmd")) && exists(P2.join(app, "unins000.exe")) && norm(i.execPath) === norm(P2.join(app, "node.exe"))) {
11611
+ const local = i.env.LOCALAPPDATA && norm(app).startsWith(norm(P2.join(i.env.LOCALAPPDATA, "Programs") + P2.sep));
10196
11612
  return { ...base3, kind: "windows-installer", dir: app, perUser: !!local };
10197
11613
  }
10198
11614
  }
10199
11615
  const checkout = gitUp(dir);
10200
11616
  if (checkout && !/[\\/]node_modules[\\/]/.test(dir)) return { ...base3, kind: "source", dir: checkout };
10201
11617
  if (/[\\/]_npx[\\/]/.test(dir)) return { ...base3, kind: "npx", dir };
10202
- if (P.basename(dir) === "kiosko" && P.basename(P.dirname(dir)) === "node_modules") {
10203
- const nm = P.dirname(dir);
10204
- const prefix = win ? P.dirname(nm) : P.basename(P.dirname(nm)) === "lib" ? P.dirname(P.dirname(nm)) : null;
10205
- const shim = prefix && (win ? exists(P.join(prefix, "kiosko.cmd")) : exists(P.join(prefix, "bin", "kiosko")));
11618
+ if (P2.basename(dir) === "kiosko" && P2.basename(P2.dirname(dir)) === "node_modules") {
11619
+ const nm = P2.dirname(dir);
11620
+ const prefix = win ? P2.dirname(nm) : P2.basename(P2.dirname(nm)) === "lib" ? P2.dirname(P2.dirname(nm)) : null;
11621
+ const shim = prefix && (win ? exists(P2.join(prefix, "kiosko.cmd")) : exists(P2.join(prefix, "bin", "kiosko")));
10206
11622
  if (prefix && shim) return { ...base3, kind: "npm-global", dir, prefix };
10207
11623
  }
10208
11624
  return { ...base3, kind: "other", dir };
@@ -10250,8 +11666,8 @@ function updateBlocker(info, o = {}) {
10250
11666
 
10251
11667
  // packages/server/src/self-update.ts
10252
11668
  import { spawn } from "node:child_process";
10253
- import { createHash } from "node:crypto";
10254
- import { createReadStream, createWriteStream, existsSync as existsSync15, mkdirSync as mkdirSync11, readFileSync as readFileSync10, realpathSync as realpathSync2, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "node:fs";
11669
+ import { createHash as createHash3 } from "node:crypto";
11670
+ import { createReadStream, createWriteStream, existsSync as existsSync15, mkdirSync as mkdirSync11, readFileSync as readFileSync11, realpathSync as realpathSync2, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "node:fs";
10255
11671
  import { dirname as dirname7, join as join17, win32 as win324 } from "node:path";
10256
11672
  import { Readable, Transform } from "node:stream";
10257
11673
  import { pipeline } from "node:stream/promises";
@@ -10287,15 +11703,15 @@ function judgeSelfCheck(now, next, target) {
10287
11703
  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 };
10288
11704
  return { ok: true, warnings };
10289
11705
  }
10290
- function parseSha256File(text3, name) {
11706
+ function parseSha256File(text3, name2) {
10291
11707
  for (const line of text3.split(/\r?\n/)) {
10292
11708
  const m = /^([a-f0-9]{64})(?:\s+\*?(.+?))?\s*$/i.exec(line.trim());
10293
- if (m && (!m[2] || m[2] === name)) return m[1].toLowerCase();
11709
+ if (m && (!m[2] || m[2] === name2)) return m[1].toLowerCase();
10294
11710
  }
10295
11711
  return null;
10296
11712
  }
10297
11713
  async function sha256File(file) {
10298
- const h = createHash("sha256");
11714
+ const h = createHash3("sha256");
10299
11715
  await pipeline(createReadStream(file), h);
10300
11716
  return h.digest("hex");
10301
11717
  }
@@ -10348,10 +11764,10 @@ var KioskoUpdater = class {
10348
11764
  }
10349
11765
  step(code, ok, detail) {
10350
11766
  const steps = [...this.status.steps];
10351
- const open = steps.findLastIndex((s2) => s2.code === code && s2.ok === null);
10352
- const keep = detail ?? (open >= 0 ? steps[open].detail : void 0);
11767
+ const open2 = steps.findLastIndex((s2) => s2.code === code && s2.ok === null);
11768
+ const keep = detail ?? (open2 >= 0 ? steps[open2].detail : void 0);
10353
11769
  const s = { at: this.now, code, ok, ...keep ? { detail: keep } : {} };
10354
- if (open >= 0 && ok !== null) steps[open] = s;
11770
+ if (open2 >= 0 && ok !== null) steps[open2] = s;
10355
11771
  else steps.push(s);
10356
11772
  if (ok !== null || detail) this.say(`${code}${ok === false ? " failed" : ok ? " ok" : ""}${detail ? `: ${detail}` : ""}`);
10357
11773
  this.set({ steps });
@@ -10526,27 +11942,27 @@ var KioskoUpdater = class {
10526
11942
  }
10527
11943
  // ---------- Windows ----------
10528
11944
  async downloadInstaller(version) {
10529
- const name = windowsInstallerName(version);
10530
- const exeUrl = releaseAsset(version, name);
11945
+ const name2 = windowsInstallerName(version);
11946
+ const exeUrl = releaseAsset(version, name2);
10531
11947
  const dir = join17(this.d.tmpDir, `kiosko-update-${version}`);
10532
11948
  rmSync4(dir, { recursive: true, force: true });
10533
11949
  mkdirSync11(dir, { recursive: true });
10534
- const file = join17(dir, name);
11950
+ const file = join17(dir, name2);
10535
11951
  this.step("download", null, exeUrl);
10536
11952
  let expected;
10537
11953
  try {
10538
11954
  const r = await this.d.fetch(`${exeUrl}.sha256`, { redirect: "follow" });
10539
11955
  if (!r.ok) throw new Error(`HTTP ${r.status}`);
10540
- expected = parseSha256File((await r.text()).slice(0, 4096), name);
11956
+ expected = parseSha256File((await r.text()).slice(0, 4096), name2);
10541
11957
  } catch (err) {
10542
- this.step("download", false, `${name}.sha256: ${err instanceof Error ? err.message : String(err)}`);
10543
- throw new UpdateError("downloadFailed", `could not download ${name}.sha256 from GitHub: download the installer from the release page instead`);
11958
+ this.step("download", false, `${name2}.sha256: ${err instanceof Error ? err.message : String(err)}`);
11959
+ throw new UpdateError("downloadFailed", `could not download ${name2}.sha256 from GitHub: download the installer from the release page instead`);
10544
11960
  }
10545
11961
  if (!expected) {
10546
- this.step("download", false, `${name}.sha256 names no checksum for ${name}`);
10547
- throw new UpdateError("hashMissing", `the release has no usable checksum for ${name}: not running it`);
11962
+ this.step("download", false, `${name2}.sha256 names no checksum for ${name2}`);
11963
+ throw new UpdateError("hashMissing", `the release has no usable checksum for ${name2}: not running it`);
10548
11964
  }
10549
- const hash = createHash("sha256");
11965
+ const hash = createHash3("sha256");
10550
11966
  let size = 0;
10551
11967
  try {
10552
11968
  const r = await this.d.fetch(exeUrl, { redirect: "follow" });
@@ -10563,14 +11979,14 @@ var KioskoUpdater = class {
10563
11979
  } catch (err) {
10564
11980
  rmSync4(dir, { recursive: true, force: true });
10565
11981
  this.step("download", false, err instanceof Error ? err.message : String(err));
10566
- throw new UpdateError("downloadFailed", `could not download ${name}: ${err instanceof Error ? err.message : String(err)}`);
11982
+ throw new UpdateError("downloadFailed", `could not download ${name2}: ${err instanceof Error ? err.message : String(err)}`);
10567
11983
  }
10568
11984
  this.step("download", true, `${(size / 1024 / 1024).toFixed(1)} MB`);
10569
11985
  const got = hash.digest("hex");
10570
11986
  if (got !== expected) {
10571
11987
  rmSync4(dir, { recursive: true, force: true });
10572
11988
  this.step("hash", false, `sha256 ${got}, the release says ${expected}`);
10573
- throw new UpdateError("hashMismatch", `${name} is not the file the release publishes (sha256 ${got.slice(0, 12)}\u2026, expected ${expected.slice(0, 12)}\u2026): deleted, not run`);
11989
+ 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`);
10574
11990
  }
10575
11991
  this.step("hash", true, `sha256 ${got}`);
10576
11992
  this.file = file;
@@ -10587,10 +12003,10 @@ var KioskoUpdater = class {
10587
12003
  }
10588
12004
  const info = this.d.install;
10589
12005
  const dir = dirname7(this.file);
10590
- const service = await this.d.serviceTask?.().catch(() => false) ?? false;
12006
+ const service2 = await this.d.serviceTask?.().catch(() => false) ?? false;
10591
12007
  const script = join17(dir, "kiosko-upgrade.cmd");
10592
12008
  const log = win324.join(this.d.home, "kiosko.log");
10593
- writeFileSync12(script, windowsUpgradeScript({ exe: this.file, args: installerArgs(!!info.perUser, join17(dir, "install.log")), dir: info.dir, service, port: this.d.port, log }));
12009
+ writeFileSync12(script, windowsUpgradeScript({ exe: this.file, args: installerArgs(!!info.perUser, join17(dir, "install.log")), dir: info.dir, service: service2, port: this.d.port, log }));
10594
12010
  this.d.mark?.({ from: this.d.current, to: version, at: this.now, how: "installer", lines: this.lines.slice(-30) });
10595
12011
  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)"}`);
10596
12012
  this.set({ state: "restarting", restart: "installer" });
@@ -10633,7 +12049,7 @@ function readMarker(home, version, now = Date.now()) {
10633
12049
  if (!existsSync15(f)) return null;
10634
12050
  let m = {};
10635
12051
  try {
10636
- m = JSON.parse(readFileSync10(f, "utf8"));
12052
+ m = JSON.parse(readFileSync11(f, "utf8"));
10637
12053
  } catch {
10638
12054
  }
10639
12055
  rmSync4(f, { force: true });
@@ -10656,7 +12072,10 @@ var MIME = {
10656
12072
  ".woff2": "font/woff2",
10657
12073
  ".ico": "image/x-icon"
10658
12074
  };
10659
- var realDiscover = async (url2, tokenFile) => ({ trcc: await discoverTrcc(url2, tokenFile), usb: await discoverUsb() });
12075
+ var realDiscover = async (url2, tokenFile) => {
12076
+ const [trcc, usb, remote] = await Promise.all([discoverTrcc(url2, tokenFile), discoverUsb(), discoverRemote()]);
12077
+ return { trcc, usb, remote };
12078
+ };
10660
12079
  function webRoot() {
10661
12080
  const bundled = join18(import.meta.dirname, "web");
10662
12081
  if (existsSync16(join18(bundled, "index.html"))) return bundled;
@@ -10710,7 +12129,7 @@ function startServer(o) {
10710
12129
  const install = o.install ?? currentInstall();
10711
12130
  const registryUrl = o.selfUpdate?.registry ?? npmRegistry();
10712
12131
  const blocker = updateBlocker(install, { demo: runtime.demoMode });
10713
- const instance = randomBytes(8).toString("hex");
12132
+ const instance = randomBytes4(8).toString("hex");
10714
12133
  const how = o.selfUpdate?.restartHow ?? restartHow(install, { tty: !!process.stdout.isTTY, pid: process.pid });
10715
12134
  const probeHost = o.host === "0.0.0.0" || o.host === "::" ? "127.0.0.1" : o.host.includes(":") ? `[${o.host}]` : o.host;
10716
12135
  const handover = {
@@ -10853,6 +12272,18 @@ data: ${JSON.stringify(data)}
10853
12272
  platform: process.platform
10854
12273
  };
10855
12274
  }
12275
+ const remote = remoteApi({
12276
+ runtime,
12277
+ json,
12278
+ body,
12279
+ commit: (cfg) => {
12280
+ const c = normalize(cfg);
12281
+ saveConfig(c, o.configPath);
12282
+ rev++;
12283
+ runtime.apply(c);
12284
+ send("config", { rev, by: null });
12285
+ }
12286
+ });
10856
12287
  function findScreen(cfg, id) {
10857
12288
  return cfg.screens.find((s) => s.id === id);
10858
12289
  }
@@ -10863,9 +12294,9 @@ data: ${JSON.stringify(data)}
10863
12294
  if (p === "/api/state" && m === "GET") return json(res, 200, state(req));
10864
12295
  if (p === "/api/config" && m === "PUT") {
10865
12296
  const b = await body(req);
10866
- const raw = b && typeof b === "object" && "config" in b ? b.config : b;
12297
+ const raw2 = b && typeof b === "object" && "config" in b ? b.config : b;
10867
12298
  if (typeof b?.baseRev === "number" && b.baseRev !== rev) return json(res, 409, { error: "the configuration changed elsewhere", code: "conflict", rev, config: runtime.config });
10868
- const cfg = normalize(raw);
12299
+ const cfg = normalize(raw2);
10869
12300
  saveConfig(cfg, o.configPath);
10870
12301
  rev++;
10871
12302
  runtime.apply(cfg);
@@ -10979,6 +12410,7 @@ data: ${JSON.stringify({ version: o.version })}
10979
12410
  runtime.refreshWidget(decodeURIComponent(mm[1]));
10980
12411
  return json(res, 200, { ok: true });
10981
12412
  }
12413
+ if ((p.startsWith("/api/remote/") || /^\/api\/screens\/[^/]+\/remote\//.test(p)) && await remote(req, res, p, m)) return;
10982
12414
  if (p === "/api/devices/discover" && m === "GET") {
10983
12415
  const url0 = url2.searchParams.get("url") ?? "http://127.0.0.1:8099";
10984
12416
  return json(res, 200, await (o.discover ?? realDiscover)(url0, url2.searchParams.get("tokenFile") ?? void 0));
@@ -11016,9 +12448,9 @@ data: ${JSON.stringify({ version: o.version })}
11016
12448
  }
11017
12449
  if (p === "/api/plugins/install" && m === "POST") {
11018
12450
  const b = await body(req);
11019
- const name = String(b.name ?? "").trim();
12451
+ const name2 = String(b.name ?? "").trim();
11020
12452
  try {
11021
- const r = await installPlugin(name, { registry: runtime.registry, runtime });
12453
+ const r = await installPlugin(name2, { registry: runtime.registry, runtime });
11022
12454
  if (r.restart) restartNeeded = true;
11023
12455
  rev++;
11024
12456
  send("config", { rev, by: null });
@@ -11154,7 +12586,7 @@ data: ${JSON.stringify({ version: o.version })}
11154
12586
  }
11155
12587
  const ext = extname(file);
11156
12588
  res.writeHead(200, { "content-type": MIME[ext] ?? "application/octet-stream", "cache-control": ext === ".html" ? "no-cache" : "max-age=300" });
11157
- res.end(readFileSync11(file));
12589
+ res.end(readFileSync12(file));
11158
12590
  }
11159
12591
  const server = createServer((req, res) => {
11160
12592
  const host = req.headers.host ?? "";
@@ -11195,7 +12627,7 @@ data: ${JSON.stringify({ version: o.version })}
11195
12627
  import { existsSync as existsSync17, readdirSync as readdirSync5 } from "node:fs";
11196
12628
  import { homedir as homedir5 } from "node:os";
11197
12629
  import { join as join19 } from "node:path";
11198
- var ROTATIONS = [0, 90, 180, 270];
12630
+ var ROTATIONS2 = [0, 90, 180, 270];
11199
12631
  function starterPanels(found, trccUrl = "http://127.0.0.1:8099") {
11200
12632
  const out = [];
11201
12633
  const named = (width, height) => {
@@ -11207,7 +12639,7 @@ function starterPanels(found, trccUrl = "http://127.0.0.1:8099") {
11207
12639
  for (const u of found.usb) {
11208
12640
  const width = u.width || 1920;
11209
12641
  const height = u.height || 462;
11210
- out.push({ name: named(width, height), width, height, rotate: ROTATIONS.includes(u.rotate ?? 0) ? u.rotate ?? 0 : 0, device: { driver: "usb", ...u.serial ? { serial: u.serial } : {} } });
12642
+ 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 } : {} } });
11211
12643
  }
11212
12644
  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 } });
11213
12645
  return out;
@@ -11226,8 +12658,8 @@ var CATS_PAGE = { en: "Cats room", es: "Sala de los gatos", de: "Katzenzimmer",
11226
12658
  function starterConfig(registry2, o = {}) {
11227
12659
  const locale = o.locale ?? "en";
11228
12660
  const has = (t2) => !!registry2.widget(t2);
11229
- const one = (name, width, height, device, rotate = 0) => {
11230
- const screen = newScreen(name, width, height, device);
12661
+ const one = (name2, width, height, device, rotate = 0) => {
12662
+ const screen = newScreen(name2, width, height, device);
11231
12663
  screen.rotate = rotate;
11232
12664
  screen.pages = [starterPage(has, { width, height, locale, agents: o.agents ?? true, weather: o.weather ?? true })];
11233
12665
  if ((o.agents ?? true) && has("cats/room")) {
@@ -11244,7 +12676,7 @@ function starterConfig(registry2, o = {}) {
11244
12676
  }
11245
12677
 
11246
12678
  // packages/server/src/cli.ts
11247
- var VERSION = "0.2.9";
12679
+ var VERSION = "0.2.11";
11248
12680
  var USAGE2 = `Kiosko ${VERSION}: a widget mosaic for USB LCD panels
11249
12681
 
11250
12682
  kiosko start [--port 7420] [--host 127.0.0.1] [--config file] [--open] [--demo]
@@ -11258,6 +12690,9 @@ var USAGE2 = `Kiosko ${VERSION}: a widget mosaic for USB LCD panels
11258
12690
  kiosko usb [list] the LY panels libusb sees, with their serial numbers
11259
12691
  kiosko usb test [--serial S] [--seconds 10] [--size 1920x462] [--rotate 180]
11260
12692
  drive a panel with the sample screen (experimental)
12693
+ kiosko remote [list] Kiosko remote screens on the network (mDNS)
12694
+ kiosko remote pair <uid|host> [--screen id] pair one (type the code it shows)
12695
+ kiosko remote ota|logs|unpair <screen> [firmware.bin]
11261
12696
  kiosko gallery [--out gallery] [--locale en | --all-languages] [--theme midnight] [--pages config.json]
11262
12697
  kiosko plugins [list|add <id>\u2026|link <folder>\u2026|remove <id>\u2026]
11263
12698
  kiosko service install|uninstall|print (start with your session)
@@ -11266,9 +12701,9 @@ var USAGE2 = `Kiosko ${VERSION}: a widget mosaic for USB LCD panels
11266
12701
  var argv = process.argv.slice(2);
11267
12702
  var FLAG_COMMANDS = /* @__PURE__ */ new Set(["--help", "-h", "--version", "-v"]);
11268
12703
  var cmd = argv.includes("--help") || argv.includes("-h") ? "help" : argv[0] && (!argv[0].startsWith("-") || FLAG_COMMANDS.has(argv[0])) ? argv[0] : "start";
11269
- var flag = (name) => argv.includes(name);
11270
- var opt = (name) => {
11271
- const i = argv.indexOf(name);
12704
+ var flag = (name2) => argv.includes(name2);
12705
+ var opt = (name2) => {
12706
+ const i = argv.indexOf(name2);
11272
12707
  return i >= 0 ? argv[i + 1] : void 0;
11273
12708
  };
11274
12709
  var SCREEN_THREAD = ["./screen-thread.js", "./screen-thread.ts"].map((f) => new URL(f, import.meta.url)).find((u) => existsSync18(u));
@@ -11282,8 +12717,8 @@ async function registry() {
11282
12717
  if (r.plugin(o.id)) continue;
11283
12718
  try {
11284
12719
  const url2 = import.meta.resolve(o.npm);
11285
- const mod = await import(url2);
11286
- if (mod.default) r.add(mod.default, `npm:${o.npm}`, url2);
12720
+ const mod2 = await import(url2);
12721
+ if (mod2.default) r.add(mod2.default, `npm:${o.npm}`, url2);
11287
12722
  } catch {
11288
12723
  }
11289
12724
  }
@@ -11383,12 +12818,12 @@ async function main() {
11383
12818
  }
11384
12819
  const reg = await registry();
11385
12820
  const modePath = join20(dirname9(from), "modo");
11386
- const modeOverride = existsSync18(modePath) ? readFileSync12(modePath, "utf8") : null;
11387
- const { config: imported, notes } = importAimonitor(JSON.parse(readFileSync12(from, "utf8")), reg, modeOverride, { withSecrets: flag("--with-secrets") });
12821
+ const modeOverride = existsSync18(modePath) ? readFileSync13(modePath, "utf8") : null;
12822
+ const { config: imported, notes } = importAimonitor(JSON.parse(readFileSync13(from, "utf8")), reg, modeOverride, { withSecrets: flag("--with-secrets") });
11388
12823
  if (modeOverride) notes.push(`mode from ${modePath}: ${modeOverride.trim()}`);
11389
12824
  for (const n of notes) console.log(`- ${n}`);
11390
12825
  if (flag("--write")) {
11391
- if (existsSync18(path)) writeFileSync13(`${path}.bak`, readFileSync12(path));
12826
+ if (existsSync18(path)) writeFileSync13(`${path}.bak`, readFileSync13(path));
11392
12827
  saveConfig(imported, path);
11393
12828
  console.log(`written ${path}${existsSync18(`${path}.bak`) ? ` (previous one in ${path}.bak)` : ""}`);
11394
12829
  } else {
@@ -11441,12 +12876,24 @@ async function main() {
11441
12876
  if (!usb.ok) console.log(`usb not available: ${usb.error}`);
11442
12877
  else if (!usb.panels.length) console.log("usb no LY panel (0416:5408/5409) plugged in");
11443
12878
  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}` : ""}`);
12879
+ const remote = await discoverRemote(2e3);
12880
+ if (!remote.length) console.log("remote no Kiosko remote screen answered on this network (mDNS)");
12881
+ for (const r of remote) {
12882
+ const used = cfg.screens.find((s) => s.device.driver === "remote" && s.device.uid === r.uid);
12883
+ 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}"` : ""}`);
12884
+ }
12885
+ 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`);
11444
12886
  for (const s of cfg.screens) {
11445
12887
  const missing = s.pages.flatMap((p) => p.tiles.flatMap((t2) => t2.widgets.filter((w) => !reg.widget(w.type)).map((w) => w.type)));
11446
12888
  console.log(`screen ${s.name} ${s.width}\xD7${s.height} ${s.device.driver}${missing.length ? ` \u2717 unknown widgets: ${[...new Set(missing)].join(", ")}` : ""}`);
11447
12889
  }
11448
12890
  return;
11449
12891
  }
12892
+ case "remote": {
12893
+ process.env.KIOSKO_QUIET ??= "1";
12894
+ process.exitCode = await remoteCommand(argv.slice(1), { configPath: path, port: Number(opt("--port")) || 7420, registry });
12895
+ return;
12896
+ }
11450
12897
  case "service": {
11451
12898
  const pass = ["--port", "--host", "--config"].flatMap((f) => opt(f) ? [f, opt(f)] : []);
11452
12899
  const env = process.env.KIOSKO_HOME ? { KIOSKO_HOME: process.env.KIOSKO_HOME } : {};
@@ -11460,7 +12907,7 @@ async function main() {
11460
12907
  const reg = await registry();
11461
12908
  const out = opt("--out") ?? "gallery";
11462
12909
  const sample = opt("--pages");
11463
- const n = buildGallery(reg, { out, locale: opt("--locale") ?? "en", languages: flag("--all-languages"), theme: opt("--theme") ?? "midnight", ...sample ? { pages: JSON.parse(readFileSync12(sample, "utf8")) } : {} });
12910
+ const n = buildGallery(reg, { out, locale: opt("--locale") ?? "en", languages: flag("--all-languages"), theme: opt("--theme") ?? "midnight", ...sample ? { pages: JSON.parse(readFileSync13(sample, "utf8")) } : {} });
11464
12911
  console.log(`${n} widgets \u2192 ${out}/index.html`);
11465
12912
  return;
11466
12913
  }