burrow-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +594 -2
  3. package/bin/burrow.js +200 -0
  4. package/examples/acme-shop.tunnel.yml +18 -0
  5. package/package.json +45 -4
  6. package/src/access.js +163 -0
  7. package/src/add.js +106 -0
  8. package/src/cloudflare.js +118 -0
  9. package/src/commands.js +386 -0
  10. package/src/completion.js +127 -0
  11. package/src/config-file.js +31 -0
  12. package/src/config.js +82 -0
  13. package/src/dashboard/auth.js +79 -0
  14. package/src/dashboard/data.js +70 -0
  15. package/src/dashboard/logs.js +95 -0
  16. package/src/dashboard/manage.js +102 -0
  17. package/src/dashboard/panels/README.md +50 -0
  18. package/src/dashboard/panels/access.js +218 -0
  19. package/src/dashboard/panels/alerts.js +244 -0
  20. package/src/dashboard/panels/backup.js +193 -0
  21. package/src/dashboard/panels/bulk.js +246 -0
  22. package/src/dashboard/panels/cleanup.js +237 -0
  23. package/src/dashboard/panels/doctor.js +119 -0
  24. package/src/dashboard/panels/health.js +146 -0
  25. package/src/dashboard/panels/history.js +104 -0
  26. package/src/dashboard/panels/hooks.js +86 -0
  27. package/src/dashboard/panels/live.js +153 -0
  28. package/src/dashboard/panels/project-form.js +463 -0
  29. package/src/dashboard/panels/quick-actions.js +133 -0
  30. package/src/dashboard/panels/sessions.js +267 -0
  31. package/src/dashboard/panels/shares.js +280 -0
  32. package/src/dashboard/panels/stats.js +165 -0
  33. package/src/dashboard/panels/updates.js +156 -0
  34. package/src/dashboard/panels/uptime.js +115 -0
  35. package/src/dashboard/panels.js +53 -0
  36. package/src/dashboard/server.js +390 -0
  37. package/src/dashboard/session-store.js +47 -0
  38. package/src/dashboard/totp.js +103 -0
  39. package/src/dashboard/ui.js +454 -0
  40. package/src/doctor.js +342 -0
  41. package/src/edit.js +135 -0
  42. package/src/health-observer.js +81 -0
  43. package/src/history.js +145 -0
  44. package/src/hooks.js +256 -0
  45. package/src/naming.js +38 -0
  46. package/src/open.js +67 -0
  47. package/src/pending.js +72 -0
  48. package/src/process.js +95 -0
  49. package/src/project-form.js +134 -0
  50. package/src/project.js +114 -0
  51. package/src/prune.js +99 -0
  52. package/src/rename-state.js +39 -0
  53. package/src/restart.js +35 -0
  54. package/src/service.js +173 -0
  55. package/src/share-expiry.js +55 -0
  56. package/src/share.js +275 -0
  57. package/src/shell-words.js +284 -0
  58. package/src/stats.js +180 -0
  59. package/src/transfer.js +124 -0
  60. package/src/update.js +254 -0
  61. package/src/uptime.js +91 -0
  62. package/src/watch.js +263 -0
  63. package/src/zones.js +102 -0
@@ -0,0 +1,146 @@
1
+ // Panel: local port health. A dot per hostname shows whether the local port behind it
2
+ // answers, so a dead app (port closed) is told apart from a dead tunnel (cloudflared
3
+ // stopped, or no Cloudflare connections). Reuses the TCP checks of `burrow watch`.
4
+ import { existsSync, readdirSync } from 'node:fs';
5
+ import { stateDir } from '../../config.js';
6
+ import { hostnames, loadProjectFile, DASHBOARD_PROJECT, dashboardProject } from '../../project.js';
7
+ import { readMeta, localProjects } from '../../process.js';
8
+ import { localTargets, tcpOpen } from '../../watch.js';
9
+
10
+ export const order = 20;
11
+ const CACHE_MS = 3000;
12
+ let cache = { at: 0, data: null };
13
+
14
+ function projectFor(project, cfg) {
15
+ if (project === DASHBOARD_PROJECT) return dashboardProject(cfg.dashboardPort);
16
+ const file = readMeta(project)?.file;
17
+ if (!file || !existsSync(file)) return null;
18
+ try { return loadProjectFile(file); } catch { return null; }
19
+ }
20
+
21
+ function knownProjects() {
22
+ let metas = [];
23
+ try { metas = readdirSync(stateDir()).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)); } catch {}
24
+ return [...new Set([DASHBOARD_PROJECT, ...metas, ...localProjects()])].sort();
25
+ }
26
+
27
+ // Same host:port rules as localTargets in watch.js.
28
+ function hostPort(url) {
29
+ let u;
30
+ try { u = new URL(url); } catch { return null; }
31
+ const port = Number(u.port) || { 'http:': 80, 'ws:': 80, 'https:': 443, 'wss:': 443, 'ssh:': 22 }[u.protocol];
32
+ if (!port || !u.hostname) return null;
33
+ return { host: u.hostname.replace(/^\[|\]$/g, ''), port };
34
+ }
35
+
36
+ // { project: [{ service, hostname, targets: [{ host, port, up }], up }] }
37
+ export async function probeAll(cfg, { timeoutMs = 1500, probe = tcpOpen } = {}) {
38
+ const out = {};
39
+ await Promise.all(knownProjects().map(async (project) => {
40
+ const proj = projectFor(project, cfg);
41
+ if (!proj) return;
42
+ let hosts = [];
43
+ try { hosts = cfg.domain ? hostnames(proj, cfg.domain) : []; } catch {}
44
+ // localTargets lists each host:port once; a service may share a port with another.
45
+ const status = new Map();
46
+ await Promise.all(localTargets(project, cfg).map(async (t) => {
47
+ status.set(`${t.host}:${t.port}`, await probe(t.host, t.port, timeoutMs));
48
+ }));
49
+ out[project] = proj.services.map((s) => {
50
+ const mine = [];
51
+ for (const url of [s.url, ...s.paths.map((x) => x.url)]) {
52
+ const t = hostPort(url);
53
+ if (t && status.has(`${t.host}:${t.port}`) && !mine.some((m) => m.host === t.host && m.port === t.port)) {
54
+ mine.push({ ...t, up: status.get(`${t.host}:${t.port}`) });
55
+ }
56
+ }
57
+ return {
58
+ service: s.name,
59
+ hostname: hosts.find((h) => h.service === s.name)?.hostname || null,
60
+ targets: mine,
61
+ up: mine.length ? mine.every((t) => t.up) : null, // null: nothing to probe (e.g. http_status:404)
62
+ };
63
+ });
64
+ }));
65
+ return out;
66
+ }
67
+
68
+ export async function route(ctx) {
69
+ if (ctx.method !== 'GET' || ctx.path !== '/api/health') return false;
70
+ if (Date.now() - cache.at > CACHE_MS || !cache.data) cache = { at: Date.now(), data: await probeAll(ctx.loadConfig()) };
71
+ ctx.json(200, { projects: cache.data, at: cache.at });
72
+ return true;
73
+ }
74
+
75
+ export const html = {
76
+ hostExtras: '<span class="dot" :class="dotClass(p, h)" :title="dotTitle(p, h)" role="img" :aria-label="dotTitle(p, h)"></span>',
77
+ localExtras: '<br><small class="verdict" :class="verdictClass(p)" x-text="verdict(p)"></small>',
78
+ };
79
+
80
+ export const css = `
81
+ .dot{display:inline-block;width:.6rem;height:.6rem;border-radius:50%;background:var(--pico-muted-border-color);flex:none}
82
+ .dot.ok{background:#1f9d55}.dot.bad{background:#dc2626}.dot.warn{background:#d97706}
83
+ small.verdict.bad{color:#dc2626}small.verdict.warn{color:#d97706}
84
+ `;
85
+
86
+ export const js = `
87
+ burrowPanel(function () {
88
+ return {
89
+ health: {}, healthTimer: null,
90
+ init: function () {
91
+ var self = this;
92
+ this.loadHealth();
93
+ this.healthTimer = setInterval(function () { self.loadHealth(); }, 10000);
94
+ },
95
+ loadHealth: async function () {
96
+ try { this.health = (await getJson('/api/health')).projects || {}; } catch (e) { this.health = {}; }
97
+ },
98
+ serviceFor: function (p, h) {
99
+ var list = this.health[p.project] || [];
100
+ for (var i = 0; i < list.length; i++) if (list[i].hostname === h) return list[i];
101
+ return null;
102
+ },
103
+ tunnelDown: function (p) {
104
+ if (!p.running) return 'cloudflared stopped';
105
+ var s = p.tunnel && p.tunnel.status;
106
+ if (s === 'down' || s === 'inactive') return 'no Cloudflare connections';
107
+ return '';
108
+ },
109
+ deadTargets: function (p) {
110
+ var out = [];
111
+ (this.health[p.project] || []).forEach(function (s) {
112
+ s.targets.forEach(function (t) { if (!t.up) out.push(s.service + ' :' + t.port); });
113
+ });
114
+ return out;
115
+ },
116
+ dotClass: function (p, h) {
117
+ var s = this.serviceFor(p, h);
118
+ if (!s || s.up === null) return '';
119
+ if (!s.up) return 'bad';
120
+ return this.tunnelDown(p) ? 'warn' : 'ok';
121
+ },
122
+ dotTitle: function (p, h) {
123
+ var s = this.serviceFor(p, h);
124
+ if (!s) return 'local port: unknown';
125
+ if (s.up === null) return 'nothing local to check';
126
+ var ports = s.targets.map(function (t) { return t.host + ':' + t.port + (t.up ? ' answers' : ' not answering'); }).join(', ');
127
+ if (!s.up) return 'App down: ' + ports;
128
+ var t = this.tunnelDown(p);
129
+ return t ? 'App up (' + ports + '), tunnel down: ' + t : 'OK: ' + ports;
130
+ },
131
+ verdict: function (p) {
132
+ if (!this.health[p.project]) return '';
133
+ var parts = [];
134
+ var dead = this.deadTargets(p);
135
+ if (dead.length) parts.push('app down: ' + dead.join(', '));
136
+ var t = this.tunnelDown(p);
137
+ if (t && (p.running || p.tunnel)) parts.push('tunnel down: ' + t);
138
+ return parts.length ? parts.join(' · ') : 'ports answer';
139
+ },
140
+ verdictClass: function (p) {
141
+ if (this.deadTargets(p).length) return 'bad';
142
+ return this.tunnelDown(p) && (p.running || p.tunnel) ? 'warn' : '';
143
+ },
144
+ };
145
+ });
146
+ `;
@@ -0,0 +1,104 @@
1
+ // Panel: event history. Shows the actions recorded in ~/.local/state/burrow/history/
2
+ // events.jsonl by the CLI (including commands the dashboard runs, tagged "dashboard")
3
+ // and by other panels (e.g. a tunnel.yml saved from the form).
4
+ import { assertLabel } from '../../naming.js';
5
+ import { events } from '../panels.js';
6
+ import { readEvents, recordEvent, SOURCES } from '../../history.js';
7
+
8
+ export const order = 60;
9
+
10
+ // In-process dashboard actions that don't go through the CLI.
11
+ events.on('event', (e) => recordEvent({ ...e, source: 'dashboard' }));
12
+
13
+ export async function route(ctx) {
14
+ if (ctx.method !== 'GET' || ctx.path !== '/api/history') return false;
15
+ const q = ctx.url.searchParams;
16
+ const project = q.get('project') || undefined;
17
+ const source = q.get('source') || undefined;
18
+ if (project) { try { assertLabel(project, 'project'); } catch { return ctx.json(400, { error: 'bad project' }) ?? true; } }
19
+ if (source && !SOURCES.includes(source)) return ctx.json(400, { error: `source must be one of ${SOURCES.join(', ')}` }) ?? true;
20
+ const limit = Math.min(1000, Math.max(1, parseInt(q.get('limit') || '200', 10) || 200));
21
+ ctx.json(200, { events: readEvents({ limit, project, source }) });
22
+ return true;
23
+ }
24
+
25
+ export const html = {
26
+ toolbar: '<li><button class="secondary outline" @click="openHistory">History</button></li>',
27
+ sections: `
28
+ <article x-show="historyOpen" class="history">
29
+ <header class="logs-head">
30
+ <strong>Event history</strong>
31
+ <small class="muted" x-text="historyCount"></small>
32
+ <span class="spacer"></span>
33
+ <select x-model="historyProject" @change="loadHistory" aria-label="Project">
34
+ <option value="">All projects</option>
35
+ <template x-for="p in projects" :key="p.project"><option :value="p.project" x-text="p.project"></option></template>
36
+ </select>
37
+ <select x-model="historySource" @change="loadHistory" aria-label="Source">
38
+ <option value="">Any source</option><option value="cli">CLI</option><option value="dashboard">Dashboard</option><option value="boot">Boot</option>
39
+ </select>
40
+ <button class="secondary outline" @click="loadHistory">Refresh</button>
41
+ <button class="secondary outline" @click="closeHistory">Close</button>
42
+ </header>
43
+ <p class="error" x-show="hasHistoryError" x-text="historyError"></p>
44
+ <p x-show="historyEmpty"><small class="muted">Nothing recorded yet.</small></p>
45
+ <div class="overflow-auto" x-show="hasHistory">
46
+ <table class="striped">
47
+ <thead><tr><th>When</th><th>Action</th><th>Project</th><th>Source</th><th>Result</th><th>Took</th><th>Details</th></tr></thead>
48
+ <tbody>
49
+ <template x-for="e in historyEvents" :key="e.key">
50
+ <tr>
51
+ <td :title="e.at" x-text="eventTime(e)"></td>
52
+ <td><code x-text="e.action"></code></td>
53
+ <td x-text="eventProject(e)"></td>
54
+ <td><span class="badge" :class="sourceClass(e)" x-text="e.source"></span></td>
55
+ <td><span class="badge" :class="resultClass(e)" x-text="resultText(e)"></span></td>
56
+ <td x-text="eventTook(e)"></td>
57
+ <td><small x-text="eventDetail(e)"></small></td>
58
+ </tr>
59
+ </template>
60
+ </tbody>
61
+ </table>
62
+ </div>
63
+ </article>`,
64
+ };
65
+
66
+ export const css = `
67
+ .history select{width:auto;margin:0;padding:.3rem 2rem .3rem .6rem;font-size:.85rem}
68
+ .badge.src-dashboard{color:#0172ad;border-color:#0172ad}.badge.src-boot{color:#7c3aed;border-color:#7c3aed}
69
+ `;
70
+
71
+ export const js = `
72
+ burrowPanel(function () {
73
+ return {
74
+ historyOpen: false, historyEvents: [], historyProject: '', historySource: '', historyError: '', historyLoaded: false,
75
+ get hasHistory() { return this.historyEvents.length > 0; },
76
+ get historyEmpty() { return this.historyLoaded && !this.historyEvents.length && !this.historyError; },
77
+ get hasHistoryError() { return this.historyError.length > 0; },
78
+ get historyCount() { return this.historyLoaded ? this.historyEvents.length + ' events' : ''; },
79
+ openHistory: function () { this.historyOpen = true; this.loadHistory(); },
80
+ closeHistory: function () { this.historyOpen = false; },
81
+ loadHistory: async function () {
82
+ this.historyError = '';
83
+ var q = new URLSearchParams({ limit: '300' });
84
+ if (this.historyProject) q.set('project', this.historyProject);
85
+ if (this.historySource) q.set('source', this.historySource);
86
+ try {
87
+ var list = (await getJson('/api/history?' + q.toString())).events || [];
88
+ list.forEach(function (e, i) { e.key = e.at + '|' + i; });
89
+ this.historyEvents = list;
90
+ } catch (e) { this.historyEvents = []; this.historyError = e.message; } finally { this.historyLoaded = true; }
91
+ },
92
+ eventTime: function (e) {
93
+ var d = new Date(e.at);
94
+ return d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
95
+ },
96
+ eventProject: function (e) { return e.project || '—'; },
97
+ eventDetail: function (e) { return e.detail || ''; },
98
+ eventTook: function (e) { return e.durationMs >= 0 ? (e.durationMs < 1000 ? e.durationMs + ' ms' : (e.durationMs / 1000).toFixed(1) + ' s') : ''; },
99
+ sourceClass: function (e) { return 'src-' + e.source; },
100
+ resultClass: function (e) { return e.ok ? 'ok' : 'bad'; },
101
+ resultText: function (e) { return e.ok ? 'ok' : 'failed'; },
102
+ };
103
+ });
104
+ `;
@@ -0,0 +1,86 @@
1
+ // Panel: hook results. `burrow up`/`down` record each hook run (pre_up, post_up, pre_down,
2
+ // post_down) in hooks/results.jsonl: when, project, hook, ok or the reason it failed, and
3
+ // how long it took. The command and its output are never recorded (they can hold secrets).
4
+ // Rows whose latest hook run failed get a badge; the Hooks section lists recent runs.
5
+ import { HOOK_NAMES, readHookResults } from '../../hooks.js';
6
+ import { assertLabel } from '../../naming.js';
7
+
8
+ export const order = 70;
9
+
10
+ export async function enrich(projects) {
11
+ const latest = new Map();
12
+ for (const r of readHookResults({ limit: 500 })) if (!latest.has(r.project)) latest.set(r.project, r);
13
+ for (const p of projects) {
14
+ const r = latest.get(p.project);
15
+ if (r) p.lastHook = { hook: r.hook, ok: r.ok, at: r.at, error: r.error || null };
16
+ }
17
+ }
18
+
19
+ export async function route(ctx) {
20
+ if (ctx.method !== 'GET' || ctx.path !== '/api/hooks') return false;
21
+ const project = ctx.url.searchParams.get('project') || undefined;
22
+ if (project) { try { assertLabel(project, 'project'); } catch { return ctx.json(400, { error: 'bad project' }) ?? true; } }
23
+ const limit = Math.min(500, Math.max(1, Number(ctx.url.searchParams.get('limit')) || 100));
24
+ ctx.json(200, { hooks: HOOK_NAMES, results: readHookResults({ limit, project }) });
25
+ return true;
26
+ }
27
+
28
+ export const html = {
29
+ toolbar: '<li><button class="secondary outline" @click="openHooks">Hooks</button></li>',
30
+ rowBadges: '<span class="badge bad" x-show="hookFailed(p)" :title="hookFailTitle(p)">hook failed</span>',
31
+ sections: `
32
+ <article x-show="hooksOpen" class="hooks">
33
+ <header class="logs-head">
34
+ <strong>Hook runs</strong><small class="muted">pre_up, post_up, pre_down, post_down from tunnel.yml</small>
35
+ <span class="spacer"></span>
36
+ <button class="secondary outline" @click="loadHooks">Refresh</button>
37
+ <button class="secondary outline" @click="closeHooks">Close</button>
38
+ </header>
39
+ <p x-show="noHookRuns"><small class="muted">No hook runs recorded yet. Add <code>hooks:</code> to a tunnel.yml (see docs/hooks.md).</small></p>
40
+ <table x-show="hasHookRuns" class="hook-runs">
41
+ <thead><tr><th>When</th><th>Project</th><th>Hook</th><th>Result</th><th>Took</th><th>From</th></tr></thead>
42
+ <tbody>
43
+ <template x-for="r in hookRuns" :key="r.key">
44
+ <tr>
45
+ <td><small x-text="hookWhen(r)"></small></td>
46
+ <td x-text="r.project"></td>
47
+ <td><code x-text="hookName(r)"></code></td>
48
+ <td><span class="badge" :class="hookClass(r)" x-text="hookResult(r)"></span> <small class="muted" x-text="r.error"></small></td>
49
+ <td><small x-text="hookTook(r)"></small></td>
50
+ <td><small x-text="r.source"></small></td>
51
+ </tr>
52
+ </template>
53
+ </tbody>
54
+ </table>
55
+ </article>`,
56
+ };
57
+
58
+ export const css = `
59
+ .hook-runs{font-size:.875rem}.hook-runs td{white-space:normal}
60
+ `;
61
+
62
+ export const js = `
63
+ burrowPanel(function () {
64
+ return {
65
+ hooksOpen: false, hookRuns: [], hooksLoaded: false,
66
+ get hasHookRuns() { return this.hookRuns.length > 0; },
67
+ get noHookRuns() { return this.hooksLoaded && this.hookRuns.length === 0; },
68
+ hookFailed: function (p) { return !!(p.lastHook && !p.lastHook.ok); },
69
+ hookFailTitle: function (p) { return p.lastHook ? p.lastHook.hook + ': ' + (p.lastHook.error || 'failed') : ''; },
70
+ openHooks: function () { this.hooksOpen = true; this.loadHooks(); },
71
+ closeHooks: function () { this.hooksOpen = false; },
72
+ loadHooks: async function () {
73
+ try {
74
+ var j = await getJson('/api/hooks?limit=100');
75
+ j.results.forEach(function (r, i) { r.key = r.at + '|' + i; });
76
+ this.hookRuns = j.results; this.hooksLoaded = true;
77
+ } catch (e) { this.showToast('✗ ' + e.message, false); }
78
+ },
79
+ hookWhen: function (r) { return ago(Date.now() - Date.parse(r.at)) + ' ago'; },
80
+ hookName: function (r) { return r.hook + (r.background ? ' (background)' : ''); },
81
+ hookClass: function (r) { return r.ok ? 'ok' : 'bad'; },
82
+ hookResult: function (r) { return r.ok ? (r.background ? 'started' : 'ok') : 'failed'; },
83
+ hookTook: function (r) { return r.durationMs < 1000 ? r.durationMs + ' ms' : (r.durationMs / 1000).toFixed(1) + ' s'; },
84
+ };
85
+ });
86
+ `;
@@ -0,0 +1,153 @@
1
+ // Panel: live updates. GET /api/stream is a server-sent event stream. One loop per dashboard
2
+ // builds the /api/tunnels payload every few seconds (only while someone is watching), and
3
+ // sends `changed` when it differs from the last one (the page then reloads it) and `tick`
4
+ // otherwise (the page just moves its clock). Dashboard actions (events) trigger a check
5
+ // right away. Streams end after a few minutes so the session cookie is checked again on
6
+ // reconnect. The page falls back to polling every 5 s when the stream is unavailable.
7
+ // BURROW_DASHBOARD_LIVE=off turns the stream off (the page polls as before).
8
+ import { createHash } from 'node:crypto';
9
+
10
+ export const order = 5;
11
+ const num = (v, d) => (Number(v) > 0 ? Number(v) : d);
12
+ const INTERVAL_MS = () => num(process.env.BURROW_LIVE_MS, 3000);
13
+ const MAX_CLIENTS = () => num(process.env.BURROW_LIVE_MAX_CLIENTS, 20);
14
+ const MAX_AGE_MS = () => num(process.env.BURROW_LIVE_MAX_AGE_MS, 5 * 60 * 1000);
15
+
16
+ // Hash of the payload minus fields that change on every read.
17
+ export function payloadHash(data) {
18
+ const { now, ...rest } = data || {};
19
+ return createHash('sha1').update(JSON.stringify(rest)).digest('hex');
20
+ }
21
+
22
+ const hubs = new WeakMap(); // http.Server -> hub (one per dashboard)
23
+ function hubFor(ctx) {
24
+ const server = ctx.req.socket.server;
25
+ let hub = hubs.get(server);
26
+ if (hub) return hub;
27
+ hub = { clients: new Set(), timer: null, running: false, hash: null, again: false, ctx: null, onEvent: null };
28
+ const send = (c, event, data) => { try { c.res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); } catch {} };
29
+ hub.check = async () => {
30
+ if (!hub.clients.size) return;
31
+ if (hub.running) { hub.again = true; return; }
32
+ hub.running = true;
33
+ try {
34
+ const data = await hub.ctx.snapshot();
35
+ const h = payloadHash(data);
36
+ const event = hub.hash !== null && h !== hub.hash ? 'changed' : 'tick';
37
+ hub.hash = h;
38
+ for (const c of hub.clients) send(c, event, { now: data.now });
39
+ } catch (e) {
40
+ hub.ctx.log(`error: live updates: ${e.message}`);
41
+ } finally {
42
+ hub.running = false;
43
+ if (hub.again) { hub.again = false; setTimeout(hub.check, 50); }
44
+ }
45
+ };
46
+ hub.start = () => {
47
+ if (hub.timer) return;
48
+ hub.timer = setInterval(hub.check, INTERVAL_MS());
49
+ hub.timer.unref?.();
50
+ let debounce = null;
51
+ hub.onEvent = () => { clearTimeout(debounce); debounce = setTimeout(hub.check, 300); };
52
+ ctx.events.on('event', hub.onEvent);
53
+ };
54
+ hub.stop = () => {
55
+ clearInterval(hub.timer); hub.timer = null; hub.hash = null;
56
+ if (hub.onEvent) ctx.events.off('event', hub.onEvent);
57
+ hub.onEvent = null;
58
+ };
59
+ hubs.set(server, hub);
60
+ return hub;
61
+ }
62
+
63
+ export async function route(ctx) {
64
+ if (ctx.method !== 'GET' || ctx.path !== '/api/stream') return false;
65
+ if (/^(off|0|false|no)$/i.test(process.env.BURROW_DASHBOARD_LIVE || '')) {
66
+ return ctx.json(404, { error: 'live updates are turned off (BURROW_DASHBOARD_LIVE=off)' }) ?? true;
67
+ }
68
+ const hub = hubFor(ctx);
69
+ if (hub.clients.size >= MAX_CLIENTS()) {
70
+ return ctx.json(503, { error: 'too many live connections; polling instead' }, { 'Retry-After': '30' }) ?? true;
71
+ }
72
+ const { req, res } = ctx;
73
+ res.writeHead(200, {
74
+ 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store',
75
+ 'X-Accel-Buffering': 'no', 'X-Content-Type-Options': 'nosniff', Connection: 'keep-alive',
76
+ });
77
+ res.write(`retry: 3000\nevent: hello\ndata: ${JSON.stringify({ now: Date.now(), intervalMs: INTERVAL_MS() })}\n\n`);
78
+ const client = { res };
79
+ hub.ctx = ctx;
80
+ hub.clients.add(client);
81
+ hub.start();
82
+ const end = setTimeout(() => { try { res.end(); } catch {} }, MAX_AGE_MS());
83
+ end.unref?.();
84
+ const gone = () => {
85
+ clearTimeout(end);
86
+ hub.clients.delete(client);
87
+ if (hub.ctx === ctx && hub.clients.size) hub.ctx = [...hub.clients][0].ctx || hub.ctx;
88
+ if (!hub.clients.size) hub.stop();
89
+ };
90
+ client.ctx = ctx;
91
+ req.on('close', gone);
92
+ res.on('close', gone);
93
+ return true;
94
+ }
95
+
96
+ export const html = {
97
+ toolbarMain: '<li><small class="live-status" :class="liveClass" :title="liveTitle" x-text="liveText"></small></li>',
98
+ };
99
+
100
+ export const css = `
101
+ .live-status{display:inline-flex;align-items:center;gap:.3rem;color:var(--pico-muted-color);white-space:nowrap}
102
+ .live-status::before{content:"";width:.5rem;height:.5rem;border-radius:50%;background:currentColor}
103
+ .live-status.live{color:#1f9d55}.live-status.polling{color:#d97706}
104
+ `;
105
+
106
+ export const js = `
107
+ burrowPanel(function () {
108
+ return {
109
+ liveState: 'connecting', liveEs: null, liveFailures: 0, liveRetry: null,
110
+ get liveText() { return this.liveState === 'live' ? 'Live' : this.liveState === 'polling' ? 'Polling' : 'Connecting'; },
111
+ get liveClass() { return this.liveState; },
112
+ get liveTitle() {
113
+ return this.liveState === 'live' ? 'Updates are pushed as they happen'
114
+ : this.liveState === 'polling' ? 'Live updates unavailable: refreshing every 5 seconds' : 'Connecting to live updates';
115
+ },
116
+ init: function () {
117
+ if (typeof EventSource === 'undefined') { this.liveState = 'polling'; return; }
118
+ clearInterval(this.timer); this.timer = null;
119
+ this.liveConnect();
120
+ },
121
+ livePoll: function () {
122
+ var self = this;
123
+ this.liveState = 'polling';
124
+ if (!this.timer) this.timer = setInterval(function () { self.load(); }, 5000);
125
+ },
126
+ liveConnect: function () {
127
+ var self = this;
128
+ clearTimeout(this.liveRetry);
129
+ var es = new EventSource('/api/stream');
130
+ this.liveEs = es;
131
+ es.addEventListener('hello', function () {
132
+ self.liveFailures = 0; self.liveState = 'live';
133
+ clearInterval(self.timer); self.timer = null;
134
+ self.load();
135
+ });
136
+ es.addEventListener('changed', function () { self.load(); });
137
+ es.addEventListener('tick', function (e) {
138
+ try { var d = JSON.parse(e.data); if (d.now) self.now = d.now; } catch (err) {}
139
+ });
140
+ es.onerror = function () {
141
+ es.close();
142
+ if (self.liveEs !== es) return;
143
+ self.liveEs = null;
144
+ self.liveFailures++;
145
+ // A stream that ends normally reconnects quickly; repeated failures poll meanwhile.
146
+ if (self.liveFailures > 1) self.livePoll(); else self.liveState = 'connecting';
147
+ var wait = Math.min(30000, 1000 * Math.pow(2, Math.max(0, self.liveFailures - 1)));
148
+ self.liveRetry = setTimeout(function () { self.liveConnect(); }, wait);
149
+ };
150
+ },
151
+ };
152
+ });
153
+ `;