kiosko 0.2.11 → 0.2.12

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/screen-thread.js CHANGED
@@ -17,12 +17,12 @@ function dayKey(at) {
17
17
  }
18
18
  function scheduleOn(w, at) {
19
19
  const day = new Date(at).getDay();
20
- const own = w.byDay?.[String(day)] ?? {};
21
- const start = own.start || w.start;
22
- const end = own.end || w.end;
20
+ const own2 = w.byDay?.[String(day)] ?? {};
21
+ const start = own2.start || w.start;
22
+ const end = own2.end || w.end;
23
23
  const holiday = (w.holidays ?? []).includes(dayKey(at));
24
24
  const working = w.days.includes(day) && !holiday;
25
- return { working, holiday, start, end, startMin: minutesOf(start), endMin: minutesOf(end), hours: working ? own.hours ?? w.hours ?? 0 : 0 };
25
+ return { working, holiday, start, end, startMin: minutesOf(start), endMin: minutesOf(end), hours: working ? own2.hours ?? w.hours ?? 0 : 0 };
26
26
  }
27
27
  function isWorkingAt(w, at) {
28
28
  const s = scheduleOn(w, at);
@@ -45,6 +45,25 @@ function toPx(r, grid, width, height) {
45
45
  return { x: x0, y: y0, w: Math.max(1, x1 - x0), h: Math.max(1, y1 - y0) };
46
46
  }
47
47
 
48
+ // packages/core/src/config/profiles.ts
49
+ var PROFILE_SEP = "#";
50
+ var PROFILE_ID_PATTERN = "^[a-z0-9][a-z0-9_-]{0,39}$";
51
+ var PROFILE_ID_RE = new RegExp(PROFILE_ID_PATTERN);
52
+ var acceptsProfiles = (def) => def?.profiles === true;
53
+ function sourceKey(type, profile) {
54
+ return profile ? `${type}${PROFILE_SEP}${profile}` : type;
55
+ }
56
+ function profilesOf(cfg, type) {
57
+ return cfg.sourceProfiles?.[type] ?? {};
58
+ }
59
+ function resolveSourceKey(cfg, type, profile, def) {
60
+ if (!profile || !acceptsProfiles(def) || !Object.hasOwn(profilesOf(cfg, type), profile)) return type;
61
+ return sourceKey(type, profile);
62
+ }
63
+ function sourceKeysOf(cfg, types, profile, source) {
64
+ return (types ?? []).map((t2) => [t2, resolveSourceKey(cfg, t2, profile, source(t2))]);
65
+ }
66
+
48
67
  // packages/core/src/config/model.ts
49
68
  var CONFIG_VERSION = 1;
50
69
  function deviceRotates(d) {
@@ -116,10 +135,13 @@ import { homedir as homedir2, platform } from "node:os";
116
135
 
117
136
  // packages/sdk/src/plugin.ts
118
137
  var PAD_KEYS = ["up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select"];
119
- var SDK_VERSION = "0.2.11";
138
+ var SDK_VERSION = "0.2.12";
120
139
  function defineWidget(w) {
121
140
  return w;
122
141
  }
142
+ function defineSource(s) {
143
+ return s;
144
+ }
123
145
  function definePlugin(p) {
124
146
  return p;
125
147
  }
@@ -707,6 +729,126 @@ function satisfies(version, range) {
707
729
  });
708
730
  }
709
731
 
732
+ // packages/sdk/src/http.ts
733
+ var HttpError = class extends Error {
734
+ status;
735
+ url;
736
+ /** When the server says to come back (rate limits), epoch ms. */
737
+ retryAt;
738
+ constructor(message, o) {
739
+ super(message);
740
+ this.name = "HttpError";
741
+ this.status = o.status;
742
+ this.url = o.url;
743
+ if (o.retryAt !== void 0) this.retryAt = o.retryAt;
744
+ }
745
+ };
746
+ function retryAtOf(headers, now) {
747
+ const ra = headers.get("retry-after");
748
+ if (ra) {
749
+ const s = Number(ra);
750
+ if (Number.isFinite(s)) return now + Math.max(0, s) * 1e3;
751
+ const at = Date.parse(ra);
752
+ if (Number.isFinite(at)) return at;
753
+ }
754
+ const reset = Number(headers.get("x-ratelimit-reset"));
755
+ if (headers.get("x-ratelimit-remaining") === "0" && Number.isFinite(reset) && reset > 0) return reset * 1e3;
756
+ return void 0;
757
+ }
758
+ var hostOf = (url) => {
759
+ try {
760
+ return new URL(url).host;
761
+ } catch {
762
+ return url;
763
+ }
764
+ };
765
+ async function limitedText(res, max, url) {
766
+ const tooBig = () => new HttpError(`response larger than ${max} bytes from ${hostOf(url)}`, { status: res.status, url });
767
+ const declared = Number(res.headers.get("content-length"));
768
+ if (Number.isFinite(declared) && declared > max) {
769
+ await res.body?.cancel().catch(() => void 0);
770
+ throw tooBig();
771
+ }
772
+ if (!res.body) return "";
773
+ const reader = res.body.getReader();
774
+ const chunks = [];
775
+ let size = 0;
776
+ for (; ; ) {
777
+ const { done: done2, value } = await reader.read();
778
+ if (done2) break;
779
+ size += value.byteLength;
780
+ if (size > max) {
781
+ await reader.cancel().catch(() => void 0);
782
+ throw tooBig();
783
+ }
784
+ chunks.push(value);
785
+ }
786
+ const all = new Uint8Array(size);
787
+ let at = 0;
788
+ for (const c of chunks) {
789
+ all.set(c, at);
790
+ at += c.byteLength;
791
+ }
792
+ return new TextDecoder().decode(all);
793
+ }
794
+ function createHttp(o = {}) {
795
+ const doFetch = o.fetch ?? fetch;
796
+ const now = o.now ?? Date.now;
797
+ const agent = `${o.agent ? `${o.agent} ` : ""}Kiosko (+https://kioskolcd.dev)`;
798
+ const cache = /* @__PURE__ */ new Map();
799
+ const rest = /* @__PURE__ */ new Map();
800
+ const max = o.maxCached ?? 200;
801
+ async function request(url, req = {}) {
802
+ const host = hostOf(url);
803
+ const until = rest.get(host);
804
+ if (until !== void 0) {
805
+ if (until > now()) throw new HttpError(`${host} asked to wait until ${new Date(until).toISOString()}`, { status: 429, url, retryAt: until });
806
+ rest.delete(host);
807
+ }
808
+ const method = req.method ?? "GET";
809
+ const cacheable = method === "GET" && !req.noCache;
810
+ const hit = cacheable ? cache.get(url) : void 0;
811
+ const headers = { "User-Agent": agent, ...req.headers };
812
+ if (hit?.etag) headers["If-None-Match"] = hit.etag;
813
+ if (hit?.modified) headers["If-Modified-Since"] = hit.modified;
814
+ const res = await doFetch(url, { method, headers, ...req.body !== void 0 ? { body: req.body } : {}, ...req.signal ? { signal: req.signal } : {} });
815
+ if (res.status === 304 && hit) return { data: hit.body, status: 304, fresh: false, headers: res.headers };
816
+ const retryAt = retryAtOf(res.headers, now());
817
+ if (res.status === 429 || res.status === 503 || res.status === 403 && retryAt !== void 0) {
818
+ const at = retryAt ?? now() + 6e4;
819
+ rest.set(host, at);
820
+ throw new HttpError(`HTTP ${res.status} from ${host}: rate-limited until ${new Date(at).toISOString()}`, { status: res.status, url, retryAt: at });
821
+ }
822
+ if (!res.ok) throw new HttpError(`HTTP ${res.status} from ${host}`, { status: res.status, url });
823
+ const body = req.maxBytes === void 0 ? await res.text() : await limitedText(res, req.maxBytes, url);
824
+ if (cacheable) {
825
+ const etag = res.headers.get("etag") ?? void 0;
826
+ const modified = res.headers.get("last-modified") ?? void 0;
827
+ if (etag || modified) {
828
+ cache.delete(url);
829
+ cache.set(url, { ...etag ? { etag } : {}, ...modified ? { modified } : {}, body });
830
+ while (cache.size > max) cache.delete(cache.keys().next().value);
831
+ }
832
+ }
833
+ return { data: body, status: res.status, fresh: true, headers: res.headers };
834
+ }
835
+ return {
836
+ text: request,
837
+ async json(url, req) {
838
+ const r = await request(url, { ...req, headers: { Accept: "application/json", ...req?.headers } });
839
+ try {
840
+ return { ...r, data: JSON.parse(r.data) };
841
+ } catch {
842
+ throw new HttpError(`not JSON from ${hostOf(url)}`, { status: r.status, url });
843
+ }
844
+ },
845
+ resting(url) {
846
+ const at = rest.get(hostOf(url));
847
+ return at !== void 0 && at > now() ? at : void 0;
848
+ }
849
+ };
850
+ }
851
+
710
852
  // packages/core/src/paths.ts
711
853
  import { join as join2 } from "node:path";
712
854
  function kioskoHome() {
@@ -801,14 +943,14 @@ function sourceCommonFields(def) {
801
943
  help: { en: "A reading that takes longer is cancelled and counts as failed; the next try comes sooner.", es: "Una lectura que tarde m\xE1s se cancela y cuenta como fallida; el siguiente intento llega antes.", de: "Ein Lesevorgang, der l\xE4nger dauert, wird abgebrochen und z\xE4hlt als fehlgeschlagen; der n\xE4chste Versuch kommt fr\xFCher.", "zh-Hant": "\u8D85\u904E\u6B64\u6642\u9593\u7684\u8B80\u53D6\u6703\u88AB\u53D6\u6D88\u4E26\u8996\u70BA\u5931\u6557\uFF1B\u4E0B\u6B21\u6703\u63D0\u65E9\u91CD\u8A66\u3002", "zh-Hans": "\u8D85\u8FC7\u6B64\u65F6\u95F4\u7684\u8BFB\u53D6\u4F1A\u88AB\u53D6\u6D88\u5E76\u89C6\u4E3A\u5931\u8D25\uFF1B\u4E0B\u6B21\u4F1A\u63D0\u524D\u91CD\u8BD5\u3002" }
802
944
  })
803
945
  });
804
- const own = def.options?.props ?? {};
805
- return Object.fromEntries(Object.entries(fields).filter(([k]) => !(k in own)));
946
+ const own2 = def.options?.props ?? {};
947
+ return Object.fromEntries(Object.entries(fields).filter(([k]) => !(k in own2)));
806
948
  }
807
949
  var merged = /* @__PURE__ */ new WeakMap();
808
950
  function sourceOptionsField(def) {
809
951
  if (!merged.has(def)) {
810
- const own = def.options?.props ?? {};
811
- const props = { ...own, ...sourceCommonFields(def) };
952
+ const own2 = def.options?.props ?? {};
953
+ const props = { ...own2, ...sourceCommonFields(def) };
812
954
  const o = def.options;
813
955
  merged.set(def, Object.keys(props).length ? t.object(props, { ...o?.label ? { label: o.label } : {}, ...o?.help ? { help: o.help } : {} }) : null);
814
956
  }
@@ -1157,8 +1299,8 @@ var CYCLE = [
1157
1299
  ];
1158
1300
  function pixelShift(now, o) {
1159
1301
  if (!o.enabled) return { x: 0, y: 0 };
1160
- const step = CYCLE[Math.floor(now / o.periodMs) % CYCLE.length];
1161
- return { x: Math.round(step[0] * o.amplitude), y: Math.round(step[1] * o.amplitude) };
1302
+ const step2 = CYCLE[Math.floor(now / o.periodMs) % CYCLE.length];
1303
+ return { x: Math.round(step2[0] * o.amplitude), y: Math.round(step2[1] * o.amplitude) };
1162
1304
  }
1163
1305
 
1164
1306
  // packages/lcd-canvas-kit/src/weathericons.ts
@@ -1512,14 +1654,14 @@ var OTHER_SCRIPTS = [
1512
1654
  { script: "Armn", probe: "\u0531", families: ["Noto Sans Armenian", "Sylfaen", "DejaVu Sans"] },
1513
1655
  { script: "Ethi", probe: "\u12A0", families: ["Noto Sans Ethiopic", "Ebrima", "Kefa"] }
1514
1656
  ];
1515
- function scriptOrder(own) {
1657
+ function scriptOrder(own2) {
1516
1658
  const rest = ["Hans", "Hant", "Jpan", "Kore"];
1517
- if (!own) return rest;
1518
- const first = own === "Hant-HK" ? ["Hant-HK", "Hant"] : [own];
1659
+ if (!own2) return rest;
1660
+ const first = own2 === "Hant-HK" ? ["Hant-HK", "Hant"] : [own2];
1519
1661
  return [...first, ...rest.filter((s) => !first.includes(s))];
1520
1662
  }
1521
- function cjkFamiliesFor(locale, available2, own = []) {
1522
- const out = [...own];
1663
+ function cjkFamiliesFor(locale, available2, own2 = []) {
1664
+ const out = [...own2];
1523
1665
  for (const s of scriptOrder(hanScript(locale))) {
1524
1666
  const found = CJK_FAMILIES[s].find((f) => !out.includes(f) && available2(f));
1525
1667
  if (found) out.push(found);
@@ -1712,7 +1854,7 @@ function resolve(input, inst) {
1712
1854
  if (!def) return null;
1713
1855
  let options = def.options ? validate(def.options, inst.options).value : {};
1714
1856
  let data = input.dataOf(inst);
1715
- let sources = input.sourcesOf(def.sources);
1857
+ let sources = input.sourcesOf(def.sources, inst.profile);
1716
1858
  if (input.demo && def.demo) {
1717
1859
  const needData = data === void 0;
1718
1860
  const needSources = (def.sources ?? []).some((s) => sources[s] === void 0);
@@ -1805,8 +1947,8 @@ function paintTile(g, input, tile, rect, out, nextAt, idles, animatable) {
1805
1947
  }
1806
1948
  const state = stateCtx(r, now, working, input.cfg);
1807
1949
  idles.push(safe(() => r.def.idle?.(state) ?? false, false));
1808
- const step = redrawStep(r.def, state);
1809
- if (step) nextAt.v = Math.min(nextAt.v, (Math.floor(now / step) + 1) * step);
1950
+ const step2 = redrawStep(r.def, state);
1951
+ if (step2) nextAt.v = Math.min(nextAt.v, (Math.floor(now / step2) + 1) * step2);
1810
1952
  const animation = r.def.animation;
1811
1953
  if (animation && !input.preview) {
1812
1954
  animatable.push({
@@ -1830,7 +1972,7 @@ function paintTile(g, input, tile, rect, out, nextAt, idles, animatable) {
1830
1972
  return;
1831
1973
  }
1832
1974
  const cfg = input.cfg;
1833
- const key = JSON.stringify([r.inst.id, r.inst.type, r.inst.options, r.inst.title ?? "", zoomOf(r.inst), input.screen.textScale ?? 1, legibleCjkPx(input.screen), chrome, rect, theme.id, step ? Math.floor(now / step) : 0, cfg.locale, cfg.timeFormat, cfg.workday, cfg.location ?? null, working]);
1975
+ const key = JSON.stringify([r.inst.id, r.inst.type, r.inst.options, r.inst.title ?? "", zoomOf(r.inst), input.screen.textScale ?? 1, legibleCjkPx(input.screen), chrome, rect, theme.id, step2 ? Math.floor(now / step2) : 0, cfg.locale, cfg.timeFormat, cfg.workday, cfg.location ?? null, working]);
1834
1976
  const refs = [r.data, ...(r.def.sources ?? []).map((s) => r.sources[s])];
1835
1977
  const hit = input.cache.get(tile.id);
1836
1978
  if (hit && hit.key === key && hit.refs.length === refs.length && hit.refs.every((x, i) => x === refs[i])) {
@@ -2045,12 +2187,28 @@ var AnimationScheduler = class {
2045
2187
  // packages/core/src/alerts.ts
2046
2188
  var DEFAULT_SNOOZE_MS = 10 * 6e4;
2047
2189
 
2190
+ // packages/core/src/context.ts
2191
+ function inRotation(p) {
2192
+ return !p.showWhen?.length || p.inRotation === true;
2193
+ }
2194
+ function choosePage(screen, now, working, pinned, context) {
2195
+ const eligible = screen.pages.filter((p) => whenMatches(p.when, working));
2196
+ const on = (id) => id ? eligible.find((p) => p.id === id && p.enabled !== false) : void 0;
2197
+ const fixed = on(pinned) ?? on(context);
2198
+ if (fixed) return fixed;
2199
+ const rotation = eligible.filter(inRotation);
2200
+ return pickPage(rotation.some((p) => p.enabled !== false) ? rotation : eligible, now);
2201
+ }
2202
+
2048
2203
  // packages/core/src/data.ts
2049
2204
  var DEFAULT_FETCH_MS = 10 * 6e4;
2050
2205
 
2051
2206
  // packages/core/src/remote/link.ts
2052
2207
  var MAX_MSG = 1 << 20;
2053
2208
 
2209
+ // packages/core/src/remote/firmware.ts
2210
+ var MAX_IMAGE = 4 * 1024 * 1024;
2211
+
2054
2212
  // packages/core/src/devices.ts
2055
2213
  function encodeFor(device, jpegQuality) {
2056
2214
  if (device.driver === "file") return device.format ?? "jpeg";
@@ -2071,10 +2229,10 @@ var LEVEL_COLORS = {
2071
2229
  function alertStepMs(maxFps) {
2072
2230
  return Math.max(500, Math.ceil(1e3 / Math.max(1, maxFps || 1)));
2073
2231
  }
2074
- function alertIntensity(level, elapsed, step) {
2075
- const k = Math.floor(Math.max(0, elapsed) / step);
2232
+ function alertIntensity(level, elapsed, step2) {
2233
+ const k = Math.floor(Math.max(0, elapsed) / step2);
2076
2234
  if (level !== "info" && elapsed < FLASH_MS) return k % 2 === 0 ? 1 : 0.15;
2077
- const t2 = k * step % PULSE_MS / PULSE_MS;
2235
+ const t2 = k * step2 % PULSE_MS / PULSE_MS;
2078
2236
  const depth = level === "info" ? 0.3 : 0.45;
2079
2237
  return Math.round((1 - depth * (0.5 - 0.5 * Math.cos(2 * Math.PI * t2))) * 100) / 100;
2080
2238
  }
@@ -2425,25 +2583,25 @@ function paintCard(g, w, h, look) {
2425
2583
  return { k: k2, body, chip, hint, title, open: open2, cmd, cmdW, orW, urlW, oneLine, hints, height, fits, lineH };
2426
2584
  };
2427
2585
  let k = Math.round(shape === "wide" ? h * 0.17 : shape === "tall" ? w * 0.12 : Math.min(w * 0.085, h * 0.11));
2428
- let L = layout(k);
2429
- while (k > 12 && (L.height > bh || !L.fits)) L = layout(--k);
2430
- const my = shape === "wide" ? Math.round((h - mark) / 2) : Math.max(pad, Math.round((h - mark - gap - L.height) / 2));
2586
+ let L3 = layout(k);
2587
+ while (k > 12 && (L3.height > bh || !L3.fits)) L3 = layout(--k);
2588
+ const my = shape === "wide" ? Math.round((h - mark) / 2) : Math.max(pad, Math.round((h - mark - gap - L3.height) / 2));
2431
2589
  paintBackground(g, w, h, theme, mx + mark / 2, my + mark / 2, 1);
2432
2590
  paintMark(g, mx, my, mark, theme);
2433
- let y = shape === "wide" ? pad + Math.max(0, Math.round((bh - L.height) / 2)) : my + mark + gap;
2591
+ let y = shape === "wide" ? pad + Math.max(0, Math.round((bh - L3.height) / 2)) : my + mark + gap;
2434
2592
  const ax = center ? w / 2 : bx;
2435
2593
  const align = center ? "center" : "left";
2436
- for (const line of L.title) {
2437
- drawTracked(g, line, ax, y + L.k * 0.95, { size: L.k, family: bold, color: theme.colors.ink, align });
2438
- y += L.lineH(L.k);
2594
+ for (const line of L3.title) {
2595
+ drawTracked(g, line, ax, y + L3.k * 0.95, { size: L3.k, family: bold, color: theme.colors.ink, align });
2596
+ y += L3.lineH(L3.k);
2439
2597
  }
2440
- y += L.k * 0.25;
2441
- for (const line of L.open) {
2442
- drawTracked(g, line, ax, y + L.body * 0.95, { size: L.body, family: sans, color: theme.colors.inkDim, align });
2443
- y += L.lineH(L.body);
2598
+ y += L3.k * 0.25;
2599
+ for (const line of L3.open) {
2600
+ drawTracked(g, line, ax, y + L3.body * 0.95, { size: L3.body, family: sans, color: theme.colors.inkDim, align });
2601
+ y += L3.lineH(L3.body);
2444
2602
  }
2445
- y += L.body * 0.35;
2446
- const chipH = Math.round(L.chip * 1.6);
2603
+ y += L3.body * 0.35;
2604
+ const chipH = Math.round(L3.chip * 1.6);
2447
2605
  const drawChip = (x, text2, cw) => {
2448
2606
  g.fillStyle = theme.colors.surface;
2449
2607
  g.strokeStyle = theme.colors.surfaceEdge;
@@ -2452,30 +2610,30 @@ function paintCard(g, w, h, look) {
2452
2610
  g.roundRect(x, y, cw, chipH, chipH / 3);
2453
2611
  g.fill();
2454
2612
  g.stroke();
2455
- drawTracked(g, text2, x + cw / 2, y + chipH / 2 + L.chip * 0.36, { size: L.chip, family: mono, color: theme.colors.ink, align: "center" });
2613
+ drawTracked(g, text2, x + cw / 2, y + chipH / 2 + L3.chip * 0.36, { size: L3.chip, family: mono, color: theme.colors.ink, align: "center" });
2456
2614
  };
2457
- const drawUrl = (x) => drawTracked(g, look.url, x, y + chipH / 2 + L.chip * 0.36, { size: L.chip, family: mono, color: theme.colors.accent });
2458
- if (L.oneLine) {
2459
- const total = L.cmdW + L.body * 0.6 + L.orW + L.body * 0.6 + L.urlW;
2615
+ const drawUrl = (x) => drawTracked(g, look.url, x, y + chipH / 2 + L3.chip * 0.36, { size: L3.chip, family: mono, color: theme.colors.accent });
2616
+ if (L3.oneLine) {
2617
+ const total = L3.cmdW + L3.body * 0.6 + L3.orW + L3.body * 0.6 + L3.urlW;
2460
2618
  let x = center ? Math.round((w - total) / 2) : bx;
2461
- drawChip(x, L.cmd, L.cmdW);
2462
- x += L.cmdW + L.body * 0.6;
2463
- drawTracked(g, tx.or, x, y + chipH / 2 + L.body * 0.36, { size: L.body, family: sans, color: theme.colors.inkDim });
2464
- x += L.orW + L.body * 0.6;
2619
+ drawChip(x, L3.cmd, L3.cmdW);
2620
+ x += L3.cmdW + L3.body * 0.6;
2621
+ drawTracked(g, tx.or, x, y + chipH / 2 + L3.body * 0.36, { size: L3.body, family: sans, color: theme.colors.inkDim });
2622
+ x += L3.orW + L3.body * 0.6;
2465
2623
  drawUrl(x);
2466
- y += L.chip * 1.9;
2624
+ y += L3.chip * 1.9;
2467
2625
  } else {
2468
- drawChip(center ? Math.round((w - L.cmdW) / 2) : bx, L.cmd, L.cmdW);
2469
- y += L.chip * 1.9;
2470
- drawTracked(g, tx.or, ax, y + L.body * 0.95, { size: L.body, family: sans, color: theme.colors.inkDim, align });
2471
- y += L.lineH(L.body);
2472
- drawUrl(center ? Math.round((w - L.urlW) / 2) : bx);
2473
- y += L.chip * 1.9;
2626
+ drawChip(center ? Math.round((w - L3.cmdW) / 2) : bx, L3.cmd, L3.cmdW);
2627
+ y += L3.chip * 1.9;
2628
+ drawTracked(g, tx.or, ax, y + L3.body * 0.95, { size: L3.body, family: sans, color: theme.colors.inkDim, align });
2629
+ y += L3.lineH(L3.body);
2630
+ drawUrl(center ? Math.round((w - L3.urlW) / 2) : bx);
2631
+ y += L3.chip * 1.9;
2474
2632
  }
2475
- y += L.hint * 0.6;
2476
- for (const line of L.hints) {
2477
- drawTracked(g, line, ax, y + L.hint * 0.95, { size: L.hint, family: sans, color: theme.colors.inkFaint, align });
2478
- y += L.lineH(L.hint);
2633
+ y += L3.hint * 0.6;
2634
+ for (const line of L3.hints) {
2635
+ drawTracked(g, line, ax, y + L3.hint * 0.95, { size: L3.hint, family: sans, color: theme.colors.inkFaint, align });
2636
+ y += L3.lineH(L3.hint);
2479
2637
  }
2480
2638
  }
2481
2639
 
@@ -2540,6 +2698,7 @@ var ScreenRunner = class {
2540
2698
  nextAt = 0;
2541
2699
  busy = false;
2542
2700
  pinned = null;
2701
+ context = null;
2543
2702
  playedSlot = /* @__PURE__ */ new Map();
2544
2703
  interlude = null;
2545
2704
  /** The buttons of whoever plays the interlude now (Play page). */
@@ -2623,9 +2782,7 @@ var ScreenRunner = class {
2623
2782
  this.dirty = true;
2624
2783
  }
2625
2784
  currentPage(now) {
2626
- const working = this.rt.working(now);
2627
- const pages = this.screen.pages.filter((p) => whenMatches(p.when, working));
2628
- return pickPage(pages, now, this.pinned);
2785
+ return choosePage(this.screen, now, this.rt.working(now), this.pinned, this.context?.page ?? null);
2629
2786
  }
2630
2787
  /**
2631
2788
  * The alert for this screen now (or none). One coming up stops what plays
@@ -2701,7 +2858,7 @@ var ScreenRunner = class {
2701
2858
  now,
2702
2859
  working: this.rt.working(now),
2703
2860
  dataOf: (inst) => this.rt.dataOf(inst.id),
2704
- sourcesOf: (types) => this.rt.sourcesOf(types),
2861
+ sourcesOf: (types, profile) => this.rt.sourcesOf(types, profile),
2705
2862
  log: this.rt.log,
2706
2863
  demo: this.rt.demoMode,
2707
2864
  cache: this.tiles,
@@ -2867,7 +3024,7 @@ var ScreenRunner = class {
2867
3024
  async maybeInterlude(now, force, play = false) {
2868
3025
  const due = this.screen.interludes.find((s) => {
2869
3026
  if (force) return s.id === force;
2870
- if (!s.enabled || s.everyMs < 6e4) return false;
3027
+ if (!s.enabled || s.everyMs < 6e4 || this.context) return false;
2871
3028
  const slot = Math.floor(now / s.everyMs);
2872
3029
  return now - slot * s.everyMs < 6e4 && this.playedSlot.get(s.id) !== slot;
2873
3030
  });
@@ -3018,9 +3175,9 @@ var ScreenRunner = class {
3018
3175
  if (!memoData.has(inst.id)) memoData.set(inst.id, this.rt.dataOf(inst.id));
3019
3176
  return memoData.get(inst.id);
3020
3177
  },
3021
- sourcesOf: (types) => {
3022
- const k = JSON.stringify(types ?? []);
3023
- if (!memoSources.has(k)) memoSources.set(k, this.rt.sourcesOf(types));
3178
+ sourcesOf: (types, profile) => {
3179
+ const k = JSON.stringify([types ?? [], profile ?? null]);
3180
+ if (!memoSources.has(k)) memoSources.set(k, this.rt.sourcesOf(types, profile));
3024
3181
  return memoSources.get(k);
3025
3182
  },
3026
3183
  log: this.rt.log,
@@ -3088,6 +3245,10 @@ var ScreenRunner = class {
3088
3245
  this.pinned = pageId;
3089
3246
  this.dirty = true;
3090
3247
  }
3248
+ setContext(pick2) {
3249
+ if (pick2?.page !== this.context?.page) this.dirty = true;
3250
+ this.context = pick2;
3251
+ }
3091
3252
  setOff(off) {
3092
3253
  this.off = off;
3093
3254
  if (off) this.stopInterlude();
@@ -3499,13 +3660,13 @@ var Registry = class {
3499
3660
  }
3500
3661
  /** What the editor needs to know about every widget, source and interlude (JSON-safe). */
3501
3662
  catalog(locale) {
3502
- const L = (x) => localize(x, locale);
3663
+ const L3 = (x) => localize(x, locale);
3503
3664
  const has = (type) => !!(this.widget(type) ?? this.source(type) ?? this.interlude(type));
3504
3665
  return this.list().map(({ def, origin, enabled }) => ({
3505
3666
  id: def.id,
3506
- name: L(def.name),
3667
+ name: L3(def.name),
3507
3668
  version: def.version,
3508
- description: L(def.description),
3669
+ description: L3(def.description),
3509
3670
  author: def.author,
3510
3671
  homepage: def.homepage,
3511
3672
  repository: def.repository,
@@ -3522,15 +3683,15 @@ var Registry = class {
3522
3683
  optional: (def.optional ?? []).map((type) => ({ type, plugin: pluginOf(type), ok: has(type) })),
3523
3684
  templates: (def.templates ?? []).map((tp) => {
3524
3685
  const tiles = (list2) => list2?.map((tile) => ({ ...tile, widgets: tile.widgets.map((w) => typeof w === "string" ? fullType(def.id, w) : [fullType(def.id, w[0]), w[1]]) }));
3525
- return { id: `${def.id}/${tp.id}`, name: L(tp.name), icon: tp.icon ?? "layout-template", wide: tiles(tp.wide), square: tiles(tp.square), tall: tiles(tp.tall) };
3686
+ return { id: `${def.id}/${tp.id}`, name: L3(tp.name), icon: tp.icon ?? "layout-template", wide: tiles(tp.wide), square: tiles(tp.square), tall: tiles(tp.tall) };
3526
3687
  }),
3527
3688
  builtin: origin === "builtin",
3528
3689
  origin,
3529
3690
  enabled,
3530
3691
  widgets: (def.widgets ?? []).map((w) => ({
3531
3692
  type: `${def.id}/${w.id}`,
3532
- name: L(w.name),
3533
- description: L(w.description),
3693
+ name: L3(w.name),
3694
+ description: L3(w.description),
3534
3695
  icon: w.icon,
3535
3696
  category: w.category ?? "info",
3536
3697
  tags: w.tags ?? [],
@@ -3548,9 +3709,9 @@ var Registry = class {
3548
3709
  })),
3549
3710
  sources: (def.sources ?? []).map((s) => {
3550
3711
  const field = sourceOptionsField(s);
3551
- return { type: `${def.id}/${s.id}`, name: L(s.name), description: L(s.description), options: field ? toJsonSchema(field) : null, intervalMs: s.read ? sourceTiming(s).intervalMs : null, polled: !!s.read, background: canRunInBackground(s) };
3712
+ return { type: `${def.id}/${s.id}`, name: L3(s.name), description: L3(s.description), options: field ? toJsonSchema(field) : null, intervalMs: s.read ? sourceTiming(s).intervalMs : null, polled: !!s.read, background: canRunInBackground(s), profiles: acceptsProfiles(s) };
3552
3713
  }),
3553
- interludes: (def.interludes ?? []).map((i) => ({ type: `${def.id}/${i.id}`, name: L(i.name), description: L(i.description), icon: i.icon, fps: i.fps, input: !!i.input, options: i.options ? toJsonSchema(i.options) : null }))
3714
+ interludes: (def.interludes ?? []).map((i) => ({ type: `${def.id}/${i.id}`, name: L3(i.name), description: L3(i.description), icon: i.icon, fps: i.fps, input: !!i.input, options: i.options ? toJsonSchema(i.options) : null }))
3554
3715
  }));
3555
3716
  }
3556
3717
  };
@@ -3679,11 +3840,15 @@ var Host = class {
3679
3840
  dataOf(instanceId) {
3680
3841
  return this.data.get(instanceId);
3681
3842
  }
3682
- sourcesOf(types) {
3843
+ sourcesOf(types, profile) {
3683
3844
  const out = {};
3684
- for (const t2 of types ?? []) out[t2] = this.sources.get(t2);
3845
+ for (const [t2, key] of this.sourceKeys(types, profile)) out[t2] = this.sources.get(key);
3685
3846
  return out;
3686
3847
  }
3848
+ /** The source keys a widget with `profile` reads, by type (see config/profiles.ts). */
3849
+ sourceKeys(types, profile) {
3850
+ return sourceKeysOf(this.config, types, profile, (t2) => this.registry.source(t2));
3851
+ }
3687
3852
  paintTime(instance, type, ms, now) {
3688
3853
  this.post({ t: "paintTime", instance, type, ms, now });
3689
3854
  }
@@ -3709,7 +3874,7 @@ var Host = class {
3709
3874
  if (!def || widget.disabled) continue;
3710
3875
  if (!r.page || r.page.id === page.id) {
3711
3876
  r.visibleIds.add(widget.id);
3712
- for (const s of def.sources ?? []) r.sourceTypes.add(s);
3877
+ for (const [, key] of this.sourceKeys(def.sources, widget.profile)) r.sourceTypes.add(key);
3713
3878
  }
3714
3879
  }
3715
3880
  }
@@ -3728,6 +3893,7 @@ async function runScreenThread(builtins = []) {
3728
3893
  const runner = new ScreenRunner(init.screen, host);
3729
3894
  host.runner = runner;
3730
3895
  if (init.pinned !== runner.pinned) runner.setPinned(init.pinned);
3896
+ if (init.context) runner.setContext(init.context);
3731
3897
  if (init.off) runner.setOff(true);
3732
3898
  host.visible();
3733
3899
  let lastState = "";
@@ -3788,6 +3954,9 @@ async function runScreenThread(builtins = []) {
3788
3954
  case "pin":
3789
3955
  runner.setPinned(m.page);
3790
3956
  return;
3957
+ case "context":
3958
+ runner.setContext(m.pick);
3959
+ return;
3791
3960
  case "off":
3792
3961
  runner.setOff(m.off);
3793
3962
  return;
@@ -3839,8 +4008,497 @@ var MAX_TARBALL_BYTES = 20 * 1024 * 1024;
3839
4008
  var CHUNK = 16 * 1024;
3840
4009
 
3841
4010
  // plugins/core/src/index.ts
3842
- import { readdir, readFile, stat } from "node:fs/promises";
4011
+ import { readdir, readFile as readFile2, stat } from "node:fs/promises";
4012
+ import { join as join7 } from "node:path";
4013
+
4014
+ // plugins/core/src/json.ts
4015
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3843
4016
  import { join as join6 } from "node:path";
4017
+
4018
+ // plugins/core/src/json-format.ts
4019
+ var TONES = ["ok", "info", "warn", "alert", "accent", "dim"];
4020
+ function toNumber(v) {
4021
+ if (typeof v === "number") return Number.isFinite(v) ? v : void 0;
4022
+ if (typeof v === "string" && /^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(v)) {
4023
+ const n = Number(v);
4024
+ return Number.isFinite(n) ? n : void 0;
4025
+ }
4026
+ return void 0;
4027
+ }
4028
+ var MAX_TEXT = 200;
4029
+ function formatNumber(n, decimals, locale) {
4030
+ const d = Math.max(-1, Math.min(6, Math.round(decimals)));
4031
+ try {
4032
+ return new Intl.NumberFormat(locale, d < 0 ? { maximumFractionDigits: 2 } : { minimumFractionDigits: d, maximumFractionDigits: d }).format(n);
4033
+ } catch {
4034
+ return d < 0 ? String(n) : n.toFixed(d);
4035
+ }
4036
+ }
4037
+ function valueText(v, o) {
4038
+ const n = typeof v === "number" || typeof v === "string" && o.decimals >= 0 ? toNumber(v) : void 0;
4039
+ if (n !== void 0) return formatNumber(n, o.decimals, o.locale);
4040
+ if (v === null || v === void 0 || v === "") return "\u2014";
4041
+ if (typeof v === "string") return v.length > MAX_TEXT ? `${v.slice(0, MAX_TEXT - 1)}\u2026` : v;
4042
+ if (typeof v === "boolean" || typeof v === "number") return String(v);
4043
+ let s;
4044
+ try {
4045
+ s = JSON.stringify(v);
4046
+ } catch {
4047
+ s = String(v);
4048
+ }
4049
+ return s.length > MAX_TEXT ? `${s.slice(0, MAX_TEXT - 1)}\u2026` : s;
4050
+ }
4051
+ var TIGHT_UNIT = /^(%|°|′|″|‰)/;
4052
+ function formatValue(v, o) {
4053
+ const text2 = valueText(v, o);
4054
+ if (text2 === "\u2014") return text2;
4055
+ const unit = o.unit.trim();
4056
+ return `${o.prefix}${text2}${unit ? TIGHT_UNIT.test(unit) ? unit : ` ${unit}` : ""}`;
4057
+ }
4058
+ var RULE = /^\s*(>=|<=|!=|==|=|>|<)?\s*(.*?)\s*$/s;
4059
+ function meets(v, when) {
4060
+ const m = RULE.exec(when);
4061
+ if (!m) return false;
4062
+ const op = m[1] ?? (toNumber(m[2]) !== void 0 ? ">=" : "=");
4063
+ const rhs = m[2];
4064
+ if (op === "=" || op === "==" || op === "!=") {
4065
+ const n2 = toNumber(v), r2 = toNumber(rhs);
4066
+ const equal2 = n2 !== void 0 && r2 !== void 0 ? n2 === r2 : String(v ?? "").trim().toLowerCase() === rhs.toLowerCase();
4067
+ return op === "!=" ? !equal2 : equal2;
4068
+ }
4069
+ const n = toNumber(v), r = toNumber(rhs);
4070
+ if (n === void 0 || r === void 0) return false;
4071
+ return op === ">=" ? n >= r : op === ">" ? n > r : op === "<" ? n < r : n <= r;
4072
+ }
4073
+ function toneFor(v, rules) {
4074
+ for (const r of rules) if (r.when.trim() && meets(v, r.when)) return r.tone;
4075
+ return void 0;
4076
+ }
4077
+
4078
+ // plugins/core/src/json-path.ts
4079
+ var MAX_PATH_LENGTH = 300;
4080
+ var MAX_PATH_STEPS = 32;
4081
+ var MAX_PATH_RESULTS = 500;
4082
+ var PathError = class extends Error {
4083
+ constructor(message) {
4084
+ super(message);
4085
+ this.name = "PathError";
4086
+ }
4087
+ };
4088
+ var NAME = /[\p{L}\p{N}_$@-]/u;
4089
+ function parsePath(path) {
4090
+ const p = path.trim();
4091
+ if (p.length > MAX_PATH_LENGTH) throw new PathError(`path longer than ${MAX_PATH_LENGTH} characters`);
4092
+ const steps = [];
4093
+ let i = 0;
4094
+ if (p[0] === "$") i = 1;
4095
+ const push2 = (s) => {
4096
+ if (steps.length >= MAX_PATH_STEPS) throw new PathError(`path with more than ${MAX_PATH_STEPS} steps`);
4097
+ steps.push(s);
4098
+ };
4099
+ let needDot = i === 1;
4100
+ while (i < p.length) {
4101
+ const c = p[i];
4102
+ if (c === ".") {
4103
+ i++;
4104
+ if (p[i] === "*") {
4105
+ push2({ all: true });
4106
+ i++;
4107
+ } else {
4108
+ const start = i;
4109
+ while (i < p.length && NAME.test(p[i])) i++;
4110
+ if (i === start) throw new PathError(`a name is missing after the dot at ${start}`);
4111
+ push2({ key: p.slice(start, i) });
4112
+ }
4113
+ needDot = true;
4114
+ continue;
4115
+ }
4116
+ if (c === "[") {
4117
+ i++;
4118
+ const q = p[i];
4119
+ if (q === "'" || q === '"') {
4120
+ let key = "";
4121
+ i++;
4122
+ for (; ; ) {
4123
+ if (i >= p.length) throw new PathError("a quoted key is not closed");
4124
+ const ch = p[i];
4125
+ if (ch === "\\" && i + 1 < p.length) {
4126
+ key += p[i + 1];
4127
+ i += 2;
4128
+ continue;
4129
+ }
4130
+ if (ch === q) break;
4131
+ key += ch;
4132
+ i++;
4133
+ }
4134
+ i++;
4135
+ push2({ key });
4136
+ } else if (q === "*") {
4137
+ i++;
4138
+ push2({ all: true });
4139
+ } else {
4140
+ const m = /^-?\d{1,9}/.exec(p.slice(i));
4141
+ if (!m) throw new PathError(`expected a number, '*' or a quoted key at ${i}`);
4142
+ i += m[0].length;
4143
+ push2({ index: Number(m[0]) });
4144
+ }
4145
+ if (p[i] !== "]") throw new PathError(`expected ']' at ${i}`);
4146
+ i++;
4147
+ needDot = true;
4148
+ continue;
4149
+ }
4150
+ if (!needDot && NAME.test(c)) {
4151
+ const start = i;
4152
+ while (i < p.length && NAME.test(p[i])) i++;
4153
+ push2({ key: p.slice(start, i) });
4154
+ needDot = true;
4155
+ continue;
4156
+ }
4157
+ throw new PathError(`unexpected '${c}' at ${i}`);
4158
+ }
4159
+ return steps;
4160
+ }
4161
+ var own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
4162
+ function step(v, s, out) {
4163
+ if (v === null || typeof v !== "object") return;
4164
+ if ("all" in s) {
4165
+ for (const x of Array.isArray(v) ? v : Object.values(v)) {
4166
+ if (out.length >= MAX_PATH_RESULTS) return;
4167
+ out.push(x);
4168
+ }
4169
+ return;
4170
+ }
4171
+ if ("index" in s) {
4172
+ if (!Array.isArray(v)) return;
4173
+ const i = s.index < 0 ? v.length + s.index : s.index;
4174
+ if (i >= 0 && i < v.length) out.push(v[i]);
4175
+ return;
4176
+ }
4177
+ if (own(v, s.key)) out.push(v[s.key]);
4178
+ }
4179
+ function readPath(doc, path) {
4180
+ const steps = typeof path === "string" ? parsePath(path) : path;
4181
+ const many = steps.some((s) => "all" in s);
4182
+ let cur = [doc];
4183
+ for (const s of steps) {
4184
+ const next = [];
4185
+ for (const v of cur) {
4186
+ step(v, s, next);
4187
+ if (next.length >= MAX_PATH_RESULTS) break;
4188
+ }
4189
+ cur = next;
4190
+ if (!cur.length) break;
4191
+ }
4192
+ if (many) return { found: cur.length > 0, value: cur };
4193
+ return cur.length ? { found: true, value: cur[0] } : { found: false, value: void 0 };
4194
+ }
4195
+ var keyStep = (k) => /^[A-Za-z_$][\w$-]*$/.test(k) ? `.${k}` : `['${k.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}']`;
4196
+ function leafPaths(doc, max = 8) {
4197
+ const out = [];
4198
+ const walk = (v, at, depth) => {
4199
+ if (out.length >= max) return;
4200
+ if (v !== null && typeof v === "object" && depth < 8) {
4201
+ if (Array.isArray(v)) {
4202
+ if (v.length) walk(v[0], `${at}[0]`, depth + 1);
4203
+ else out.push({ path: at, value: v });
4204
+ return;
4205
+ }
4206
+ const keys = Object.keys(v);
4207
+ if (!keys.length) out.push({ path: at, value: v });
4208
+ for (const k of keys) walk(v[k], at + keyStep(k), depth + 1);
4209
+ return;
4210
+ }
4211
+ out.push({ path: at, value: v });
4212
+ };
4213
+ walk(doc, "$", 0);
4214
+ return out;
4215
+ }
4216
+
4217
+ // plugins/core/src/push-store.ts
4218
+ var PUSH_LIMITS = {
4219
+ /** Largest body a push may send. */
4220
+ maxBytes: 64 * 1024,
4221
+ /** Most payloads kept per name for the charts… */
4222
+ historyItems: 240,
4223
+ /** …and most bytes they may take together. */
4224
+ historyBytes: 64 * 1024,
4225
+ /** Longest `ttlMs` honoured: 30 days. */
4226
+ maxTtlMs: 30 * 24 * 36e5
4227
+ };
4228
+ var PUSH_NAME = /^[a-z0-9][a-z0-9_-]{0,39}$/;
4229
+ var sizeOf = (v) => {
4230
+ try {
4231
+ return JSON.stringify(v)?.length ?? 0;
4232
+ } catch {
4233
+ return Infinity;
4234
+ }
4235
+ };
4236
+ var PushStore = class {
4237
+ names = [];
4238
+ entries = /* @__PURE__ */ new Map();
4239
+ listeners = /* @__PURE__ */ new Set();
4240
+ /** The push names set up (from the config): payloads of names no longer there are dropped. */
4241
+ configure(names) {
4242
+ const next = [...new Set(names.filter((n) => PUSH_NAME.test(n)))].sort();
4243
+ if (next.join("\n") === this.names.join("\n")) return;
4244
+ this.names = next;
4245
+ for (const k of [...this.entries.keys()]) if (!next.includes(k)) this.entries.delete(k);
4246
+ this.changed();
4247
+ }
4248
+ has(name) {
4249
+ return this.names.includes(name);
4250
+ }
4251
+ /** Keeps `payload` as the latest of `name` (which must be set up), with its `ttlMs` if it says one. */
4252
+ set(name, payload, now = Date.now()) {
4253
+ if (!this.has(name)) throw new Error(`unknown push name: ${name}`);
4254
+ const ttl = payload && typeof payload === "object" && !Array.isArray(payload) ? payload.ttlMs : void 0;
4255
+ const ttlMs = typeof ttl === "number" && Number.isFinite(ttl) && ttl > 0 ? Math.min(ttl, PUSH_LIMITS.maxTtlMs) : void 0;
4256
+ const old = this.entries.get(name);
4257
+ const history = [...old?.history ?? [], { at: now, payload }];
4258
+ let bytes = history.reduce((s, r) => s + sizeOf(r.payload), 0);
4259
+ while (history.length > 1 && (history.length > PUSH_LIMITS.historyItems || bytes > PUSH_LIMITS.historyBytes)) bytes -= sizeOf(history.shift().payload);
4260
+ const entry = { at: now, payload, ...ttlMs ? { expiresAt: now + ttlMs } : {}, history };
4261
+ this.entries.set(name, entry);
4262
+ this.changed();
4263
+ return entry;
4264
+ }
4265
+ /** Forgets the payloads of `name` (`DELETE /api/push/<name>`). */
4266
+ clear(name) {
4267
+ const had = this.entries.delete(name);
4268
+ if (had) this.changed();
4269
+ return had;
4270
+ }
4271
+ get(name) {
4272
+ return this.entries.get(name);
4273
+ }
4274
+ snapshot() {
4275
+ return { hooks: Object.fromEntries(this.names.map((n) => [n, this.entries.get(n) ?? null])) };
4276
+ }
4277
+ /** Calls `fn` with a new snapshot on every change; returns what stops it. */
4278
+ subscribe(fn) {
4279
+ this.listeners.add(fn);
4280
+ return () => this.listeners.delete(fn);
4281
+ }
4282
+ /** The entries, to keep on disk. */
4283
+ dump() {
4284
+ return Object.fromEntries(this.entries);
4285
+ }
4286
+ /** Entries kept on disk, back (those of names not set up are ignored, malformed ones too). */
4287
+ load(saved) {
4288
+ if (!saved || typeof saved !== "object") return;
4289
+ for (const [name, e] of Object.entries(saved)) {
4290
+ if (!this.has(name) || !e || typeof e !== "object") continue;
4291
+ const { at, payload, expiresAt, history } = e;
4292
+ if (typeof at !== "number") continue;
4293
+ const hist = Array.isArray(history) ? history.filter((r) => !!r && typeof r === "object" && typeof r.at === "number").slice(-PUSH_LIMITS.historyItems) : [];
4294
+ this.entries.set(name, { at, payload, ...typeof expiresAt === "number" ? { expiresAt } : {}, history: hist.length ? hist : [{ at, payload }] });
4295
+ }
4296
+ this.changed();
4297
+ }
4298
+ changed() {
4299
+ if (!this.listeners.size) return;
4300
+ const snap = this.snapshot();
4301
+ for (const fn of this.listeners) fn(snap);
4302
+ }
4303
+ };
4304
+ var pushes = new PushStore();
4305
+ var live = (e, now) => !!e && (e.expiresAt === void 0 || e.expiresAt > now);
4306
+
4307
+ // plugins/core/src/json.ts
4308
+ var L = (en, es, de, hant, hans) => ({ en, es, de, "zh-Hant": hant, "zh-Hans": hans });
4309
+ var PUSH_SOURCE = "core/push";
4310
+ var TONE_LABELS = {
4311
+ ok: L("Green (fine)", "Verde (bien)", "Gr\xFCn (gut)", "\u7DA0\u8272\uFF08\u6B63\u5E38\uFF09", "\u7EFF\u8272\uFF08\u6B63\u5E38\uFF09"),
4312
+ info: L("Blue (note)", "Azul (aviso)", "Blau (Hinweis)", "\u85CD\u8272\uFF08\u63D0\u793A\uFF09", "\u84DD\u8272\uFF08\u63D0\u793A\uFF09"),
4313
+ warn: L("Amber (watch)", "\xC1mbar (ojo)", "Bernstein (aufpassen)", "\u7425\u73C0\u8272\uFF08\u6CE8\u610F\uFF09", "\u7425\u73C0\u8272\uFF08\u6CE8\u610F\uFF09"),
4314
+ alert: L("Red (needs you)", "Rojo (te necesita)", "Rot (braucht dich)", "\u7D05\u8272\uFF08\u9700\u8981\u8655\u7406\uFF09", "\u7EA2\u8272\uFF08\u9700\u8981\u5904\u7406\uFF09"),
4315
+ accent: L("Accent", "Acento", "Akzent", "\u5F37\u8ABF\u8272", "\u5F3A\u8C03\u8272"),
4316
+ dim: L("Dim", "Tenue", "Ged\xE4mpft", "\u6DE1\u8272", "\u6697\u6DE1")
4317
+ };
4318
+ var toneColor = (theme, tone) => tone === void 0 ? theme.colors.ink : tone === "dim" ? theme.colors.inkDim : theme.colors[tone];
4319
+ function sourceOptions() {
4320
+ return {
4321
+ url: t.string({
4322
+ format: "url",
4323
+ risk: "network",
4324
+ placeholder: "https://api.example.com/status.json",
4325
+ label: L("URL", "URL", "URL", "URL", "URL"),
4326
+ help: L(
4327
+ "Asked every refresh (the widget's interval). It should answer JSON; plain text is read as one value. {secret} in it becomes the secret below.",
4328
+ "Se consulta en cada refresco (el intervalo del widget). Deber\xEDa responder JSON; el texto plano se lee como un solo valor. {secret} se cambia por el secreto de abajo.",
4329
+ "Wird bei jeder Aktualisierung abgefragt (Intervall des Widgets). Sie sollte JSON liefern; reiner Text gilt als ein Wert. {secret} wird durch das Geheimnis unten ersetzt.",
4330
+ "\u6BCF\u6B21\u91CD\u65B0\u6574\u7406\u6642\u67E5\u8A62\uFF08\u5C0F\u5DE5\u5177\u7684\u9593\u9694\uFF09\u3002\u61C9\u56DE\u50B3 JSON\uFF1B\u7D14\u6587\u5B57\u6703\u7576\u6210\u55AE\u4E00\u6578\u503C\u3002\u5176\u4E2D\u7684 {secret} \u6703\u63DB\u6210\u4E0B\u65B9\u7684\u5BC6\u9470\u3002",
4331
+ "\u6BCF\u6B21\u5237\u65B0\u65F6\u8BF7\u6C42\uFF08\u5C0F\u7EC4\u4EF6\u7684\u95F4\u9694\uFF09\u3002\u5E94\u8FD4\u56DE JSON\uFF1B\u7EAF\u6587\u672C\u4F1A\u5F53\u4F5C\u5355\u4E2A\u503C\u3002\u5176\u4E2D\u7684 {secret} \u4F1A\u66FF\u6362\u4E3A\u4E0B\u65B9\u7684\u5BC6\u94A5\u3002"
4332
+ )
4333
+ }),
4334
+ push: t.string({
4335
+ choices: { source: PUSH_SOURCE, list: "names" },
4336
+ placeholder: "garage",
4337
+ label: L("Or a push name", "O un nombre de push", "Oder ein Push-Name", "\u6216\u63A8\u9001\u540D\u7A31", "\u6216\u63A8\u9001\u540D\u79F0"),
4338
+ help: L(
4339
+ "Instead of a URL: what a script sends to POST /api/push/<name>. Set up push names in Settings \u2192 Push.",
4340
+ "En vez de una URL: lo que un script env\xEDa a POST /api/push/<nombre>. Los nombres se crean en Ajustes \u2192 Push.",
4341
+ "Statt einer URL: was ein Skript an POST /api/push/<name> sendet. Push-Namen legst du unter Einstellungen \u2192 Push an.",
4342
+ "\u53D6\u4EE3 URL\uFF1A\u8173\u672C\u50B3\u9001\u5230 POST /api/push/<\u540D\u7A31> \u7684\u5167\u5BB9\u3002\u63A8\u9001\u540D\u7A31\u5728\u300C\u8A2D\u5B9A \u2192 \u63A8\u9001\u300D\u4E2D\u5EFA\u7ACB\u3002",
4343
+ "\u4EE3\u66FF URL\uFF1A\u811A\u672C\u53D1\u9001\u5230 POST /api/push/<\u540D\u79F0> \u7684\u5185\u5BB9\u3002\u63A8\u9001\u540D\u79F0\u5728\u201C\u8BBE\u7F6E \u2192 \u63A8\u9001\u201D\u4E2D\u521B\u5EFA\u3002"
4344
+ )
4345
+ }),
4346
+ secret: t.string({
4347
+ secret: true,
4348
+ label: L("Secret (token, API key)", "Secreto (token, clave de API)", "Geheimnis (Token, API-Schl\xFCssel)", "\u5BC6\u9470\uFF08\u6B0A\u6756\u3001API \u91D1\u9470\uFF09", "\u5BC6\u94A5\uFF08\u4EE4\u724C\u3001API \u5BC6\u94A5\uFF09"),
4349
+ help: L(
4350
+ 'Sent in the header below (e.g. "Bearer abc123"), or wherever {secret} appears in the URL, headers or body.',
4351
+ "Se env\xEDa en la cabecera de abajo (p. ej. \xABBearer abc123\xBB), o donde aparezca {secret} en la URL, las cabeceras o el cuerpo.",
4352
+ "Wird im Header unten gesendet (z. B. \u201EBearer abc123\u201C) oder dort, wo {secret} in URL, Headern oder Body steht.",
4353
+ "\u653E\u5728\u4E0B\u65B9\u7684\u6A19\u982D\u4E2D\u9001\u51FA\uFF08\u4F8B\u5982\u300CBearer abc123\u300D\uFF09\uFF0C\u6216\u653E\u5728 URL\u3001\u6A19\u982D\u3001\u5167\u6587\u4E2D {secret} \u51FA\u73FE\u7684\u4F4D\u7F6E\u3002",
4354
+ "\u653E\u5728\u4E0B\u65B9\u7684\u8BF7\u6C42\u5934\u4E2D\u53D1\u9001\uFF08\u4F8B\u5982\u201CBearer abc123\u201D\uFF09\uFF0C\u6216\u653E\u5728 URL\u3001\u8BF7\u6C42\u5934\u3001\u8BF7\u6C42\u4F53\u4E2D {secret} \u51FA\u73B0\u7684\u4F4D\u7F6E\u3002"
4355
+ )
4356
+ }),
4357
+ authHeader: t.string({
4358
+ default: "Authorization",
4359
+ advanced: true,
4360
+ label: L("Header for the secret", "Cabecera del secreto", "Header f\xFCr das Geheimnis", "\u5BC6\u9470\u4F7F\u7528\u7684\u6A19\u982D", "\u5BC6\u94A5\u4F7F\u7528\u7684\u8BF7\u6C42\u5934"),
4361
+ help: L("Authorization, X-Api-Key\u2026 Empty: only where {secret} is written.", "Authorization, X-Api-Key\u2026 Vac\xEDa: solo donde est\xE9 {secret}.", "Authorization, X-Api-Key\u2026 Leer: nur dort, wo {secret} steht.", "Authorization\u3001X-Api-Key\u2026 \u7559\u7A7A\uFF1A\u53EA\u653E\u5728 {secret} \u7684\u4F4D\u7F6E\u3002", "Authorization\u3001X-Api-Key\u2026 \u7559\u7A7A\uFF1A\u53EA\u653E\u5728 {secret} \u7684\u4F4D\u7F6E\u3002")
4362
+ }),
4363
+ headers: t.map({ advanced: true, label: L("Other headers", "Otras cabeceras", "Weitere Header", "\u5176\u4ED6\u6A19\u982D", "\u5176\u4ED6\u8BF7\u6C42\u5934"), keyLabel: L("Header", "Cabecera", "Header", "\u6A19\u982D", "\u8BF7\u6C42\u5934"), valueLabel: L("Value", "Valor", "Wert", "\u503C", "\u503C") }),
4364
+ method: t.enum(["GET", "POST"], { advanced: true, label: L("Method", "M\xE9todo", "Methode", "\u65B9\u6CD5", "\u65B9\u6CD5") }),
4365
+ body: t.string({ multiline: true, advanced: true, placeholder: '{"query": "\u2026"}', label: L("Body (POST)", "Cuerpo (POST)", "Body (POST)", "\u5167\u6587\uFF08POST\uFF09", "\u8BF7\u6C42\u4F53\uFF08POST\uFF09"), help: L("Sent as JSON when it looks like JSON, else as text.", "Se env\xEDa como JSON si lo parece; si no, como texto.", "Wird als JSON gesendet, wenn es danach aussieht, sonst als Text.", "\u770B\u8D77\u4F86\u50CF JSON \u6642\u4EE5 JSON \u9001\u51FA\uFF0C\u5426\u5247\u4EE5\u7D14\u6587\u5B57\u9001\u51FA\u3002", "\u770B\u8D77\u6765\u50CF JSON \u65F6\u6309 JSON \u53D1\u9001\uFF0C\u5426\u5219\u6309\u7EAF\u6587\u672C\u53D1\u9001\u3002") }),
4366
+ timeoutMs: t.duration({ default: 1e4, min: 1e3, max: 6e4, advanced: true, label: L("Give up after", "Abandonar tras", "Aufgeben nach", "\u903E\u6642\u6642\u9593", "\u8D85\u65F6\u65F6\u95F4") }),
4367
+ maxKb: t.integer({ default: 512, min: 1, max: 5120, unit: "KB", advanced: true, label: L("Largest answer", "Respuesta m\xE1s grande", "Gr\xF6\xDFte Antwort", "\u56DE\u61C9\u5927\u5C0F\u4E0A\u9650", "\u54CD\u5E94\u5927\u5C0F\u4E0A\u9650"), help: L("A longer answer is refused, so a wrong URL can't fill the memory.", "Una m\xE1s larga se rechaza, para que una URL equivocada no llene la memoria.", "Eine l\xE4ngere wird abgelehnt, damit eine falsche URL nicht den Speicher f\xFCllt.", "\u8D85\u904E\u7684\u56DE\u61C9\u6703\u88AB\u62D2\u7D55\uFF0C\u4EE5\u514D\u932F\u8AA4\u7684 URL \u585E\u6EFF\u8A18\u61B6\u9AD4\u3002", "\u8D85\u51FA\u7684\u54CD\u5E94\u4F1A\u88AB\u62D2\u7EDD\uFF0C\u4EE5\u514D\u9519\u8BEF\u7684 URL \u5360\u6EE1\u5185\u5B58\u3002") })
4368
+ };
4369
+ }
4370
+ var pathField = (o = {}) => t.string({
4371
+ placeholder: o.placeholder ?? "$.current.temperature_2m",
4372
+ label: o.label ?? L("Path to the value", "Ruta del valor", "Pfad zum Wert", "\u6578\u503C\u8DEF\u5F91", "\u6570\u503C\u8DEF\u5F84"),
4373
+ help: o.help ?? L(
4374
+ "$.a.b, items[0].price, items[-1], ['key with spaces']. Empty: the widget lists the paths it finds.",
4375
+ "$.a.b, items[0].price, items[-1], ['clave con espacios']. Vac\xEDa: el widget ense\xF1a las rutas que encuentra.",
4376
+ "$.a.b, items[0].price, items[-1], ['Schl\xFCssel mit Leerzeichen']. Leer: Das Widget zeigt die gefundenen Pfade.",
4377
+ "$.a.b\u3001items[0].price\u3001items[-1]\u3001['\u542B\u7A7A\u683C\u7684\u9375']\u3002\u7559\u7A7A\uFF1A\u5C0F\u5DE5\u5177\u6703\u5217\u51FA\u627E\u5230\u7684\u8DEF\u5F91\u3002",
4378
+ "$.a.b\u3001items[0].price\u3001items[-1]\u3001['\u542B\u7A7A\u683C\u7684\u952E']\u3002\u7559\u7A7A\uFF1A\u5C0F\u7EC4\u4EF6\u4F1A\u5217\u51FA\u627E\u5230\u7684\u8DEF\u5F84\u3002"
4379
+ )
4380
+ });
4381
+ var formatOptions = () => ({
4382
+ prefix: t.string({ placeholder: "$", label: L("Before the value", "Antes del valor", "Vor dem Wert", "\u6578\u503C\u524D\u7DB4", "\u6570\u503C\u524D\u7F00") }),
4383
+ unit: t.string({ placeholder: "\xB0C", label: L("Unit", "Unidad", "Einheit", "\u55AE\u4F4D", "\u5355\u4F4D") }),
4384
+ decimals: t.integer({ default: -1, min: -1, max: 6, label: L("Decimals", "Decimales", "Nachkommastellen", "\u5C0F\u6578\u4F4D\u6578", "\u5C0F\u6570\u4F4D\u6570"), help: L("-1: as it comes (up to 2).", "-1: tal como viene (hasta 2).", "-1: wie geliefert (bis zu 2).", "-1\uFF1A\u4F9D\u539F\u59CB\u503C\uFF08\u6700\u591A 2 \u4F4D\uFF09\u3002", "-1\uFF1A\u6309\u539F\u59CB\u503C\uFF08\u6700\u591A 2 \u4F4D\uFF09\u3002") }),
4385
+ thresholds: t.list(
4386
+ t.object({
4387
+ when: t.string({ placeholder: ">= 30", label: L("When", "Cuando", "Wenn", "\u689D\u4EF6", "\u6761\u4EF6") }),
4388
+ tone: t.enum(TONES, { default: "warn", label: L("Colour", "Color", "Farbe", "\u984F\u8272", "\u989C\u8272"), labels: TONE_LABELS })
4389
+ }),
4390
+ {
4391
+ max: 8,
4392
+ label: L("Colours by value", "Colores seg\xFAn el valor", "Farben nach Wert", "\u4F9D\u6578\u503C\u8B8A\u8272", "\u6309\u6570\u503C\u53D8\u8272"),
4393
+ help: L(
4394
+ "The first that holds wins: >= 30, > 30, < 0, <= 5, = failed, != ok, or a bare number (meaning >=).",
4395
+ "Gana la primera que se cumple: >= 30, > 30, < 0, <= 5, = failed, != ok, o un n\xFAmero solo (es >=).",
4396
+ "Die erste zutreffende gilt: >= 30, > 30, < 0, <= 5, = failed, != ok oder eine blo\xDFe Zahl (bedeutet >=).",
4397
+ "\u7B2C\u4E00\u500B\u6210\u7ACB\u7684\u689D\u4EF6\u751F\u6548\uFF1A>= 30\u3001> 30\u3001< 0\u3001<= 5\u3001= failed\u3001!= ok\uFF0C\u6216\u55AE\u7368\u4E00\u500B\u6578\u5B57\uFF08\u8868\u793A >=\uFF09\u3002",
4398
+ "\u7B2C\u4E00\u4E2A\u6210\u7ACB\u7684\u6761\u4EF6\u751F\u6548\uFF1A>= 30\u3001> 30\u3001< 0\u3001<= 5\u3001= failed\u3001!= ok\uFF0C\u6216\u5355\u72EC\u4E00\u4E2A\u6570\u5B57\uFF08\u8868\u793A >=\uFF09\u3002"
4399
+ )
4400
+ }
4401
+ )
4402
+ });
4403
+ var http = createHttp({ agent: "kiosko-core" });
4404
+ var recent = /* @__PURE__ */ new Map();
4405
+ var SHARE_MS = 2e3;
4406
+ var fill = (s, secret) => s.replace(/\{secret\}/g, secret);
4407
+ function requestOf(o) {
4408
+ const placed = [o.url, o.body, ...Object.keys(o.headers), ...Object.values(o.headers)].some((s) => s.includes("{secret}"));
4409
+ const url = o.url.includes("{secret}") ? o.url.replace(/\{secret\}/g, encodeURIComponent(o.secret)) : o.url.trim();
4410
+ const headers = {};
4411
+ for (const [k, v] of Object.entries(o.headers)) if (k.trim()) headers[k.trim()] = fill(String(v), o.secret);
4412
+ if (o.secret && !placed && o.authHeader.trim()) headers[o.authHeader.trim()] = o.secret;
4413
+ const body = o.method === "POST" && o.body.trim() ? fill(o.body, o.secret) : void 0;
4414
+ if (body !== void 0 && !Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) headers["Content-Type"] = /^\s*[[{]/.test(body) ? "application/json" : "text/plain; charset=utf-8";
4415
+ return { url, method: o.method, headers, ...body !== void 0 ? { body } : {} };
4416
+ }
4417
+ function parseBody(text2) {
4418
+ try {
4419
+ return JSON.parse(text2);
4420
+ } catch {
4421
+ return text2.trim();
4422
+ }
4423
+ }
4424
+ async function requestJson(o, signal) {
4425
+ const req = requestOf(o);
4426
+ if (!/^https?:\/\//i.test(req.url)) throw new Error("the URL must start with http:// or https://");
4427
+ const key = JSON.stringify([req, o.maxKb]);
4428
+ const now = Date.now();
4429
+ for (const [k, r] of recent) if (now - r.at > SHARE_MS) recent.delete(k);
4430
+ const hit = recent.get(key);
4431
+ if (hit) return hit.doc;
4432
+ const timeout = AbortSignal.timeout(o.timeoutMs);
4433
+ const doc = http.text(req.url, { signal: AbortSignal.any([signal, timeout]), method: req.method, headers: { Accept: "application/json, text/plain;q=0.8, */*;q=0.5", ...req.headers }, ...req.body !== void 0 ? { body: req.body } : {}, maxBytes: o.maxKb * 1024 }).then((r) => parseBody(r.data));
4434
+ recent.set(key, { at: now, doc });
4435
+ doc.catch(() => recent.delete(key));
4436
+ return doc;
4437
+ }
4438
+ function pushedDoc(sources, name, now) {
4439
+ const e = sources[PUSH_SOURCE]?.hooks?.[name.trim()];
4440
+ return live(e, now) ? { found: true, doc: e.payload, at: e.at } : { found: false, doc: void 0 };
4441
+ }
4442
+ function hintsOf(doc, max = 6) {
4443
+ return leafPaths(doc, max).map((l) => `${l.path} = ${valueText(l.value, { decimals: -1, locale: "en" }).slice(0, 40)}`);
4444
+ }
4445
+ function pick(doc, path) {
4446
+ if (!path.trim()) return { found: false, hints: hintsOf(doc) };
4447
+ try {
4448
+ const r = readPath(doc, path);
4449
+ return r.found ? { found: true, value: r.value } : { found: false, hints: hintsOf(doc) };
4450
+ } catch (err) {
4451
+ return { found: false, error: err instanceof Error ? err.message : String(err) };
4452
+ }
4453
+ }
4454
+ var MAX_POINTS = 500;
4455
+ var SAME_POINT_MS = 2e3;
4456
+ var histories = /* @__PURE__ */ new Map();
4457
+ function hash(s) {
4458
+ let h = 2166136261;
4459
+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619) >>> 0;
4460
+ return h.toString(36);
4461
+ }
4462
+ function addPoint(series, at, v, max) {
4463
+ const last = series.at(-1);
4464
+ const out = last && Math.abs(at - last[0]) < SAME_POINT_MS ? [...series.slice(0, -1), [at, v]] : [...series, [at, v]];
4465
+ return out.slice(-Math.max(2, Math.min(MAX_POINTS, max)));
4466
+ }
4467
+ async function remember(dir, key, at, v, max) {
4468
+ const file = join6(dir, "json-history", `${hash(key)}.json`);
4469
+ let series = histories.get(key);
4470
+ if (!series) {
4471
+ try {
4472
+ const saved = JSON.parse(await readFile(file, "utf8"));
4473
+ series = Array.isArray(saved) ? saved.filter((p) => Array.isArray(p) && typeof p[0] === "number" && typeof p[1] === "number") : [];
4474
+ } catch {
4475
+ series = [];
4476
+ }
4477
+ }
4478
+ if (v !== void 0) {
4479
+ series = addPoint(series, at, v, max);
4480
+ await mkdir(join6(dir, "json-history"), { recursive: true });
4481
+ await writeFile(file, JSON.stringify(series));
4482
+ }
4483
+ histories.set(key, series);
4484
+ return series;
4485
+ }
4486
+ function pushedSeries(sources, name, path, max) {
4487
+ const e = sources[PUSH_SOURCE]?.hooks?.[name.trim()];
4488
+ if (!e || !path.trim()) return [];
4489
+ let steps;
4490
+ try {
4491
+ steps = parsePath(path);
4492
+ } catch {
4493
+ return [];
4494
+ }
4495
+ const out = [];
4496
+ for (const r of e.history) {
4497
+ const n = toNumber(readPath(r.payload, steps).value);
4498
+ if (n !== void 0) out.push([r.at, n]);
4499
+ }
4500
+ return out.slice(-max);
4501
+ }
3844
4502
  function fit(g, text2, family, w, h, max = 400) {
3845
4503
  let size = Math.min(max, h);
3846
4504
  g.font = `${size}px "${family}"`;
@@ -3848,6 +4506,522 @@ function fit(g, text2, family, w, h, max = 400) {
3848
4506
  if (width > w) size = Math.floor(size * w / width);
3849
4507
  return Math.max(8, size);
3850
4508
  }
4509
+ function drawNothing(g, ctx, p) {
4510
+ const { box, kit, theme } = ctx;
4511
+ const size = Math.max(10, Math.min(26, Math.round(box.h / 7)));
4512
+ const font = { size, family: theme.fonts.sans, color: theme.colors.inkDim };
4513
+ kit.drawTracked(g, kit.truncate(g, p.message, box.w, font), box.x, box.y + size * 1.1, font);
4514
+ const hs = Math.max(9, Math.round(size * 0.8));
4515
+ const mono = { size: hs, family: theme.fonts.mono, color: theme.colors.inkFaint };
4516
+ (p.hints ?? []).forEach((h, i) => {
4517
+ const y = box.y + size * 1.1 + (i + 1) * hs * 1.35;
4518
+ if (y < box.y + box.h) kit.drawTracked(g, kit.truncate(g, h, box.w, mono), box.x, y, mono);
4519
+ });
4520
+ }
4521
+ var WAITING = L("Waiting for data\u2026", "Esperando datos\u2026", "Warte auf Daten\u2026", "\u7B49\u5F85\u8CC7\u6599\u4E2D\u2026", "\u7B49\u5F85\u6570\u636E\u4E2D\u2026");
4522
+ var NO_SOURCE = L("Set a URL or a push name", "Pon una URL o un nombre de push", "URL oder Push-Namen angeben", "\u8ACB\u8A2D\u5B9A URL \u6216\u63A8\u9001\u540D\u7A31", "\u8BF7\u8BBE\u7F6E URL \u6216\u63A8\u9001\u540D\u79F0");
4523
+ var NOT_FOUND = L("Nothing at that path. It has:", "No hay nada en esa ruta. Tiene:", "Unter diesem Pfad ist nichts. Vorhanden:", "\u8A72\u8DEF\u5F91\u6C92\u6709\u8CC7\u6599\u3002\u53EF\u7528\u7684\u6709\uFF1A", "\u8BE5\u8DEF\u5F84\u6CA1\u6709\u6570\u636E\u3002\u53EF\u7528\u7684\u6709\uFF1A");
4524
+ var CHOOSE = L("Choose a path. It has:", "Elige una ruta. Tiene:", "W\xE4hle einen Pfad. Vorhanden:", "\u8ACB\u9078\u64C7\u8DEF\u5F91\u3002\u53EF\u7528\u7684\u6709\uFF1A", "\u8BF7\u9009\u62E9\u8DEF\u5F84\u3002\u53EF\u7528\u7684\u6709\uFF1A");
4525
+ var BAD_PATH = L("Wrong path: ", "Ruta incorrecta: ", "Falscher Pfad: ", "\u8DEF\u5F91\u932F\u8AA4\uFF1A", "\u8DEF\u5F84\u9519\u8BEF\uFF1A");
4526
+ var NO_PUSH = L('Nothing pushed to "{name}" yet', "A\xFAn no se ha enviado nada a \xAB{name}\xBB", "Noch nichts an \u201E{name}\u201C gesendet", "\u5C1A\u672A\u6709\u5167\u5BB9\u63A8\u9001\u5230\u300C{name}\u300D", "\u5C1A\u672A\u6709\u5185\u5BB9\u63A8\u9001\u5230\u201C{name}\u201D");
4527
+ function drawCurve(g, ctx, series, b, color) {
4528
+ if (series.length < 2 || b.w < 4 || b.h < 4) return;
4529
+ const vs = series.map((p) => p[1]);
4530
+ let lo = Math.min(...vs), hi = Math.max(...vs);
4531
+ if (hi === lo) {
4532
+ lo -= 1;
4533
+ hi += 1;
4534
+ }
4535
+ const t0 = series[0][0], t1 = series.at(-1)[0];
4536
+ const span = t1 - t0 || 1;
4537
+ const lw = Math.max(2, Math.round(b.h / 24));
4538
+ const xy = (p) => [b.x + (p[0] - t0) / span * b.w, b.y + lw / 2 + (1 - (p[1] - lo) / (hi - lo)) * (b.h - lw)];
4539
+ const pts = series.map(xy);
4540
+ g.save();
4541
+ g.beginPath();
4542
+ g.moveTo(pts[0][0], b.y + b.h);
4543
+ for (const [x, y] of pts) g.lineTo(x, y);
4544
+ g.lineTo(pts.at(-1)[0], b.y + b.h);
4545
+ g.closePath();
4546
+ g.fillStyle = /^#[0-9a-f]{6}$/i.test(color) ? ctx.kit.css(ctx.kit.hex(color), 0.18) : color;
4547
+ g.fill();
4548
+ g.beginPath();
4549
+ pts.forEach(([x, y], i) => i ? g.lineTo(x, y) : g.moveTo(x, y));
4550
+ g.strokeStyle = color;
4551
+ g.lineWidth = lw;
4552
+ g.lineJoin = "round";
4553
+ g.lineCap = "round";
4554
+ g.stroke();
4555
+ const [lx, ly] = pts.at(-1);
4556
+ g.fillStyle = color;
4557
+ g.beginPath();
4558
+ g.arc(lx, ly, lw * 1.4, 0, Math.PI * 2);
4559
+ g.fill();
4560
+ g.restore();
4561
+ }
4562
+ var jsonValue = defineWidget({
4563
+ id: "json",
4564
+ name: L("JSON value", "Valor JSON", "JSON-Wert", "JSON \u6578\u503C", "JSON \u6570\u503C"),
4565
+ description: L(
4566
+ "One number or word from any URL that answers JSON, or from a push: big, with its unit, colours by value and a curve of its history.",
4567
+ "Un n\xFAmero o una palabra de cualquier URL que responda JSON, o de un push: grande, con su unidad, colores seg\xFAn el valor y una curva con su hist\xF3rico.",
4568
+ "Eine Zahl oder ein Wort von einer beliebigen URL, die JSON liefert, oder aus einem Push: gro\xDF, mit Einheit, Farben nach Wert und einer Kurve des Verlaufs.",
4569
+ "\u4F86\u81EA\u4EFB\u4F55\u56DE\u50B3 JSON \u7684 URL \u6216\u63A8\u9001\u7684\u4E00\u500B\u6578\u5B57\u6216\u6587\u5B57\uFF1A\u5927\u5B57\u986F\u793A\uFF0C\u9644\u55AE\u4F4D\u3001\u4F9D\u6578\u503C\u8B8A\u8272\uFF0C\u4EE5\u53CA\u6B77\u53F2\u66F2\u7DDA\u3002",
4570
+ "\u6765\u81EA\u4EFB\u4F55\u8FD4\u56DE JSON \u7684 URL \u6216\u63A8\u9001\u7684\u4E00\u4E2A\u6570\u5B57\u6216\u6587\u5B57\uFF1A\u5927\u5B57\u663E\u793A\uFF0C\u9644\u5355\u4F4D\u3001\u6309\u6570\u503C\u53D8\u8272\uFF0C\u4EE5\u53CA\u5386\u53F2\u66F2\u7EBF\u3002"
4571
+ ),
4572
+ icon: "braces",
4573
+ category: "dev",
4574
+ tags: ["rest", "api", "json", "webhook", "push"],
4575
+ size: { min: { w: 120, h: 80 }, preferred: { w: 320, h: 220 } },
4576
+ sources: [PUSH_SOURCE],
4577
+ options: t.object({
4578
+ ...sourceOptions(),
4579
+ select: pathField(),
4580
+ label: t.string({ placeholder: "Temperature", label: L("Label", "Etiqueta", "Beschriftung", "\u6A19\u7C64", "\u6807\u7B7E"), help: L("A few words above the value. The tile's title works too.", "Unas palabras encima del valor. Tambi\xE9n vale el t\xEDtulo de la tesela.", "Ein paar Worte \xFCber dem Wert. Der Titel der Kachel geht auch.", "\u6578\u503C\u4E0A\u65B9\u7684\u5E7E\u500B\u5B57\u3002\u4E5F\u53EF\u4EE5\u7528\u65B9\u683C\u7684\u6A19\u984C\u3002", "\u6570\u503C\u4E0A\u65B9\u7684\u51E0\u4E2A\u5B57\u3002\u4E5F\u53EF\u4EE5\u7528\u683C\u5B50\u7684\u6807\u9898\u3002") }),
4581
+ ...formatOptions(),
4582
+ chart: t.enum(["below", "none"], { label: L("History curve", "Curva del hist\xF3rico", "Verlaufskurve", "\u6B77\u53F2\u66F2\u7DDA", "\u5386\u53F2\u66F2\u7EBF"), labels: { below: L("Under the value", "Debajo del valor", "Unter dem Wert", "\u5728\u6578\u503C\u4E0B\u65B9", "\u5728\u6570\u503C\u4E0B\u65B9"), none: L("None", "Ninguna", "Keine", "\u4E0D\u986F\u793A", "\u4E0D\u663E\u793A") } }),
4583
+ points: t.integer({ default: 60, min: 5, max: MAX_POINTS, advanced: true, label: L("Points in the curve", "Puntos de la curva", "Punkte der Kurve", "\u66F2\u7DDA\u9EDE\u6578", "\u66F2\u7EBF\u70B9\u6570"), help: L("One per refresh (or per push).", "Uno por refresco (o por push).", "Einer pro Aktualisierung (oder pro Push).", "\u6BCF\u6B21\u91CD\u65B0\u6574\u7406\uFF08\u6216\u6BCF\u6B21\u63A8\u9001\uFF09\u4E00\u9EDE\u3002", "\u6BCF\u6B21\u5237\u65B0\uFF08\u6216\u6BCF\u6B21\u63A8\u9001\uFF09\u4E00\u4E2A\u70B9\u3002") })
4584
+ }),
4585
+ intervalMs: 6e4,
4586
+ timeoutMs: 65e3,
4587
+ async fetch({ options, signal, cacheDir }) {
4588
+ if (options.push.trim() || !options.url.trim()) return null;
4589
+ const doc = await requestJson(options, signal);
4590
+ const picked = pick(doc, options.select);
4591
+ const at = Date.now();
4592
+ const n = picked.found ? toNumber(picked.value) : void 0;
4593
+ const series = options.chart === "none" ? [] : await remember(cacheDir, JSON.stringify([requestOf(options).url, options.method, options.body, options.select]), at, n, options.points).catch(() => []);
4594
+ return { at, picked, series };
4595
+ },
4596
+ redraw: "minute",
4597
+ render(g, ctx) {
4598
+ const { box, options, theme, kit, now, sources } = ctx;
4599
+ let picked;
4600
+ let series = [];
4601
+ if (options.push.trim()) {
4602
+ const p = pushedDoc(sources, options.push, now);
4603
+ if (!p.found) return drawNothing(g, ctx, { message: ctx.t(NO_PUSH).replace("{name}", options.push.trim()) });
4604
+ picked = pick(p.doc, options.select);
4605
+ if (options.chart !== "none") series = pushedSeries(sources, options.push, options.select, options.points);
4606
+ } else if (!options.url.trim()) return drawNothing(g, ctx, { message: ctx.t(NO_SOURCE) });
4607
+ else if (ctx.data) {
4608
+ picked = ctx.data.picked;
4609
+ series = ctx.data.series ?? [];
4610
+ }
4611
+ if (!picked) return drawNothing(g, ctx, { message: ctx.t(WAITING) });
4612
+ if (picked.error) return drawNothing(g, ctx, { message: ctx.t(BAD_PATH) + picked.error });
4613
+ if (!picked.found) return drawNothing(g, ctx, { message: ctx.t(options.select.trim() ? NOT_FOUND : CHOOSE), hints: picked.hints });
4614
+ const tone = toneFor(picked.value, options.thresholds);
4615
+ const color = toneColor(theme, tone);
4616
+ const labelH = options.label.trim() ? Math.max(10, Math.min(30, Math.round(box.h * 0.14))) : 0;
4617
+ const curve = options.chart !== "none" && series.length >= 2;
4618
+ const curveH = curve ? Math.round(box.h * 0.32) : 0;
4619
+ if (labelH) kit.drawTracked(g, kit.truncate(g, options.label.trim(), box.w, { size: labelH, family: theme.fonts.sansBold }), box.x, box.y + labelH * 0.9, { size: labelH, family: theme.fonts.sansBold, color: theme.colors.inkDim, smallCaps: true, tracking: 1 });
4620
+ const text2 = options.prefix + valueText(picked.value, { decimals: options.decimals, locale: ctx.locale });
4621
+ const unit = options.unit.trim();
4622
+ const top = box.y + (labelH ? labelH * 1.4 : 0);
4623
+ const room = box.h - (top - box.y) - (curveH ? curveH + 6 : 0);
4624
+ const numeric = toNumber(picked.value) !== void 0;
4625
+ const family = numeric ? theme.fonts.monoBold : theme.fonts.sansBold;
4626
+ let size = fit(g, text2, family, box.w * (unit ? 0.78 : 0.98), room * 0.92);
4627
+ let unitSize = Math.max(8, Math.round(size * 0.42));
4628
+ g.font = `${unitSize}px "${theme.fonts.sans}"`;
4629
+ const unitW = unit ? g.measureText(unit).width + size * 0.1 : 0;
4630
+ g.font = `${size}px "${family}"`;
4631
+ let textW = g.measureText(text2).width;
4632
+ if (textW + unitW > box.w) {
4633
+ const k = box.w / (textW + unitW);
4634
+ size = Math.max(8, Math.floor(size * k));
4635
+ unitSize = Math.max(8, Math.round(size * 0.42));
4636
+ g.font = `${size}px "${family}"`;
4637
+ textW = g.measureText(text2).width;
4638
+ }
4639
+ const base2 = top + (room + size * 0.72) / 2;
4640
+ g.fillStyle = color;
4641
+ g.textAlign = "left";
4642
+ g.fillText(text2, box.x, base2);
4643
+ if (unit) {
4644
+ g.font = `${unitSize}px "${theme.fonts.sans}"`;
4645
+ g.fillStyle = theme.colors.inkDim;
4646
+ g.fillText(unit, box.x + textW + size * 0.1, base2);
4647
+ }
4648
+ if (curve) drawCurve(g, ctx, series, { x: box.x, y: box.y + box.h - curveH, w: box.w, h: curveH }, tone ? color : theme.colors.accent);
4649
+ },
4650
+ demo: ({ now }) => ({
4651
+ options: { url: "https://api.open-meteo.com/v1/forecast?latitude=40.4&longitude=-3.7&current=temperature_2m", select: "$.current.temperature_2m", label: "Madrid", unit: "\xB0C", decimals: 1, thresholds: [{ when: ">= 30", tone: "alert" }, { when: ">= 25", tone: "warn" }] },
4652
+ data: { at: now, picked: { found: true, value: 21.4 }, series: Array.from({ length: 24 }, (_, i) => [now - (23 - i) * 36e5, 14 + 7 * Math.sin((i - 6) / 4) + i % 3 * 0.3]) }
4653
+ })
4654
+ });
4655
+ function rowsOf(doc, o) {
4656
+ try {
4657
+ if (o.items.trim()) {
4658
+ const r = readPath(doc, o.items);
4659
+ const items = !r.found ? [] : Array.isArray(r.value) ? r.value : r.value && typeof r.value === "object" ? Object.entries(r.value).map(([k, v]) => ({ key: k, value: v })) : [];
4660
+ if (!r.found) return { rows: null, hints: hintsOf(doc) };
4661
+ const labelSteps = o.itemLabel.trim() ? parsePath(o.itemLabel) : null;
4662
+ const valueSteps = o.itemValue.trim() ? parsePath(o.itemValue) : null;
4663
+ return {
4664
+ rows: items.slice(0, 200).map((it) => ({
4665
+ label: labelSteps ? valueText(readPath(it, labelSteps).value, { decimals: -1, locale: "en" }) : valueText(it, { decimals: -1, locale: "en" }),
4666
+ value: valueSteps ? readPath(it, valueSteps).value : void 0
4667
+ }))
4668
+ };
4669
+ }
4670
+ const fields = o.fields.filter((f) => f.select.trim());
4671
+ if (!fields.length) return { rows: null, hints: hintsOf(doc, 8) };
4672
+ return { rows: fields.map((f) => ({ label: f.label || f.select, value: readPath(doc, f.select).value, ...f.unit ? { unit: f.unit } : {} })) };
4673
+ } catch (err) {
4674
+ return { rows: null, error: err instanceof Error ? err.message : String(err) };
4675
+ }
4676
+ }
4677
+ var jsonList = defineWidget({
4678
+ id: "json-list",
4679
+ name: L("JSON list", "Lista JSON", "JSON-Liste", "JSON \u6E05\u55AE", "JSON \u5217\u8868"),
4680
+ description: L(
4681
+ "Several values from a URL that answers JSON, or from a push: the fields you choose, or the items of a list, each with its value.",
4682
+ "Varios valores de una URL que responda JSON, o de un push: los campos que elijas, o los elementos de una lista, cada uno con su valor.",
4683
+ "Mehrere Werte von einer URL, die JSON liefert, oder aus einem Push: die Felder, die du w\xE4hlst, oder die Eintr\xE4ge einer Liste, jeder mit seinem Wert.",
4684
+ "\u4F86\u81EA\u56DE\u50B3 JSON \u7684 URL \u6216\u63A8\u9001\u7684\u591A\u500B\u6578\u503C\uFF1A\u4F60\u9078\u7684\u6B04\u4F4D\uFF0C\u6216\u6E05\u55AE\u4E2D\u7684\u6BCF\u500B\u9805\u76EE\u53CA\u5176\u6578\u503C\u3002",
4685
+ "\u6765\u81EA\u8FD4\u56DE JSON \u7684 URL \u6216\u63A8\u9001\u7684\u591A\u4E2A\u6570\u503C\uFF1A\u4F60\u9009\u7684\u5B57\u6BB5\uFF0C\u6216\u5217\u8868\u4E2D\u7684\u6BCF\u4E2A\u6761\u76EE\u53CA\u5176\u6570\u503C\u3002"
4686
+ ),
4687
+ icon: "list",
4688
+ category: "dev",
4689
+ tags: ["rest", "api", "json", "webhook", "push"],
4690
+ size: { min: { w: 160, h: 80 }, preferred: { w: 360, h: 240 } },
4691
+ sources: [PUSH_SOURCE],
4692
+ options: t.object({
4693
+ ...sourceOptions(),
4694
+ fields: t.list(
4695
+ t.object({
4696
+ label: t.string({ label: L("Label", "Etiqueta", "Beschriftung", "\u6A19\u7C64", "\u6807\u7B7E") }),
4697
+ select: pathField({ placeholder: "$.current.wind_speed_10m", help: L("$.a.b, items[0].price\u2026", "$.a.b, items[0].price\u2026", "$.a.b, items[0].price\u2026", "$.a.b\u3001items[0].price\u2026", "$.a.b\u3001items[0].price\u2026") }),
4698
+ unit: t.string({ placeholder: "km/h", label: L("Unit", "Unidad", "Einheit", "\u55AE\u4F4D", "\u5355\u4F4D") })
4699
+ }),
4700
+ { max: 30, label: L("Fields", "Campos", "Felder", "\u6B04\u4F4D", "\u5B57\u6BB5"), help: L("One row each. Or leave them empty and give a list below.", "Una fila cada uno. O d\xE9jalos vac\xEDos y da una lista abajo.", "Je eine Zeile. Oder leer lassen und unten eine Liste angeben.", "\u6BCF\u500B\u6B04\u4F4D\u4E00\u5217\u3002\u6216\u7559\u7A7A\uFF0C\u6539\u5728\u4E0B\u65B9\u6307\u5B9A\u6E05\u55AE\u3002", "\u6BCF\u4E2A\u5B57\u6BB5\u4E00\u884C\u3002\u6216\u7559\u7A7A\uFF0C\u6539\u5728\u4E0B\u65B9\u6307\u5B9A\u5217\u8868\u3002") }
4701
+ ),
4702
+ items: pathField({ placeholder: "$.items", label: L("Or a list in it", "O una lista suya", "Oder eine Liste darin", "\u6216\u5176\u4E2D\u7684\u6E05\u55AE", "\u6216\u5176\u4E2D\u7684\u5217\u8868"), help: L("A row per item of the list (or per key of an object) at this path.", "Una fila por elemento de la lista (o por clave de un objeto) en esta ruta.", "Eine Zeile pro Eintrag der Liste (oder pro Schl\xFCssel eines Objekts) unter diesem Pfad.", "\u6B64\u8DEF\u5F91\u4E0B\u6E05\u55AE\u7684\u6BCF\u500B\u9805\u76EE\uFF08\u6216\u7269\u4EF6\u7684\u6BCF\u500B\u9375\uFF09\u5404\u4E00\u5217\u3002", "\u6B64\u8DEF\u5F84\u4E0B\u5217\u8868\u7684\u6BCF\u4E2A\u6761\u76EE\uFF08\u6216\u5BF9\u8C61\u7684\u6BCF\u4E2A\u952E\uFF09\u5404\u4E00\u884C\u3002") }),
4703
+ itemLabel: t.string({ placeholder: "name", label: L("Label of each item", "Etiqueta de cada elemento", "Beschriftung jedes Eintrags", "\u6BCF\u500B\u9805\u76EE\u7684\u6A19\u7C64", "\u6BCF\u4E2A\u6761\u76EE\u7684\u6807\u7B7E"), help: L("A path inside the item (name, user.login; key for an object's keys).", "Una ruta dentro del elemento (name, user.login; key para las claves de un objeto).", "Ein Pfad im Eintrag (name, user.login; key f\xFCr die Schl\xFCssel eines Objekts).", "\u9805\u76EE\u5167\u7684\u8DEF\u5F91\uFF08name\u3001user.login\uFF1B\u7269\u4EF6\u7684\u9375\u7528 key\uFF09\u3002", "\u6761\u76EE\u5185\u7684\u8DEF\u5F84\uFF08name\u3001user.login\uFF1B\u5BF9\u8C61\u7684\u952E\u7528 key\uFF09\u3002") }),
4704
+ itemValue: t.string({ placeholder: "price", label: L("Value of each item", "Valor de cada elemento", "Wert jedes Eintrags", "\u6BCF\u500B\u9805\u76EE\u7684\u6578\u503C", "\u6BCF\u4E2A\u6761\u76EE\u7684\u6570\u503C"), help: L("A path inside the item; empty: only the label.", "Una ruta dentro del elemento; vac\xEDa: solo la etiqueta.", "Ein Pfad im Eintrag; leer: nur die Beschriftung.", "\u9805\u76EE\u5167\u7684\u8DEF\u5F91\uFF1B\u7559\u7A7A\uFF1A\u53EA\u986F\u793A\u6A19\u7C64\u3002", "\u6761\u76EE\u5185\u7684\u8DEF\u5F84\uFF1B\u7559\u7A7A\uFF1A\u53EA\u663E\u793A\u6807\u7B7E\u3002") }),
4705
+ ...formatOptions(),
4706
+ ...listOptions()
4707
+ }),
4708
+ intervalMs: 6e4,
4709
+ timeoutMs: 65e3,
4710
+ async fetch({ options, signal }) {
4711
+ if (options.push.trim() || !options.url.trim()) return null;
4712
+ return { at: Date.now(), ...rowsOf(await requestJson(options, signal), options) };
4713
+ },
4714
+ render(g, ctx) {
4715
+ const { box, options, theme, kit, now, sources } = ctx;
4716
+ let d = null;
4717
+ if (options.push.trim()) {
4718
+ const p = pushedDoc(sources, options.push, now);
4719
+ if (!p.found) return drawNothing(g, ctx, { message: ctx.t(NO_PUSH).replace("{name}", options.push.trim()) });
4720
+ d = rowsOf(p.doc, options);
4721
+ } else if (!options.url.trim()) return drawNothing(g, ctx, { message: ctx.t(NO_SOURCE) });
4722
+ else d = ctx.data ?? null;
4723
+ if (!d) return drawNothing(g, ctx, { message: ctx.t(WAITING) });
4724
+ if (d.error) return drawNothing(g, ctx, { message: ctx.t(BAD_PATH) + d.error });
4725
+ if (!d.rows) return drawNothing(g, ctx, { message: ctx.t(options.items.trim() ? NOT_FOUND : CHOOSE), hints: d.hints });
4726
+ const rows = d.rows;
4727
+ if (!rows.length) return drawEmpty(g, ctx, ctx.t(L("The list is empty", "La lista est\xE1 vac\xEDa", "Die Liste ist leer", "\u6E05\u55AE\u662F\u7A7A\u7684", "\u5217\u8868\u4E3A\u7A7A")));
4728
+ const plan = listLayout(box, rows.length, options, { sizes: { "one-line": { min: 18, max: 44 } }, minRows: 2 });
4729
+ const ts = plan.textSize;
4730
+ plan.rows.forEach((row, i) => {
4731
+ const r = rows[i];
4732
+ const base2 = row.y + plan.rowH * 0.5 + ts * 0.36;
4733
+ const hasValue = r.value !== void 0;
4734
+ const value = hasValue ? formatValue(r.value, { decimals: options.decimals, prefix: options.prefix, unit: r.unit ?? options.unit, locale: ctx.locale }) : "";
4735
+ const vfont = { size: ts, family: toNumber(r.value) !== void 0 ? theme.fonts.monoBold : theme.fonts.sansBold, color: toneColor(theme, toneFor(r.value, options.thresholds)) };
4736
+ const vw = value ? Math.min(box.w * 0.6, kit.measureTracked(g, value, vfont)) : 0;
4737
+ const shown = value ? kit.truncate(g, value, vw, vfont) : "";
4738
+ if (shown) kit.drawTracked(g, shown, box.x + box.w, base2, { ...vfont, align: "right" });
4739
+ const lfont = { size: ts, family: theme.fonts.sans, color: hasValue ? theme.colors.inkDim : theme.colors.ink };
4740
+ kit.drawTracked(g, kit.truncate(g, r.label, Math.max(1, box.w - vw - ts * 0.6), lfont), box.x, base2, lfont);
4741
+ });
4742
+ drawMore(g, ctx, plan);
4743
+ },
4744
+ demo: () => ({
4745
+ options: { url: "https://api.open-meteo.com/v1/forecast?latitude=40.4&longitude=-3.7&current=temperature_2m,relative_humidity_2m,wind_speed_10m", fields: [{ label: "Temperature", select: "$.current.temperature_2m", unit: "\xB0C" }, { label: "Humidity", select: "$.current.relative_humidity_2m", unit: "%" }, { label: "Wind", select: "$.current.wind_speed_10m", unit: "km/h" }], thresholds: [{ when: ">= 80", tone: "info" }] },
4746
+ data: { at: 0, rows: [{ label: "Temperature", value: 21.4, unit: "\xB0C" }, { label: "Humidity", value: 83, unit: "%" }, { label: "Wind", value: 12.6, unit: "km/h" }] }
4747
+ })
4748
+ });
4749
+ var MAX_SLOTS = 40;
4750
+ function fillTemplate(template, doc, o) {
4751
+ let slots = 0;
4752
+ return template.replace(/\{\{|\}\}|\{([^{}\n]{1,300})\}/g, (m, path) => {
4753
+ if (m === "{{") return "{";
4754
+ if (m === "}}") return "}";
4755
+ if (++slots > MAX_SLOTS) return m;
4756
+ try {
4757
+ const r = readPath(doc, path);
4758
+ return r.found ? Array.isArray(r.value) && /\*/.test(path) ? r.value.map((v) => valueText(v, o)).join(", ") : valueText(r.value, o) : "\u2014";
4759
+ } catch {
4760
+ return m;
4761
+ }
4762
+ });
4763
+ }
4764
+ var jsonText = defineWidget({
4765
+ id: "json-text",
4766
+ name: L("JSON text", "Texto JSON", "JSON-Text", "JSON \u6587\u5B57", "JSON \u6587\u5B57"),
4767
+ description: L(
4768
+ 'A sentence with values from a URL that answers JSON, or from a push: "Backup OK at 03:12", "Deploy #812: passed".',
4769
+ "Una frase con valores de una URL que responda JSON, o de un push: \xABCopia OK a las 03:12\xBB, \xABDespliegue #812: correcto\xBB.",
4770
+ "Ein Satz mit Werten von einer URL, die JSON liefert, oder aus einem Push: \u201EBackup OK um 03:12\u201C, \u201EDeployment #812: bestanden\u201C.",
4771
+ "\u4E00\u53E5\u8A71\uFF0C\u5176\u4E2D\u7684\u6578\u503C\u4F86\u81EA\u56DE\u50B3 JSON \u7684 URL \u6216\u63A8\u9001\uFF1A\u300C\u5099\u4EFD\u5B8C\u6210 03:12\u300D\u3001\u300C\u90E8\u7F72 #812\uFF1A\u901A\u904E\u300D\u3002",
4772
+ "\u4E00\u53E5\u8BDD\uFF0C\u5176\u4E2D\u7684\u6570\u503C\u6765\u81EA\u8FD4\u56DE JSON \u7684 URL \u6216\u63A8\u9001\uFF1A\u201C\u5907\u4EFD\u5B8C\u6210 03:12\u201D\u3001\u201C\u90E8\u7F72 #812\uFF1A\u901A\u8FC7\u201D\u3002"
4773
+ ),
4774
+ icon: "text-quote",
4775
+ category: "dev",
4776
+ tags: ["rest", "api", "json", "webhook", "push"],
4777
+ size: { min: { w: 120, h: 60 }, preferred: { w: 400, h: 160 } },
4778
+ sources: [PUSH_SOURCE],
4779
+ options: t.object({
4780
+ ...sourceOptions(),
4781
+ template: t.string({
4782
+ default: "{$.text}",
4783
+ multiline: true,
4784
+ label: L("Text", "Texto", "Text", "\u6587\u5B57", "\u6587\u5B57"),
4785
+ help: L(
4786
+ "Paths in braces are filled in: Backup {$.status} at {$.time}. {$.items[*].name} lists them all. {{ and }} write braces.",
4787
+ "Las rutas entre llaves se rellenan: Copia {$.status} a las {$.time}. {$.items[*].name} las enumera todas. {{ y }} escriben llaves.",
4788
+ "Pfade in geschweiften Klammern werden ersetzt: Backup {$.status} um {$.time}. {$.items[*].name} z\xE4hlt alle auf. {{ und }} schreiben Klammern.",
4789
+ "\u5927\u62EC\u865F\u4E2D\u7684\u8DEF\u5F91\u6703\u88AB\u586B\u5165\uFF1A\u5099\u4EFD {$.status}\uFF0C\u6642\u9593 {$.time}\u3002{$.items[*].name} \u6703\u5168\u90E8\u5217\u51FA\u3002{{ \u548C }} \u8868\u793A\u5927\u62EC\u865F\u672C\u8EAB\u3002",
4790
+ "\u5927\u62EC\u53F7\u4E2D\u7684\u8DEF\u5F84\u4F1A\u88AB\u586B\u5165\uFF1A\u5907\u4EFD {$.status}\uFF0C\u65F6\u95F4 {$.time}\u3002{$.items[*].name} \u4F1A\u5168\u90E8\u5217\u51FA\u3002{{ \u548C }} \u8868\u793A\u5927\u62EC\u53F7\u672C\u8EAB\u3002"
4791
+ )
4792
+ }),
4793
+ colorFrom: t.string({ advanced: true, placeholder: "$.status", label: L("Colour from", "Color seg\xFAn", "Farbe nach", "\u984F\u8272\u4F9D\u64DA", "\u989C\u8272\u4F9D\u636E"), help: L("The path whose value the colours below look at.", "La ruta cuyo valor miran los colores de abajo.", "Der Pfad, dessen Wert die Farben unten pr\xFCfen.", "\u4E0B\u65B9\u984F\u8272\u898F\u5247\u6240\u53C3\u8003\u7684\u8DEF\u5F91\u3002", "\u4E0B\u65B9\u989C\u8272\u89C4\u5219\u6240\u53C2\u8003\u7684\u8DEF\u5F84\u3002") }),
4794
+ decimals: formatOptions().decimals,
4795
+ thresholds: formatOptions().thresholds,
4796
+ maxSize: t.integer({ default: 64, min: 10, max: 300, unit: "px", slider: true, label: L("Largest letter size", "Tama\xF1o m\xE1ximo de letra", "Gr\xF6\xDFte Schriftgr\xF6\xDFe", "\u6700\u5927\u5B57\u9AD4\u5927\u5C0F", "\u6700\u5927\u5B57\u53F7") }),
4797
+ align: t.enum(["left", "center", "right"], { label: L("Alignment", "Alineaci\xF3n", "Ausrichtung", "\u5C0D\u9F4A", "\u5BF9\u9F50"), labels: { left: L("Left", "Izquierda", "Links", "\u9760\u5DE6", "\u5DE6\u5BF9\u9F50"), center: L("Centre", "Centro", "Mitte", "\u7F6E\u4E2D", "\u5C45\u4E2D"), right: L("Right", "Derecha", "Rechts", "\u9760\u53F3", "\u53F3\u5BF9\u9F50") } })
4798
+ }),
4799
+ intervalMs: 6e4,
4800
+ timeoutMs: 65e3,
4801
+ async fetch({ options, signal, locale }) {
4802
+ if (options.push.trim() || !options.url.trim()) return null;
4803
+ return textOf(await requestJson(options, signal), options, locale, Date.now());
4804
+ },
4805
+ render(g, ctx) {
4806
+ const { box, options, theme, kit, now, sources } = ctx;
4807
+ let d;
4808
+ if (options.push.trim()) {
4809
+ const p = pushedDoc(sources, options.push, now);
4810
+ if (!p.found) return drawNothing(g, ctx, { message: ctx.t(NO_PUSH).replace("{name}", options.push.trim()) });
4811
+ d = textOf(p.doc, options, ctx.locale, p.at ?? now);
4812
+ } else if (!options.url.trim()) return drawNothing(g, ctx, { message: ctx.t(NO_SOURCE) });
4813
+ else d = ctx.data ?? null;
4814
+ if (!d) return drawNothing(g, ctx, { message: ctx.t(WAITING) });
4815
+ const family = theme.fonts.sans;
4816
+ const paragraphs = d.text.split("\n");
4817
+ let size = options.maxSize;
4818
+ let lines = [];
4819
+ for (; ; size -= 2) {
4820
+ lines = paragraphs.flatMap((p) => p.trim() ? kit.wrapLines(g, p, box.w, 50, { size, family }) : [""]);
4821
+ if (size - 2 < 10 || lines.length * size * 1.2 <= box.h && !lines.some((l) => l.endsWith("\u2026"))) break;
4822
+ }
4823
+ const lh = size * 1.2;
4824
+ const top = box.y + Math.max(0, box.h - lines.length * lh) / 2 + size * 0.85;
4825
+ const x = options.align === "center" ? box.x + box.w / 2 : options.align === "right" ? box.x + box.w : box.x;
4826
+ lines.forEach((l, i) => kit.drawTracked(g, l, x, top + i * lh, { size, family, color: toneColor(theme, d.tone), align: options.align }));
4827
+ },
4828
+ demo: ({ now }) => ({
4829
+ options: { url: "https://nas.local/backup/status.json", template: "Backup {$.status} \xB7 {$.size}", thresholds: [{ when: "!= ok", tone: "alert" }], colorFrom: "$.status" },
4830
+ data: { at: now, text: "Backup ok \xB7 12.4 GB" }
4831
+ })
4832
+ });
4833
+ function textOf(doc, o, locale, at) {
4834
+ const text2 = fillTemplate(o.template, doc, { decimals: o.decimals, locale });
4835
+ let tone;
4836
+ if (o.thresholds.length) {
4837
+ let v = text2;
4838
+ try {
4839
+ if (o.colorFrom.trim()) v = readPath(doc, o.colorFrom).value;
4840
+ } catch {
4841
+ v = void 0;
4842
+ }
4843
+ tone = toneFor(v, o.thresholds);
4844
+ }
4845
+ return { at, text: text2, ...tone ? { tone } : {} };
4846
+ }
4847
+
4848
+ // plugins/core/src/push.ts
4849
+ var L2 = (en, es, de, hant, hans) => ({ en, es, de, "zh-Hant": hant, "zh-Hans": hans });
4850
+ var pushSource = defineSource({
4851
+ id: "push",
4852
+ name: L2("Pushes", "Pushes", "Pushes", "\u63A8\u9001", "\u63A8\u9001"),
4853
+ description: L2(
4854
+ "What scripts send to POST /api/push/<name>, for the Push widget and the JSON ones.",
4855
+ "Lo que los scripts env\xEDan a POST /api/push/<nombre>, para el widget Push y los JSON.",
4856
+ "Was Skripte an POST /api/push/<name> senden, f\xFCr das Push-Widget und die JSON-Widgets.",
4857
+ "\u8173\u672C\u50B3\u9001\u5230 POST /api/push/<\u540D\u7A31> \u7684\u5167\u5BB9\uFF0C\u4F9B\u63A8\u9001\u5C0F\u5DE5\u5177\u8207 JSON \u5C0F\u5DE5\u5177\u4F7F\u7528\u3002",
4858
+ "\u811A\u672C\u53D1\u9001\u5230 POST /api/push/<\u540D\u79F0> \u7684\u5185\u5BB9\uFF0C\u4F9B\u63A8\u9001\u5C0F\u7EC4\u4EF6\u548C JSON \u5C0F\u7EC4\u4EF6\u4F7F\u7528\u3002"
4859
+ ),
4860
+ watch(_ctx, emit) {
4861
+ emit(pushes.snapshot());
4862
+ return pushes.subscribe(emit);
4863
+ },
4864
+ choices: {
4865
+ names: (d) => Object.keys(d?.hooks ?? {}).map((value) => ({ value }))
4866
+ },
4867
+ demo: ({ now }) => demoPushes(now)
4868
+ });
4869
+ var LEVELS = ["ok", "info", "warn", "alert", "critical"];
4870
+ var str = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : void 0;
4871
+ function viewOf(payload) {
4872
+ if (typeof payload === "string") return { text: payload };
4873
+ if (typeof payload === "number" || typeof payload === "boolean") return { value: payload };
4874
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return {};
4875
+ const p = payload;
4876
+ const level = typeof p.level === "string" ? p.level.toLowerCase() : void 0;
4877
+ const text2 = str(p.text) ?? str(p.message);
4878
+ const title = str(p.title);
4879
+ const unit = str(p.unit);
4880
+ return {
4881
+ ...title ? { title } : {},
4882
+ ...p.value !== void 0 ? { value: p.value } : {},
4883
+ ...text2 !== void 0 ? { text: text2 } : {},
4884
+ ...unit ? { unit } : {},
4885
+ ...LEVELS.includes(level) ? { level } : {}
4886
+ };
4887
+ }
4888
+ var entryOf = (sources, name) => sources[PUSH_SOURCE]?.hooks?.[name.trim()];
4889
+ var push = defineWidget({
4890
+ id: "push",
4891
+ name: L2("Push", "Push", "Push", "\u63A8\u9001", "\u63A8\u9001"),
4892
+ description: L2(
4893
+ "What a script, cron, CI or Home Assistant sends to POST /api/push/<name>: a value, a text and a level. An alert keeps the tile; it goes away when its time runs out.",
4894
+ "Lo que un script, cron, la CI o Home Assistant env\xEDa a POST /api/push/<nombre>: un valor, un texto y un nivel. Una alerta se queda la tesela; se quita sola cuando caduca.",
4895
+ "Was ein Skript, Cron, CI oder Home Assistant an POST /api/push/<name> sendet: ein Wert, ein Text und eine Stufe. Ein Alarm beh\xE4lt die Kachel; er verschwindet, wenn seine Zeit abl\xE4uft.",
4896
+ "\u8173\u672C\u3001cron\u3001CI \u6216 Home Assistant \u50B3\u9001\u5230 POST /api/push/<\u540D\u7A31> \u7684\u5167\u5BB9\uFF1A\u6578\u503C\u3001\u6587\u5B57\u8207\u7B49\u7D1A\u3002\u8B66\u5831\u6703\u4F54\u4F4F\u65B9\u683C\uFF0C\u5230\u671F\u5F8C\u81EA\u52D5\u6D88\u5931\u3002",
4897
+ "\u811A\u672C\u3001cron\u3001CI \u6216 Home Assistant \u53D1\u9001\u5230 POST /api/push/<\u540D\u79F0> \u7684\u5185\u5BB9\uFF1A\u6570\u503C\u3001\u6587\u5B57\u548C\u7EA7\u522B\u3002\u8B66\u62A5\u4F1A\u5360\u4F4F\u683C\u5B50\uFF0C\u5230\u671F\u540E\u81EA\u52A8\u6D88\u5931\u3002"
4898
+ ),
4899
+ icon: "webhook",
4900
+ category: "dev",
4901
+ tags: ["webhook", "push", "curl", "script", "cron", "ci"],
4902
+ size: { min: { w: 120, h: 60 }, preferred: { w: 360, h: 200 } },
4903
+ sources: [PUSH_SOURCE],
4904
+ options: t.object({
4905
+ name: t.string({ choices: { source: PUSH_SOURCE, list: "names" }, placeholder: "backup", label: L2("Push name", "Nombre del push", "Push-Name", "\u63A8\u9001\u540D\u7A31", "\u63A8\u9001\u540D\u79F0"), help: L2("Set up push names, with their URL and token, in Settings \u2192 Push.", "Los nombres, con su URL y su token, se crean en Ajustes \u2192 Push.", "Push-Namen mit URL und Token legst du unter Einstellungen \u2192 Push an.", "\u63A8\u9001\u540D\u7A31\u53CA\u5176 URL \u548C\u6B0A\u6756\u5728\u300C\u8A2D\u5B9A \u2192 \u63A8\u9001\u300D\u4E2D\u5EFA\u7ACB\u3002", "\u63A8\u9001\u540D\u79F0\u53CA\u5176 URL \u548C\u4EE4\u724C\u5728\u201C\u8BBE\u7F6E \u2192 \u63A8\u9001\u201D\u4E2D\u521B\u5EFA\u3002") }),
4906
+ unit: t.string({ placeholder: "\xB0C", label: L2("Unit", "Unidad", "Einheit", "\u55AE\u4F4D", "\u5355\u4F4D"), help: L2("When the push doesn't say one.", "Si el push no trae una.", "Wenn der Push keine mitbringt.", "\u63A8\u9001\u5167\u5BB9\u672A\u6307\u5B9A\u55AE\u4F4D\u6642\u4F7F\u7528\u3002", "\u63A8\u9001\u5185\u5BB9\u672A\u6307\u5B9A\u5355\u4F4D\u65F6\u4F7F\u7528\u3002") }),
4907
+ decimals: t.integer({ default: -1, min: -1, max: 6, label: L2("Decimals", "Decimales", "Nachkommastellen", "\u5C0F\u6578\u4F4D\u6578", "\u5C0F\u6570\u4F4D\u6570"), help: L2("-1: as it comes (up to 2).", "-1: tal como viene (hasta 2).", "-1: wie geliefert (bis zu 2).", "-1\uFF1A\u4F9D\u539F\u59CB\u503C\uFF08\u6700\u591A 2 \u4F4D\uFF09\u3002", "-1\uFF1A\u6309\u539F\u59CB\u503C\uFF08\u6700\u591A 2 \u4F4D\uFF09\u3002") }),
4908
+ showAge: t.boolean({ default: true, label: L2("Show how long ago", "Mostrar hace cu\xE1nto", "Anzeigen, wie lange her", "\u986F\u793A\u591A\u4E45\u4EE5\u524D", "\u663E\u793A\u591A\u4E45\u4EE5\u524D") })
4909
+ }),
4910
+ redraw: "minute",
4911
+ visible: ({ options, sources, now }) => {
4912
+ const e = entryOf(sources, options.name);
4913
+ return !e || live(e, now);
4914
+ },
4915
+ urgent: ({ options, sources, now }) => {
4916
+ const e = entryOf(sources, options.name);
4917
+ const level = live(e, now) ? viewOf(e.payload).level : void 0;
4918
+ return level === "alert" || level === "critical";
4919
+ },
4920
+ alerts: ({ options, sources, now }) => {
4921
+ const e = entryOf(sources, options.name);
4922
+ if (!live(e, now)) return [];
4923
+ const v = viewOf(e.payload);
4924
+ if (v.level !== "critical") return [];
4925
+ const title = v.title ?? v.text ?? options.name;
4926
+ const alert = { id: `push-${options.name.trim()}-${e.at}`, level: "critical", title, icon: "webhook", source: "Push", ...e.expiresAt ? { expiresAt: e.expiresAt } : {} };
4927
+ if (v.title && v.text) alert.text = v.text;
4928
+ return [alert];
4929
+ },
4930
+ render(g, ctx) {
4931
+ const { box, options, theme, kit, now, sources, fmt } = ctx;
4932
+ const name = options.name.trim();
4933
+ const small = Math.max(10, Math.min(24, Math.round(box.h / 7)));
4934
+ const dimFont = { size: small, family: theme.fonts.sans, color: theme.colors.inkDim };
4935
+ if (!name) return void kit.drawTracked(g, kit.truncate(g, ctx.t(L2("Choose a push name", "Elige un nombre de push", "W\xE4hle einen Push-Namen", "\u8ACB\u9078\u64C7\u63A8\u9001\u540D\u7A31", "\u8BF7\u9009\u62E9\u63A8\u9001\u540D\u79F0")), box.w, dimFont), box.x, box.y + small * 1.1, dimFont);
4936
+ const e = entryOf(sources, name);
4937
+ if (!e) {
4938
+ kit.drawTracked(g, kit.truncate(g, ctx.t(L2("Waiting for a push", "Esperando un push", "Warte auf einen Push", "\u7B49\u5F85\u63A8\u9001", "\u7B49\u5F85\u63A8\u9001")), box.w, dimFont), box.x, box.y + small * 1.1, dimFont);
4939
+ const mono = { size: Math.max(9, Math.round(small * 0.8)), family: theme.fonts.mono, color: theme.colors.inkFaint };
4940
+ kit.drawTracked(g, kit.truncate(g, `POST /api/push/${name}`, box.w, mono), box.x, box.y + small * 2.5, mono);
4941
+ return;
4942
+ }
4943
+ const v = viewOf(e.payload);
4944
+ const tone = v.level === "critical" ? "alert" : v.level;
4945
+ const color = toneColor(theme, tone);
4946
+ let y = box.y;
4947
+ const footer = options.showAge ? small * 1.3 : 0;
4948
+ if (v.title) {
4949
+ const tf = { size: small, family: theme.fonts.sansBold, color: theme.colors.inkDim, smallCaps: true, tracking: 1 };
4950
+ kit.drawTracked(g, kit.truncate(g, v.title, box.w, tf), box.x, y + small * 0.9, tf);
4951
+ y += small * 1.4;
4952
+ }
4953
+ const room = box.y + box.h - footer - y;
4954
+ const hasValue = v.value !== void 0;
4955
+ const hasText = !!v.text?.trim();
4956
+ if (hasValue) {
4957
+ const valueH = hasText ? room * 0.62 : room;
4958
+ const text2 = valueText(v.value, { decimals: options.decimals, locale: ctx.locale });
4959
+ const unit = (v.unit ?? options.unit).trim();
4960
+ const numeric = toNumber(v.value) !== void 0;
4961
+ const family = numeric ? theme.fonts.monoBold : theme.fonts.sansBold;
4962
+ let size = Math.min(valueH * 0.9, 400);
4963
+ g.font = `${size}px "${family}"`;
4964
+ const unitK = 0.42;
4965
+ const full = () => g.measureText(text2).width + (unit ? g.measureText(unit).width * unitK + size * 0.1 : 0);
4966
+ const w = full();
4967
+ if (w > box.w) size = Math.max(8, Math.floor(size * box.w / w));
4968
+ g.font = `${size}px "${family}"`;
4969
+ const tw = g.measureText(text2).width;
4970
+ const base2 = y + (valueH + size * 0.72) / 2;
4971
+ g.fillStyle = color;
4972
+ g.textAlign = "left";
4973
+ g.fillText(text2, box.x, base2);
4974
+ if (unit) {
4975
+ g.font = `${Math.max(8, Math.round(size * unitK))}px "${theme.fonts.sans}"`;
4976
+ g.fillStyle = theme.colors.inkDim;
4977
+ g.fillText(unit, box.x + tw + size * 0.1, base2);
4978
+ }
4979
+ y += valueH;
4980
+ }
4981
+ if (hasText) {
4982
+ const h = hasValue ? room * 0.38 : room;
4983
+ let size = Math.min(hasValue ? h * 0.8 : 64, h);
4984
+ let lines = [];
4985
+ for (; ; size -= 2) {
4986
+ lines = kit.wrapLines(g, v.text, box.w, hasValue ? 2 : 6, { size, family: theme.fonts.sans });
4987
+ if (size - 2 < 10 || lines.length * size * 1.2 <= h) break;
4988
+ }
4989
+ const lh = size * 1.2;
4990
+ const top = y + Math.max(0, h - lines.length * lh) / 2 + size * 0.85;
4991
+ const tc = hasValue ? theme.colors.ink : color;
4992
+ lines.forEach((l, i) => kit.drawTracked(g, l, box.x, top + i * lh, { size, family: theme.fonts.sans, color: tc }));
4993
+ }
4994
+ if (!hasValue && !hasText) {
4995
+ const raw = formatValue(e.payload, { decimals: options.decimals, prefix: "", unit: "", locale: ctx.locale });
4996
+ kit.drawTracked(g, kit.truncate(g, raw, box.w, { size: small, family: theme.fonts.mono }), box.x, y + small * 1.2, { size: small, family: theme.fonts.mono, color: theme.colors.ink });
4997
+ }
4998
+ if (footer) {
4999
+ const af = { size: Math.max(9, Math.round(small * 0.8)), family: theme.fonts.sans, color: theme.colors.inkFaint };
5000
+ kit.drawTracked(g, fmt.ago(e.at), box.x + box.w, box.y + box.h - af.size * 0.3, { ...af, align: "right" });
5001
+ }
5002
+ },
5003
+ demo: ({ now }) => ({ options: { name: "backup" }, sources: { [PUSH_SOURCE]: demoPushes(now) } })
5004
+ });
5005
+ function demoPushes(now) {
5006
+ const at = now - 25 * 6e4;
5007
+ const backup = { title: "Backup", value: "OK", text: "nas \u2192 b2 \xB7 12.4 GB", level: "ok" };
5008
+ const garage = { temp: 21.4, humidity: 48 };
5009
+ return {
5010
+ hooks: {
5011
+ backup: { at, payload: backup, history: [{ at, payload: backup }] },
5012
+ garage: { at: now - 6e4, payload: garage, history: Array.from({ length: 24 }, (_, i) => ({ at: now - (23 - i) * 36e5, payload: { temp: 18 + 4 * Math.sin(i / 4), humidity: 48 } })) }
5013
+ }
5014
+ };
5015
+ }
5016
+
5017
+ // plugins/core/src/index.ts
5018
+ function fit2(g, text2, family, w, h, max = 400) {
5019
+ let size = Math.min(max, h);
5020
+ g.font = `${size}px "${family}"`;
5021
+ const width = g.measureText(text2).width;
5022
+ if (width > w) size = Math.floor(size * w / width);
5023
+ return Math.max(8, size);
5024
+ }
3851
5025
  function isoWeek(d) {
3852
5026
  const t0 = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
3853
5027
  t0.setUTCDate(t0.getUTCDate() + 4 - (t0.getUTCDay() || 7));
@@ -3907,7 +5081,7 @@ var clock = defineWidget({
3907
5081
  const markFirst = !!mark && full.startsWith(mark);
3908
5082
  const dateText = options.showDate ? new Date(at).toLocaleDateString(locale, DATE_FORMATS[options.dateFormat]) : "";
3909
5083
  const dateH = options.showDate ? Math.min(box.h * 0.2, 40) : 0;
3910
- const size = fit(g, text2, theme.fonts.monoBold, box.w * (mark ? 0.76 : 0.96), (box.h - dateH * 1.3) * 0.95);
5084
+ const size = fit2(g, text2, theme.fonts.monoBold, box.w * (mark ? 0.76 : 0.96), (box.h - dateH * 1.3) * 0.95);
3911
5085
  const color = options.color === "accent" ? theme.colors.accent : options.color === "dim" ? theme.colors.inkDim : theme.colors.ink;
3912
5086
  const block = size * 0.78 + (dateH ? dateH * 1.4 : 0);
3913
5087
  const base2 = box.y + (box.h - block) / 2 + size * 0.78;
@@ -3931,7 +5105,7 @@ var clock = defineWidget({
3931
5105
  const x = options.align === "left" ? box.x : options.align === "right" ? box.x + box.w : box.x + box.w / 2;
3932
5106
  g.textAlign = options.align;
3933
5107
  if (dateH) {
3934
- const ds = Math.min(dateH, fit(g, dateText, theme.fonts.sans, box.w * 0.96, dateH));
5108
+ const ds = Math.min(dateH, fit2(g, dateText, theme.fonts.sans, box.w * 0.96, dateH));
3935
5109
  g.font = `${ds}px "${theme.fonts.sans}"`;
3936
5110
  g.fillStyle = theme.colors.inkDim;
3937
5111
  g.fillText(dateText, x, base2 + dateH * 1.35);
@@ -3964,7 +5138,7 @@ var date = defineWidget({
3964
5138
  const weekdayColor = { accent: c.accent, ink: c.ink, dim: c.inkDim, alert: c.alert }[options.weekdayColor];
3965
5139
  kit.drawTracked(g, weekday, box.x + box.w / 2, box.y + top, { size: top, family: theme.fonts.sansBold, color: weekdayColor, align: "center", smallCaps: true, tracking: 2 });
3966
5140
  const num = String(d.getDate());
3967
- const size = fit(g, num, theme.fonts.sansBold, box.w * 0.9, box.h * 0.56);
5141
+ const size = fit2(g, num, theme.fonts.sansBold, box.w * 0.9, box.h * 0.56);
3968
5142
  g.font = `${size}px "${theme.fonts.sansBold}"`;
3969
5143
  g.fillStyle = theme.colors.ink;
3970
5144
  g.textAlign = "center";
@@ -3974,7 +5148,7 @@ var date = defineWidget({
3974
5148
  const ms = Math.min(top, box.h * 0.13);
3975
5149
  let line = month;
3976
5150
  if (options.showWeekNumber) line += ` \xB7 ${tr({ en: "wk {n}", es: "sem {n}", de: "KW {n}", "zh-Hant": "\u7B2C {n} \u9031", "zh-Hans": "\u7B2C {n} \u5468" }).replace("{n}", String(isoWeek(d)))}`;
3977
- const ls = Math.min(ms, fit(g, line, theme.fonts.sans, box.w * 0.96, ms));
5151
+ const ls = Math.min(ms, fit2(g, line, theme.fonts.sans, box.w * 0.96, ms));
3978
5152
  g.font = `${ls}px "${theme.fonts.sans}"`;
3979
5153
  g.fillStyle = theme.colors.inkDim;
3980
5154
  g.textAlign = "center";
@@ -4024,7 +5198,7 @@ var text = defineWidget({
4024
5198
  timeoutMs: 1e4,
4025
5199
  async fetch({ options, signal }) {
4026
5200
  if (!options.file.trim()) return { text: null };
4027
- const body = await readFile(expandHome(options.file), { encoding: "utf8", signal });
5201
+ const body = await readFile2(expandHome(options.file), { encoding: "utf8", signal });
4028
5202
  return { text: body.slice(0, MAX_FILE_CHARS).replace(/\s+$/, "") };
4029
5203
  },
4030
5204
  empty: ({ options, data }) => !noteOf(options, data).trim(),
@@ -4109,7 +5283,7 @@ async function nextInFolder(dir) {
4109
5283
  if (!files.length) return null;
4110
5284
  const i = ((turns.get(dir) ?? -1) + 1) % files.length;
4111
5285
  turns.set(dir, i);
4112
- return join6(dir, files[i]);
5286
+ return join7(dir, files[i]);
4113
5287
  }
4114
5288
  function imageUrl(src, now, addTimestamp = false) {
4115
5289
  const filled = src.replace(/\{now\}/g, String(now)).replace(/\{unix\}/g, String(Math.floor(now / 1e3)));
@@ -4118,8 +5292,8 @@ function imageUrl(src, now, addTimestamp = false) {
4118
5292
  u.searchParams.set("t", String(now));
4119
5293
  return u.href;
4120
5294
  }
4121
- function placeImage(box, w, h, fit2, position) {
4122
- const s = fit2 === "cover" ? Math.max(box.w / w, box.h / h) : Math.min(box.w / w, box.h / h);
5295
+ function placeImage(box, w, h, fit3, position) {
5296
+ const s = fit3 === "cover" ? Math.max(box.w / w, box.h / h) : Math.min(box.w / w, box.h / h);
4123
5297
  const dw = w * s, dh = h * s;
4124
5298
  const fx = position === "left" ? 0 : position === "right" ? 1 : 0.5;
4125
5299
  const fy = position === "top" ? 0 : position === "bottom" ? 1 : 0.5;
@@ -4202,27 +5376,28 @@ var image = defineWidget({
4202
5376
  var src_default = definePlugin({
4203
5377
  id: "core",
4204
5378
  name: { en: "Essentials", es: "B\xE1sicos", de: "Grundlagen", "zh-Hant": "\u57FA\u672C\u5DE5\u5177", "zh-Hans": "\u57FA\u7840\u7EC4\u4EF6" },
4205
- version: "0.2.11",
5379
+ version: "0.2.12",
4206
5380
  languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
4207
5381
  sdk: "^0.2.0",
4208
- // The picture widget reads the image (or folder, or URL) you give it.
5382
+ // The picture widget reads the image (or folder, or URL) you give it; the JSON ones ask the URL you give them.
4209
5383
  permissions: { files: ["user"], network: ["user"] },
4210
- description: { en: "Clock, date, notes, lists and pictures.", es: "Reloj, fecha, notas, listas e im\xE1genes.", de: "Uhr, Datum, Notizen, Listen und Bilder.", "zh-Hant": "\u6642\u9418\u3001\u65E5\u671F\u3001\u4FBF\u689D\u3001\u6E05\u55AE\u548C\u5716\u7247\u3002", "zh-Hans": "\u65F6\u949F\u3001\u65E5\u671F\u3001\u4FBF\u7B7E\u3001\u5217\u8868\u548C\u56FE\u7247\u3002" },
5384
+ description: { en: "Clock, date, notes, lists, pictures, any JSON and pushes from your scripts.", es: "Reloj, fecha, notas, listas, im\xE1genes, cualquier JSON y los push de tus scripts.", de: "Uhr, Datum, Notizen, Listen, Bilder, beliebiges JSON und Pushes deiner Skripte.", "zh-Hant": "\u6642\u9418\u3001\u65E5\u671F\u3001\u4FBF\u689D\u3001\u6E05\u55AE\u3001\u5716\u7247\u3001\u4EFB\u4F55 JSON\uFF0C\u4EE5\u53CA\u8173\u672C\u50B3\u4F86\u7684\u63A8\u9001\u3002", "zh-Hans": "\u65F6\u949F\u3001\u65E5\u671F\u3001\u4FBF\u7B7E\u3001\u5217\u8868\u3001\u56FE\u7247\u3001\u4EFB\u4F55 JSON\uFF0C\u4EE5\u53CA\u811A\u672C\u53D1\u6765\u7684\u63A8\u9001\u3002" },
4211
5385
  author: "Kiosko",
4212
5386
  license: "MIT",
4213
5387
  icon: "box",
4214
- widgets: [clock, date, text, list, image]
5388
+ widgets: [clock, date, text, list, image, jsonValue, jsonList, jsonText, push],
5389
+ sources: [pushSource]
4215
5390
  });
4216
5391
 
4217
5392
  // plugins/legacy/src/index.ts
4218
5393
  import { existsSync as existsSync5, statSync as statSync2 } from "node:fs";
4219
- import { isAbsolute, join as join7 } from "node:path";
5394
+ import { isAbsolute, join as join8 } from "node:path";
4220
5395
  import { pathToFileURL as pathToFileURL3 } from "node:url";
4221
5396
  var loaded = /* @__PURE__ */ new Map();
4222
5397
  function resolveModule(name, dir) {
4223
5398
  const expanded = expandPath(name);
4224
- const base2 = isAbsolute(expanded) ? expanded : join7(expandPath(dir), expanded);
4225
- for (const p of [base2, `${base2}.mjs`, `${base2}.js`, join7(base2, "index.mjs"), join7(base2, "index.js")]) {
5399
+ const base2 = isAbsolute(expanded) ? expanded : join8(expandPath(dir), expanded);
5400
+ for (const p of [base2, `${base2}.mjs`, `${base2}.js`, join8(base2, "index.mjs"), join8(base2, "index.js")]) {
4226
5401
  if (existsSync5(p) && statSync2(p).isFile()) return p;
4227
5402
  }
4228
5403
  return null;
@@ -4298,7 +5473,7 @@ var module2 = defineWidget({
4298
5473
  var src_default2 = definePlugin({
4299
5474
  id: "legacy",
4300
5475
  name: { en: "aimonitor compatibility", es: "Compatibilidad aimonitor", de: "aimonitor-Kompatibilit\xE4t", "zh-Hant": "aimonitor \u76F8\u5BB9\u6027", "zh-Hans": "aimonitor \u517C\u5BB9" },
4301
- version: "0.2.11",
5476
+ version: "0.2.12",
4302
5477
  languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
4303
5478
  sdk: "^0.2.0",
4304
5479
  // Runs the aimonitor modules you point it at, and reads their folder.