co-maintainer 0.6.1 → 0.6.4

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 (99) hide show
  1. package/THIRD_PARTY_NOTICES +161 -0
  2. package/dist/package.json +4 -2
  3. package/dist/src/ai/batch.js +7 -0
  4. package/dist/src/ai/oauth/ids.d.ts +10 -0
  5. package/dist/src/ai/oauth/ids.js +10 -0
  6. package/dist/src/ai/oauth/registry.d.ts +33 -0
  7. package/dist/src/ai/oauth/registry.js +40 -0
  8. package/dist/src/ai/oauth/sign-in-with-chatgpt.d.ts +56 -0
  9. package/dist/src/ai/oauth/sign-in-with-chatgpt.js +552 -0
  10. package/dist/src/ai/openai.d.ts +18 -1
  11. package/dist/src/ai/openai.js +68 -5
  12. package/dist/src/ai/provider.d.ts +3 -0
  13. package/dist/src/ai/provider.js +11 -2
  14. package/dist/src/cli/args.js +61 -21
  15. package/dist/src/cli/commands/oauth.d.ts +1 -0
  16. package/dist/src/cli/commands/oauth.js +73 -0
  17. package/dist/src/cli/commands/registry.js +79 -3
  18. package/dist/src/cli/commands/serve.js +31 -3
  19. package/dist/src/cli/commands/set.js +54 -0
  20. package/dist/src/cli/main.js +5 -0
  21. package/dist/src/cli/review_args.js +5 -0
  22. package/dist/src/config.d.ts +14 -0
  23. package/dist/src/github/client.js +13 -0
  24. package/dist/src/github/collect.d.ts +2 -2
  25. package/dist/src/github/collect.js +60 -23
  26. package/dist/src/github/permissions.js +8 -0
  27. package/dist/src/knowledge/types.d.ts +3 -4
  28. package/dist/src/pr/reviewer.js +5 -4
  29. package/dist/src/server/api/jobs.js +8 -1
  30. package/dist/src/server/api/repos.js +73 -11
  31. package/dist/src/server/api/settings.js +6 -0
  32. package/dist/src/server/app.d.ts +5 -0
  33. package/dist/src/server/app.js +7 -0
  34. package/dist/src/server/http.d.ts +3 -0
  35. package/dist/src/server/http.js +5 -0
  36. package/dist/src/server/pages/activity.js +412 -19
  37. package/dist/src/server/pages/add_repo.js +6 -1
  38. package/dist/src/server/pages/analytics.js +99 -31
  39. package/dist/src/server/pages/catalog.d.ts +1 -0
  40. package/dist/src/server/pages/catalog.js +145 -0
  41. package/dist/src/server/pages/client.d.ts +1 -1
  42. package/dist/src/server/pages/client.js +1 -1
  43. package/dist/src/server/pages/home.d.ts +14 -4
  44. package/dist/src/server/pages/home.js +83 -49
  45. package/dist/src/server/pages/icons.d.ts +3 -0
  46. package/dist/src/server/pages/icons.js +3 -0
  47. package/dist/src/server/pages/knowledge.js +10 -5
  48. package/dist/src/server/pages/layout.d.ts +19 -3
  49. package/dist/src/server/pages/layout.js +156 -33
  50. package/dist/src/server/pages/pr.js +4 -3
  51. package/dist/src/server/pages/rate_limit_waits.d.ts +5 -0
  52. package/dist/src/server/pages/rate_limit_waits.js +74 -0
  53. package/dist/src/server/pages/repo.js +100 -66
  54. package/dist/src/server/pages/repo_prs.js +4 -3
  55. package/dist/src/server/pages/repo_remote.js +4 -3
  56. package/dist/src/server/pages/repo_settings.d.ts +2 -2
  57. package/dist/src/server/pages/repo_settings.js +420 -46
  58. package/dist/src/server/pages/router.d.ts +5 -0
  59. package/dist/src/server/pages/router.js +82 -31
  60. package/dist/src/server/pages/settings.d.ts +10 -1
  61. package/dist/src/server/pages/settings.js +351 -207
  62. package/dist/src/server/pages/setup.d.ts +2 -5
  63. package/dist/src/server/pages/setup.js +21 -23
  64. package/dist/src/server/pages/styles.d.ts +1 -1
  65. package/dist/src/server/pages/styles.js +1 -1
  66. package/dist/src/server/pages/ui.d.ts +117 -0
  67. package/dist/src/server/pages/ui.js +166 -0
  68. package/dist/src/services/clear.js +2 -0
  69. package/dist/src/services/cli_repos.d.ts +2 -0
  70. package/dist/src/services/cli_repos.js +50 -0
  71. package/dist/src/services/concurrency.d.ts +39 -0
  72. package/dist/src/services/concurrency.js +88 -0
  73. package/dist/src/services/dashboard.d.ts +43 -1
  74. package/dist/src/services/dashboard.js +10 -2
  75. package/dist/src/services/jobs.js +5 -3
  76. package/dist/src/services/nav_counts.d.ts +8 -0
  77. package/dist/src/services/nav_counts.js +19 -0
  78. package/dist/src/services/rate_limit.d.ts +33 -0
  79. package/dist/src/services/rate_limit.js +78 -0
  80. package/dist/src/services/repo_list.d.ts +19 -0
  81. package/dist/src/services/repo_list.js +38 -0
  82. package/dist/src/services/review.d.ts +23 -1
  83. package/dist/src/services/review.js +104 -5
  84. package/dist/src/services/search.d.ts +13 -0
  85. package/dist/src/services/search.js +72 -0
  86. package/dist/src/services/setup.js +17 -16
  87. package/dist/src/services/setup_checklist.d.ts +1 -1
  88. package/dist/src/services/setup_checklist.js +26 -47
  89. package/dist/src/store/cache_db.js +1 -1
  90. package/dist/src/store/findings.d.ts +1 -1
  91. package/dist/src/store/findings.js +3 -3
  92. package/dist/src/store/migrations.js +7 -0
  93. package/dist/src/store/repos.d.ts +5 -0
  94. package/dist/src/store/repos.js +12 -0
  95. package/dist/src/store/reviews.d.ts +12 -1
  96. package/dist/src/store/reviews.js +34 -2
  97. package/dist/src/store/rows.d.ts +6 -0
  98. package/dist/src/types.d.ts +5 -1
  99. package/package.json +4 -2
@@ -0,0 +1,145 @@
1
+ /** The internal component gallery served at `/__ui` when the server runs in
2
+ * debug mode (`serve --debug` or `CM_DEBUG=1`). It renders every design-system
3
+ * component in `ui.ts` twice, once light and once dark, so the library can be
4
+ * reviewed and captured as a visual baseline without any real data. It is not
5
+ * part of the product and is absent from a normal server.
6
+ */
7
+ import { escapeHtml, html } from "./layout.js";
8
+ import { client } from "./client.js";
9
+ import { iconNames } from "./icons.js";
10
+ import { alert, badge, card, codeBlock, crumb, dl, emptyState, field, foot, icon, iconSprite, pageHeader, section, segmented, statCard, steps, switchControl, table, tabs, timeline, } from "./ui.js";
11
+ /** `p` prefixes every id so the light and dark copies stay unique. */
12
+ function panel(p) {
13
+ const tones = ["emerald", "amber", "red", "sky", "neutral"];
14
+ return `
15
+ ${pageHeader({
16
+ crumb: crumb([
17
+ { label: "Repositories", href: "#" },
18
+ { label: "acme/widgets" },
19
+ ]),
20
+ title: "Component gallery",
21
+ lead: "Every design-system component, light and dark.",
22
+ actions: `<button class="btn pri" type="button">${icon("sparkles")}Primary</button>
23
+ <button class="btn out" type="button">${icon("download")}Outline</button>
24
+ <button class="btn gh" type="button">Ghost</button>
25
+ <button class="btn danger" type="button">Danger</button>`,
26
+ })}
27
+
28
+ ${tabs([
29
+ { label: "Overview", href: "#", on: true },
30
+ { label: "Pull requests", href: "#", count: 3 },
31
+ { label: "Knowledge", href: "#" },
32
+ ])}
33
+
34
+ ${card(section(table({
35
+ head: ["Pull request", "Author", "Status", "Cost"],
36
+ rows: [
37
+ [
38
+ `<span class="strong">Tidy the helper</span><span class="sub">#12 · fix/helper</span>`,
39
+ "octocat",
40
+ badge("emerald", "Reviewed"),
41
+ `<span class="r tnum">$0.14</span>`,
42
+ ],
43
+ [
44
+ `<span class="strong">Drop the cache</span><span class="sub">#11 · chore/cache</span>`,
45
+ "hubot",
46
+ badge("amber", "Running", { icon: "loader" }),
47
+ `<span class="r tnum">$0.02</span>`,
48
+ ],
49
+ [
50
+ `<span class="strong">Rework auth</span><span class="sub">#9 · feat/auth</span>`,
51
+ "mona",
52
+ badge("red", "Failed"),
53
+ `<span class="r tnum">$0.00</span>`,
54
+ ],
55
+ ],
56
+ }), { title: "Recent reviews", count: 3 }), { flush: true })}
57
+
58
+ <div class="stats">
59
+ ${statCard({ label: "Reviews", value: "128", hint: "+12 vs previous 30 days", icon: "git-pull-request" })}
60
+ ${statCard({ label: "Cost", value: "$4.20", hint: "last 30 days", icon: "coins" })}
61
+ ${statCard({ label: "Median time", value: "1m 30s", hint: "per review", icon: "timer" })}
62
+ ${statCard({ label: "Findings", value: "42", hint: "P0 to P3", icon: "list-checks" })}
63
+ </div>
64
+
65
+ ${card(section(`
66
+ <div class="filters">
67
+ ${segmented([
68
+ { label: "7d", attrs: 'data-range="7d"' },
69
+ { label: "30d", on: true, attrs: 'data-range="30d"' },
70
+ { label: "90d", attrs: 'data-range="90d"' },
71
+ { label: "Recommended", tag: "rec", tagRec: true },
72
+ ])}
73
+ <div class="sbox">${icon("search")}<input class="inp" type="search" placeholder="Search"></div>
74
+ </div>
75
+ <div class="row"><div class="b"><p class="strong">Concurrency</p><p class="muted">Reviews run at the same time.</p></div>
76
+ ${switchControl({ id: `${p}-sw-1`, label: "Auto review", on: true })}
77
+ </div>
78
+ <div class="row"><div class="b"><p class="strong">Auto review</p><p class="muted">Review pushes automatically.</p></div>
79
+ ${switchControl({ id: `${p}-sw-2`, label: "Auto review" })}
80
+ </div>`, { title: "Controls" }))}
81
+
82
+ ${card(section(`<div class="grid2">
83
+ ${field({ label: "Repository", id: `${p}-f1`, value: "acme/widgets", hint: "Owner/name" })}
84
+ ${field({ label: "Branch", id: `${p}-f2`, placeholder: "main" })}
85
+ </div>
86
+ ${field({ label: "Review guide", id: `${p}-f3`, type: "textarea", rows: 3, value: "Focus on correctness." })}
87
+ ${dl([
88
+ { k: "Provider", v: "OpenRouter" },
89
+ {
90
+ k: "High model",
91
+ v: `<span class="mono">anthropic/claude-sonnet-4</span>`,
92
+ },
93
+ { k: "Low model", v: `<span class="mono">deepseek/deepseek-chat</span>` },
94
+ ])}`, { title: "Form fields" }))}
95
+
96
+ ${card(section(`${alert("emerald", { title: "Up to date", body: "Built 12 min ago from 171 facts." })}
97
+ ${alert("amber", { title: "Setup is not finished", body: "Reviews cannot be posted until the GitHub App is connected.", action: `<button class="btn out sm" type="button">Continue${icon("arrow-right", "arr")}</button>` })}
98
+ ${alert("red", { title: "The model returned an empty answer", body: "Nothing was posted as a review. A note was left on the pull request." })}
99
+ ${alert("sky", { title: "Token created", body: "Shown once. Run this on the developer machine." })}
100
+ ${codeBlock({ code: "co-maintainer init acme/widgets --include-codebase --gh-concurrent=1 --ai-concurrent=3" })}`, { title: "Alerts" }))}
101
+
102
+ ${card(section(`<div class="actions-row">${tones
103
+ .map((tone) => badge(tone, tone[0].toUpperCase() + tone.slice(1)))
104
+ .join("")}</div>`, { title: "Badges" }))}
105
+
106
+ ${card(section(steps([
107
+ { n: 1, title: "Models and API key", detail: "Done", state: "done" },
108
+ { n: 2, title: "GitHub App", detail: "In progress", state: "now" },
109
+ { n: 3, title: "First repository" },
110
+ ]), { title: "Setup steps" }), { flush: true })}
111
+
112
+ ${card(section(timeline([
113
+ { title: "Review posted", when: "2 minutes ago", icon: "circle-check" },
114
+ { title: "Sync finished", when: "1 hour ago", icon: "refresh-cw" },
115
+ { title: "Repository added", when: "yesterday", icon: "plus" },
116
+ ]), { title: "Timeline" }))}
117
+
118
+ ${card(emptyState({
119
+ title: "No reviews yet",
120
+ text: "Open a pull request or start one by number.",
121
+ icon: "inbox",
122
+ action: `<button class="btn pri" type="button">Start review</button>`,
123
+ }), { flush: true })}
124
+
125
+ ${card(section(`<div class="actions-row">${iconNames
126
+ .map((name) => `<span class="badge b-ne">${icon(name)}${escapeHtml(name)}</span>`)
127
+ .join("")}</div>`, { title: `Icons (${iconNames.length})` }))}
128
+
129
+ ${card(section("Footer content here.", { title: "Card with footer" }), {})}
130
+ ${foot(`Updated just now<span class="sp"></span><a href="#">Refresh</a>`)}`;
131
+ }
132
+ export function renderCatalog() {
133
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8">
134
+ <meta name="viewport" content="width=device-width, initial-scale=1">
135
+ <title>Component gallery · co-maintainer</title>
136
+ <link rel="stylesheet" href="/styles.css">
137
+ <link rel="icon" href="/logo.png" type="image/png">
138
+ <script>${client}</script></head><body>
139
+ ${iconSprite}
140
+ <div class="app"><main><div class="wrap"><p class="muted">Light theme</p>${panel("l")}</div></main></div>
141
+ <div class="dark"><div class="app"><main><div class="wrap"><p class="muted">Dark theme</p>${panel("d")}</div></main></div></div>
142
+ <div id="toasts"></div>
143
+ </body></html>`;
144
+ return html(body);
145
+ }
@@ -1,2 +1,2 @@
1
1
  /** Generated from src/server/pages/client.js by scripts/embed_assets.mjs — do not edit. */
2
- export declare const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON; keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. Called from the inline scripts on the\n * knowledge pages, so it looks unused from inside this file. */\n// oxlint-disable-next-line no-unused-vars\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\n// oxlint-disable-next-line no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n if (!document.getElementById(\"activity-root\")) return;\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";
2
+ export declare const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\n/** Copy text for the `codeBlock` copy button. `navigator.clipboard` needs a\n * secure context, so the hidden-textarea path keeps Copy working on plain\n * http://localhost too. `done` runs only when one of the two paths worked. */\nfunction copyText(value, done, failed) {\n function fallback() {\n if (legacyCopy(value)) done();\n else if (failed) failed();\n }\n if (navigator.clipboard && navigator.clipboard.writeText) {\n navigator.clipboard.writeText(value).then(done, fallback);\n return;\n }\n fallback();\n}\n\nfunction legacyCopy(value) {\n const area = document.createElement(\"textarea\");\n area.value = value;\n area.setAttribute(\"readonly\", \"\");\n area.style.position = \"fixed\";\n area.style.opacity = \"0\";\n document.body.appendChild(area);\n area.select();\n let copied = false;\n try {\n copied = document.execCommand(\"copy\") === true;\n } catch {\n copied = false;\n }\n area.remove();\n return copied;\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON; keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\nfunction saved(btn, card) {\n if (card) {\n let state = card.querySelector(\".save-state\");\n if (!state) {\n state = document.createElement(\"span\");\n state.className = \"save-state\";\n state.setAttribute(\"role\", \"status\");\n if (btn && btn.parentNode) {\n btn.parentNode.insertBefore(state, btn.nextSibling);\n }\n }\n state.textContent = \"Saved\";\n }\n toast(\"Saved\");\n}\nglobalThis.saved = saved;\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. Called from the inline scripts on the\n * knowledge pages, so it looks unused from inside this file. */\n// oxlint-disable-next-line no-unused-vars\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\n// oxlint-disable-next-line no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\nfunction logLevelClass(level) {\n return [\"info\", \"dim\", \"ok\", \"warn\", \"error\"].indexOf(level) >= 0\n ? level\n : \"info\";\n}\n\nfunction logClock(at) {\n const date = new Date(at);\n if (isNaN(date.getTime())) return \"--:--:--\";\n return date.toTimeString().slice(0, 8);\n}\n\n/** One append-only log panel. The rendered lines are the starting point, the\n * SSE stream resumes after their last seq, and a slow poll catches lines\n * written by another process (the CLI or a direct database write). */\nfunction startLogPanel(panel) {\n if (panel.getAttribute(\"data-started\") === \"1\") return;\n panel.setAttribute(\"data-started\", \"1\");\n const log = panel.querySelector(\".log\");\n if (!log) return;\n const jump = panel.querySelector(\"[data-log-jump]\");\n const jumpN = jump && jump.querySelector(\"span\");\n const count = panel.querySelector(\".cnt\");\n const pause = panel.querySelector(\"[data-log-pause]\");\n const clear = panel.querySelector(\"[data-log-clear]\");\n const status = panel.querySelector(\".st\");\n const errorBox = panel.querySelector(\"[data-log-error]\");\n const id = panel.getAttribute(\"data-job\") || panel.getAttribute(\"data-log\");\n let live = panel.getAttribute(\"data-live\") === \"1\";\n let baseStatus = live\n ? \"Running\"\n : panel.getAttribute(\"data-status\") || \"Done\";\n let baseClass = live\n ? \"run\"\n : baseStatus === \"Failed\"\n ? \"failed\"\n : baseStatus === \"Not posted\" || baseStatus === \"Canceled\"\n ? \"warn\"\n : \"done\";\n let lines = log.querySelectorAll(\".line\").length;\n let empty = log.querySelector(\".log-empty\");\n let pending = 0;\n let paused = false;\n let buffered = [];\n let lastSeq = Number(panel.getAttribute(\"data-seq\") || 0);\n if (!isFinite(lastSeq)) lastSeq = 0;\n const timers = [];\n let stream = null;\n\n function showEmpty() {\n if (empty) return;\n empty = document.createElement(\"p\");\n empty.className = \"log-empty\";\n empty.textContent =\n \"No log lines yet. New lines appear here as the job runs.\";\n log.appendChild(empty);\n }\n\n function hideEmpty() {\n if (!empty) return;\n empty.remove();\n empty = null;\n }\n\n function setError(message) {\n if (!errorBox) return;\n errorBox.textContent = message;\n errorBox.hidden = false;\n }\n\n function clearError() {\n if (!errorBox) return;\n errorBox.textContent = \"\";\n errorBox.hidden = true;\n }\n\n function atBottom() {\n return log.scrollTop + log.clientHeight >= log.scrollHeight - 4;\n }\n\n function setCount() {\n if (!count) return;\n count.textContent = lines + (lines === 1 ? \" line\" : \" lines\");\n }\n\n function setJump() {\n if (!jump) return;\n if (pending > 0) {\n if (jumpN) jumpN.textContent = \"(\" + pending + \")\";\n jump.hidden = false;\n } else {\n if (jumpN) jumpN.textContent = \"\";\n jump.hidden = true;\n }\n }\n\n function add(line) {\n if (!line || typeof line.seq !== \"number\" || line.seq <= lastSeq) return;\n const wasAtBottom = atBottom();\n const el = document.createElement(\"div\");\n el.className = \"line lv-\" + logLevelClass(line.level);\n el.setAttribute(\"data-seq\", String(line.seq));\n const t = document.createElement(\"span\");\n t.className = \"t\";\n t.textContent = logClock(line.at);\n const m = document.createElement(\"span\");\n m.className = \"msg\";\n m.textContent = String(line.message || \"\");\n el.appendChild(t);\n el.appendChild(m);\n log.appendChild(el);\n lines += 1;\n lastSeq = line.seq;\n hideEmpty();\n clearError();\n setCount();\n if (wasAtBottom) {\n log.scrollTop = log.scrollHeight;\n pending = 0;\n setJump();\n } else {\n pending += 1;\n setJump();\n }\n }\n\n function receive(line) {\n if (!line || typeof line.seq !== \"number\" || line.seq <= lastSeq) return;\n if (paused) {\n for (let index = 0; index < buffered.length; index++) {\n if (buffered[index].seq === line.seq) return;\n }\n buffered.push(line);\n return;\n }\n add(line);\n }\n\n function flush() {\n buffered.sort(function (a, b) {\n return a.seq - b.seq;\n });\n for (let index = 0; index < buffered.length; index++) add(buffered[index]);\n buffered = [];\n }\n\n function stopLive() {\n if (stream) {\n const current = stream;\n stream = null;\n try {\n current.abort();\n } catch {\n // the stream was already closed\n }\n }\n for (let index = 0; index < timers.length; index++) {\n clearInterval(timers[index]);\n }\n timers.length = 0;\n }\n\n function setLiveStatus(next) {\n live = false;\n panel.setAttribute(\"data-live\", \"0\");\n baseStatus =\n next === \"failed\" ? \"Failed\" : next === \"canceled\" ? \"Canceled\" : \"Done\";\n baseClass =\n next === \"failed\" ? \"failed\" : next === \"canceled\" ? \"warn\" : \"done\";\n panel.setAttribute(\"data-status\", baseStatus);\n if (!paused && status) {\n status.className = \"st \" + baseClass;\n status.textContent = baseStatus;\n }\n clearError();\n stopLive();\n }\n\n function poll() {\n if (!id) return;\n fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n })\n .then(function (res) {\n if (!res.ok) throw new Error(\"could not poll the job log\");\n return res.json();\n })\n .then(function (job) {\n if (!job) return;\n clearError();\n (job.logs || []).forEach(receive);\n if (job.status !== \"running\" && job.status !== \"queued\") {\n setLiveStatus(job.status);\n }\n })\n .catch(function () {\n if (live) setError(\"Log connection lost. Reconnecting...\");\n });\n }\n\n function connect() {\n if (!id || typeof fetch !== \"function\") return;\n const controller =\n typeof AbortController === \"function\" ? new AbortController() : null;\n stream = controller;\n fetch(\n \"/api/jobs/\" +\n encodeURIComponent(id) +\n \"/logs/stream?from=\" +\n encodeURIComponent(String(lastSeq)),\n {\n headers: {\n accept: \"text/event-stream\",\n \"x-requested-with\": \"co-maintainer\",\n },\n signal: controller ? controller.signal : undefined,\n },\n )\n .then(function (res) {\n if (!res.ok || !res.body || typeof res.body.getReader !== \"function\") {\n setError(\"Log connection lost. Reconnecting...\");\n return;\n }\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n function pump() {\n return reader.read().then(function (chunk) {\n if (chunk.done) return;\n buffer += decoder.decode(chunk.value, { stream: true });\n const frames = buffer.split(\"\\n\\n\");\n buffer = frames.pop() || \"\";\n frames.forEach(function (frame) {\n const data = [];\n frame.split(\"\\n\").forEach(function (line) {\n if (line.indexOf(\"data:\") === 0) {\n data.push(line.slice(5).replace(/^ /, \"\"));\n }\n });\n if (!data.length) return;\n try {\n receive(JSON.parse(data.join(\"\\n\")));\n } catch {\n // a malformed frame is skipped, not fatal\n }\n });\n return pump();\n });\n }\n return pump();\n })\n .catch(function () {\n if (stream === controller) {\n setError(\"Log connection lost. Reconnecting...\");\n }\n });\n }\n\n if (jump) {\n jump.addEventListener(\"click\", function () {\n log.scrollTop = log.scrollHeight;\n pending = 0;\n setJump();\n });\n }\n log.addEventListener(\"scroll\", function () {\n if (atBottom()) {\n pending = 0;\n setJump();\n }\n });\n if (pause) {\n pause.addEventListener(\"click\", function () {\n paused = !paused;\n pause.textContent = paused ? \"Resume\" : \"Pause\";\n if (status) {\n status.className = \"st \" + (paused ? \"paused\" : baseClass);\n status.textContent = paused ? \"Paused\" : baseStatus;\n }\n if (!paused) flush();\n });\n }\n if (clear) {\n clear.addEventListener(\"click\", function () {\n for (let index = 0; index < buffered.length; index++) {\n if (buffered[index].seq > lastSeq) lastSeq = buffered[index].seq;\n }\n log.replaceChildren();\n lines = 0;\n pending = 0;\n buffered = [];\n showEmpty();\n setCount();\n setJump();\n });\n }\n setCount();\n setJump();\n if (live) {\n connect();\n timers.push(setInterval(poll, 1000));\n }\n}\n\n/** The Ctrl K palette. Every query gets a sequence number and only the\n * newest answer is drawn, so a slow reply to an older query never replaces\n * the results of the newer one. The highlighted row is the one Enter opens. */\nfunction startPalette() {\n const pal = document.getElementById(\"pal\");\n const overlay = document.getElementById(\"pal-ov\");\n const input = document.getElementById(\"pal-q\");\n const list = document.getElementById(\"pal-list\");\n if (!pal || !overlay || !input || !list) return;\n let returnFocus = null;\n let seq = 0;\n let timer = 0;\n let index = 0;\n\n function items() {\n return list.querySelectorAll(\"[data-href]\");\n }\n function highlight(next) {\n const rows = items();\n if (rows.length === 0) return;\n index = (next + rows.length) % rows.length;\n rows.forEach(function (row, i) {\n row.classList.toggle(\"on\", i === index);\n row.setAttribute(\"aria-selected\", i === index ? \"true\" : \"false\");\n });\n input.setAttribute(\"aria-activedescendant\", rows[index].id);\n rows[index].scrollIntoView({ block: \"nearest\" });\n }\n function draw(result) {\n list.textContent = \"\";\n if (result.groups.length === 0) {\n const empty = document.createElement(\"div\");\n empty.className = \"none\";\n empty.textContent = \"No results\";\n list.appendChild(empty);\n input.removeAttribute(\"aria-activedescendant\");\n return;\n }\n let n = 0;\n result.groups.forEach(function (group) {\n const label = document.createElement(\"div\");\n label.className = \"gl\";\n label.textContent = group.label;\n list.appendChild(label);\n group.items.forEach(function (item) {\n const row = document.createElement(\"a\");\n row.className = \"it\";\n row.id = \"pal-it-\" + n++;\n row.href = item.href;\n row.setAttribute(\"data-href\", item.href);\n row.setAttribute(\"role\", \"option\");\n row.setAttribute(\"aria-selected\", \"false\");\n const name = document.createElement(\"span\");\n name.className = \"lbl\";\n name.textContent = item.label;\n row.innerHTML =\n '<svg class=\"ic\" aria-hidden=\"true\"><use href=\"#i-' +\n String(item.icon).replace(/[^a-z0-9-]/g, \"\") +\n '\"></use></svg>';\n row.appendChild(name);\n list.appendChild(row);\n });\n });\n highlight(0);\n }\n async function search() {\n const mine = ++seq;\n pal.setAttribute(\"data-loading\", \"\");\n try {\n const res = await fetch(\n \"/api/search?q=\" + encodeURIComponent(input.value),\n { headers: { \"x-requested-with\": \"co-maintainer\" } },\n );\n const result = await res.json();\n if (mine !== seq) return;\n draw(res.ok ? result : { groups: [] });\n } catch {\n if (mine === seq) draw({ groups: [] });\n } finally {\n if (mine === seq) pal.removeAttribute(\"data-loading\");\n }\n }\n function open() {\n if (!pal.hidden) return;\n returnFocus = document.activeElement;\n pal.hidden = false;\n overlay.hidden = false;\n input.value = \"\";\n input.focus();\n search();\n }\n function close() {\n if (pal.hidden) return;\n pal.hidden = true;\n overlay.hidden = true;\n seq++;\n pal.removeAttribute(\"data-loading\");\n if (returnFocus && returnFocus.focus) returnFocus.focus();\n }\n\n document.addEventListener(\"click\", function (ev) {\n if (ev.target && ev.target.closest && ev.target.closest(\"[data-palette]\")) {\n ev.preventDefault();\n open();\n }\n });\n overlay.addEventListener(\"click\", close);\n document.addEventListener(\"keydown\", function (ev) {\n if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === \"k\") {\n ev.preventDefault();\n if (pal.hidden) open();\n else close();\n return;\n }\n if (pal.hidden) return;\n if (ev.key === \"Escape\") {\n ev.preventDefault();\n close();\n } else if (ev.key === \"ArrowDown\") {\n ev.preventDefault();\n highlight(index + 1);\n } else if (ev.key === \"ArrowUp\") {\n ev.preventDefault();\n highlight(index - 1);\n } else if (ev.key === \"Enter\" && ev.target === input) {\n const row = items()[index];\n if (row && !pal.hasAttribute(\"data-loading\")) {\n ev.preventDefault();\n location.href = row.getAttribute(\"data-href\");\n }\n }\n });\n input.addEventListener(\"input\", function () {\n clearTimeout(timer);\n pal.setAttribute(\"data-loading\", \"\");\n timer = setTimeout(search, 120);\n });\n}\n\nfunction startLogPanels() {\n const panels = document.querySelectorAll(\"[data-log]\");\n for (let index = 0; index < panels.length; index++) {\n startLogPanel(panels[index]);\n }\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n // Theme: the head bootstrap already applied the remembered choice; this only\n // flips it and stores the new one.\n const themeButton = document.getElementById(\"theme\");\n if (themeButton) {\n themeButton.addEventListener(\"click\", function () {\n const dark = document.documentElement.classList.toggle(\"dark\");\n try {\n localStorage.setItem(\"theme\", dark ? \"dark\" : \"light\");\n } catch {\n // storage may be unavailable; the class still applies for this page\n }\n });\n }\n\n // Mobile drawer. `open` on the aside slides it in; the overlay closes it and\n // choosing a link closes it before navigating.\n const drawer = document.querySelector(\"aside.side\");\n const overlay = document.getElementById(\"overlay\");\n const menuButton = document.getElementById(\"menu\");\n function setDrawer(open) {\n if (drawer) drawer.classList.toggle(\"open\", open);\n if (overlay) overlay.classList.toggle(\"on\", open);\n }\n if (menuButton) {\n menuButton.addEventListener(\"click\", function () {\n setDrawer(!(drawer && drawer.classList.contains(\"open\")));\n });\n }\n if (overlay) {\n overlay.addEventListener(\"click\", function () {\n setDrawer(false);\n });\n }\n if (drawer) {\n drawer.addEventListener(\"click\", function (ev) {\n if (ev.target && ev.target.closest && ev.target.closest(\"a\")) {\n setDrawer(false);\n }\n });\n }\n\n startPalette();\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest ? ev.target.closest(\"[data-copy]\") : null;\n if (!btn) return;\n const box = btn.closest(\".code\");\n const span = box && box.querySelector(\"span:not(.lbl)\");\n if (!span) return;\n ev.preventDefault();\n copyText(\n span.textContent || \"\",\n function () {\n toast(\"Copied\");\n },\n function () {\n toast(\"Copy failed. Select the text and copy it by hand.\");\n },\n );\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-copy-doc]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n const id = btn.getAttribute(\"data-copy-doc\");\n const sources = document.querySelectorAll(\"[data-doc-source]\");\n let source = null;\n for (let index = 0; index < sources.length; index++) {\n if (sources[index].getAttribute(\"data-doc-source\") === id) {\n source = sources[index];\n break;\n }\n }\n if (!source) return;\n copyText(\n source.textContent || \"\",\n function () {\n toast(\"Copied\");\n },\n function () {\n toast(\"Copy failed. Select the text and copy it by hand.\");\n },\n );\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n startLogPanels();\n if (!document.getElementById(\"activity-root\")) return;\n const jobPanel = document.querySelector(\"[data-log]\");\n if (jobPanel) {\n if (jobPanel.getAttribute(\"data-live\") !== \"1\") return;\n const progress = document.querySelector(\"[data-job-progress]\");\n if (!progress) return;\n const refreshError = document.querySelector(\"[data-job-refresh-error]\");\n let refreshing = false;\n const refreshJob = async function () {\n if (document.hidden || refreshing) return;\n refreshing = true;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n cache: \"no-store\",\n });\n if (!res.ok) throw new Error(\"refresh failed\");\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.querySelector(\"[data-job-progress]\");\n // A finished job renders its result page, which has no progress\n // block: load it rather than keep the running stages and Stop.\n if (!next) {\n location.reload();\n return;\n }\n progress.innerHTML = next.innerHTML;\n if (refreshError) {\n refreshError.textContent = \"\";\n refreshError.hidden = true;\n }\n } catch {\n if (refreshError) {\n refreshError.textContent =\n \"Connection lost. Could not refresh this job. Reconnecting...\";\n refreshError.hidden = false;\n }\n } finally {\n refreshing = false;\n }\n };\n setInterval(refreshJob, 2000);\n return;\n }\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";
@@ -1,2 +1,2 @@
1
1
  /** Generated from src/server/pages/client.js by scripts/embed_assets.mjs — do not edit. */
2
- export const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON; keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. Called from the inline scripts on the\n * knowledge pages, so it looks unused from inside this file. */\n// oxlint-disable-next-line no-unused-vars\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\n// oxlint-disable-next-line no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n if (!document.getElementById(\"activity-root\")) return;\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";
2
+ export const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\n/** Copy text for the `codeBlock` copy button. `navigator.clipboard` needs a\n * secure context, so the hidden-textarea path keeps Copy working on plain\n * http://localhost too. `done` runs only when one of the two paths worked. */\nfunction copyText(value, done, failed) {\n function fallback() {\n if (legacyCopy(value)) done();\n else if (failed) failed();\n }\n if (navigator.clipboard && navigator.clipboard.writeText) {\n navigator.clipboard.writeText(value).then(done, fallback);\n return;\n }\n fallback();\n}\n\nfunction legacyCopy(value) {\n const area = document.createElement(\"textarea\");\n area.value = value;\n area.setAttribute(\"readonly\", \"\");\n area.style.position = \"fixed\";\n area.style.opacity = \"0\";\n document.body.appendChild(area);\n area.select();\n let copied = false;\n try {\n copied = document.execCommand(\"copy\") === true;\n } catch {\n copied = false;\n }\n area.remove();\n return copied;\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON; keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\nfunction saved(btn, card) {\n if (card) {\n let state = card.querySelector(\".save-state\");\n if (!state) {\n state = document.createElement(\"span\");\n state.className = \"save-state\";\n state.setAttribute(\"role\", \"status\");\n if (btn && btn.parentNode) {\n btn.parentNode.insertBefore(state, btn.nextSibling);\n }\n }\n state.textContent = \"Saved\";\n }\n toast(\"Saved\");\n}\nglobalThis.saved = saved;\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. Called from the inline scripts on the\n * knowledge pages, so it looks unused from inside this file. */\n// oxlint-disable-next-line no-unused-vars\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\n// oxlint-disable-next-line no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\nfunction logLevelClass(level) {\n return [\"info\", \"dim\", \"ok\", \"warn\", \"error\"].indexOf(level) >= 0\n ? level\n : \"info\";\n}\n\nfunction logClock(at) {\n const date = new Date(at);\n if (isNaN(date.getTime())) return \"--:--:--\";\n return date.toTimeString().slice(0, 8);\n}\n\n/** One append-only log panel. The rendered lines are the starting point, the\n * SSE stream resumes after their last seq, and a slow poll catches lines\n * written by another process (the CLI or a direct database write). */\nfunction startLogPanel(panel) {\n if (panel.getAttribute(\"data-started\") === \"1\") return;\n panel.setAttribute(\"data-started\", \"1\");\n const log = panel.querySelector(\".log\");\n if (!log) return;\n const jump = panel.querySelector(\"[data-log-jump]\");\n const jumpN = jump && jump.querySelector(\"span\");\n const count = panel.querySelector(\".cnt\");\n const pause = panel.querySelector(\"[data-log-pause]\");\n const clear = panel.querySelector(\"[data-log-clear]\");\n const status = panel.querySelector(\".st\");\n const errorBox = panel.querySelector(\"[data-log-error]\");\n const id = panel.getAttribute(\"data-job\") || panel.getAttribute(\"data-log\");\n let live = panel.getAttribute(\"data-live\") === \"1\";\n let baseStatus = live\n ? \"Running\"\n : panel.getAttribute(\"data-status\") || \"Done\";\n let baseClass = live\n ? \"run\"\n : baseStatus === \"Failed\"\n ? \"failed\"\n : baseStatus === \"Not posted\" || baseStatus === \"Canceled\"\n ? \"warn\"\n : \"done\";\n let lines = log.querySelectorAll(\".line\").length;\n let empty = log.querySelector(\".log-empty\");\n let pending = 0;\n let paused = false;\n let buffered = [];\n let lastSeq = Number(panel.getAttribute(\"data-seq\") || 0);\n if (!isFinite(lastSeq)) lastSeq = 0;\n const timers = [];\n let stream = null;\n\n function showEmpty() {\n if (empty) return;\n empty = document.createElement(\"p\");\n empty.className = \"log-empty\";\n empty.textContent =\n \"No log lines yet. New lines appear here as the job runs.\";\n log.appendChild(empty);\n }\n\n function hideEmpty() {\n if (!empty) return;\n empty.remove();\n empty = null;\n }\n\n function setError(message) {\n if (!errorBox) return;\n errorBox.textContent = message;\n errorBox.hidden = false;\n }\n\n function clearError() {\n if (!errorBox) return;\n errorBox.textContent = \"\";\n errorBox.hidden = true;\n }\n\n function atBottom() {\n return log.scrollTop + log.clientHeight >= log.scrollHeight - 4;\n }\n\n function setCount() {\n if (!count) return;\n count.textContent = lines + (lines === 1 ? \" line\" : \" lines\");\n }\n\n function setJump() {\n if (!jump) return;\n if (pending > 0) {\n if (jumpN) jumpN.textContent = \"(\" + pending + \")\";\n jump.hidden = false;\n } else {\n if (jumpN) jumpN.textContent = \"\";\n jump.hidden = true;\n }\n }\n\n function add(line) {\n if (!line || typeof line.seq !== \"number\" || line.seq <= lastSeq) return;\n const wasAtBottom = atBottom();\n const el = document.createElement(\"div\");\n el.className = \"line lv-\" + logLevelClass(line.level);\n el.setAttribute(\"data-seq\", String(line.seq));\n const t = document.createElement(\"span\");\n t.className = \"t\";\n t.textContent = logClock(line.at);\n const m = document.createElement(\"span\");\n m.className = \"msg\";\n m.textContent = String(line.message || \"\");\n el.appendChild(t);\n el.appendChild(m);\n log.appendChild(el);\n lines += 1;\n lastSeq = line.seq;\n hideEmpty();\n clearError();\n setCount();\n if (wasAtBottom) {\n log.scrollTop = log.scrollHeight;\n pending = 0;\n setJump();\n } else {\n pending += 1;\n setJump();\n }\n }\n\n function receive(line) {\n if (!line || typeof line.seq !== \"number\" || line.seq <= lastSeq) return;\n if (paused) {\n for (let index = 0; index < buffered.length; index++) {\n if (buffered[index].seq === line.seq) return;\n }\n buffered.push(line);\n return;\n }\n add(line);\n }\n\n function flush() {\n buffered.sort(function (a, b) {\n return a.seq - b.seq;\n });\n for (let index = 0; index < buffered.length; index++) add(buffered[index]);\n buffered = [];\n }\n\n function stopLive() {\n if (stream) {\n const current = stream;\n stream = null;\n try {\n current.abort();\n } catch {\n // the stream was already closed\n }\n }\n for (let index = 0; index < timers.length; index++) {\n clearInterval(timers[index]);\n }\n timers.length = 0;\n }\n\n function setLiveStatus(next) {\n live = false;\n panel.setAttribute(\"data-live\", \"0\");\n baseStatus =\n next === \"failed\" ? \"Failed\" : next === \"canceled\" ? \"Canceled\" : \"Done\";\n baseClass =\n next === \"failed\" ? \"failed\" : next === \"canceled\" ? \"warn\" : \"done\";\n panel.setAttribute(\"data-status\", baseStatus);\n if (!paused && status) {\n status.className = \"st \" + baseClass;\n status.textContent = baseStatus;\n }\n clearError();\n stopLive();\n }\n\n function poll() {\n if (!id) return;\n fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n })\n .then(function (res) {\n if (!res.ok) throw new Error(\"could not poll the job log\");\n return res.json();\n })\n .then(function (job) {\n if (!job) return;\n clearError();\n (job.logs || []).forEach(receive);\n if (job.status !== \"running\" && job.status !== \"queued\") {\n setLiveStatus(job.status);\n }\n })\n .catch(function () {\n if (live) setError(\"Log connection lost. Reconnecting...\");\n });\n }\n\n function connect() {\n if (!id || typeof fetch !== \"function\") return;\n const controller =\n typeof AbortController === \"function\" ? new AbortController() : null;\n stream = controller;\n fetch(\n \"/api/jobs/\" +\n encodeURIComponent(id) +\n \"/logs/stream?from=\" +\n encodeURIComponent(String(lastSeq)),\n {\n headers: {\n accept: \"text/event-stream\",\n \"x-requested-with\": \"co-maintainer\",\n },\n signal: controller ? controller.signal : undefined,\n },\n )\n .then(function (res) {\n if (!res.ok || !res.body || typeof res.body.getReader !== \"function\") {\n setError(\"Log connection lost. Reconnecting...\");\n return;\n }\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n function pump() {\n return reader.read().then(function (chunk) {\n if (chunk.done) return;\n buffer += decoder.decode(chunk.value, { stream: true });\n const frames = buffer.split(\"\\n\\n\");\n buffer = frames.pop() || \"\";\n frames.forEach(function (frame) {\n const data = [];\n frame.split(\"\\n\").forEach(function (line) {\n if (line.indexOf(\"data:\") === 0) {\n data.push(line.slice(5).replace(/^ /, \"\"));\n }\n });\n if (!data.length) return;\n try {\n receive(JSON.parse(data.join(\"\\n\")));\n } catch {\n // a malformed frame is skipped, not fatal\n }\n });\n return pump();\n });\n }\n return pump();\n })\n .catch(function () {\n if (stream === controller) {\n setError(\"Log connection lost. Reconnecting...\");\n }\n });\n }\n\n if (jump) {\n jump.addEventListener(\"click\", function () {\n log.scrollTop = log.scrollHeight;\n pending = 0;\n setJump();\n });\n }\n log.addEventListener(\"scroll\", function () {\n if (atBottom()) {\n pending = 0;\n setJump();\n }\n });\n if (pause) {\n pause.addEventListener(\"click\", function () {\n paused = !paused;\n pause.textContent = paused ? \"Resume\" : \"Pause\";\n if (status) {\n status.className = \"st \" + (paused ? \"paused\" : baseClass);\n status.textContent = paused ? \"Paused\" : baseStatus;\n }\n if (!paused) flush();\n });\n }\n if (clear) {\n clear.addEventListener(\"click\", function () {\n for (let index = 0; index < buffered.length; index++) {\n if (buffered[index].seq > lastSeq) lastSeq = buffered[index].seq;\n }\n log.replaceChildren();\n lines = 0;\n pending = 0;\n buffered = [];\n showEmpty();\n setCount();\n setJump();\n });\n }\n setCount();\n setJump();\n if (live) {\n connect();\n timers.push(setInterval(poll, 1000));\n }\n}\n\n/** The Ctrl K palette. Every query gets a sequence number and only the\n * newest answer is drawn, so a slow reply to an older query never replaces\n * the results of the newer one. The highlighted row is the one Enter opens. */\nfunction startPalette() {\n const pal = document.getElementById(\"pal\");\n const overlay = document.getElementById(\"pal-ov\");\n const input = document.getElementById(\"pal-q\");\n const list = document.getElementById(\"pal-list\");\n if (!pal || !overlay || !input || !list) return;\n let returnFocus = null;\n let seq = 0;\n let timer = 0;\n let index = 0;\n\n function items() {\n return list.querySelectorAll(\"[data-href]\");\n }\n function highlight(next) {\n const rows = items();\n if (rows.length === 0) return;\n index = (next + rows.length) % rows.length;\n rows.forEach(function (row, i) {\n row.classList.toggle(\"on\", i === index);\n row.setAttribute(\"aria-selected\", i === index ? \"true\" : \"false\");\n });\n input.setAttribute(\"aria-activedescendant\", rows[index].id);\n rows[index].scrollIntoView({ block: \"nearest\" });\n }\n function draw(result) {\n list.textContent = \"\";\n if (result.groups.length === 0) {\n const empty = document.createElement(\"div\");\n empty.className = \"none\";\n empty.textContent = \"No results\";\n list.appendChild(empty);\n input.removeAttribute(\"aria-activedescendant\");\n return;\n }\n let n = 0;\n result.groups.forEach(function (group) {\n const label = document.createElement(\"div\");\n label.className = \"gl\";\n label.textContent = group.label;\n list.appendChild(label);\n group.items.forEach(function (item) {\n const row = document.createElement(\"a\");\n row.className = \"it\";\n row.id = \"pal-it-\" + n++;\n row.href = item.href;\n row.setAttribute(\"data-href\", item.href);\n row.setAttribute(\"role\", \"option\");\n row.setAttribute(\"aria-selected\", \"false\");\n const name = document.createElement(\"span\");\n name.className = \"lbl\";\n name.textContent = item.label;\n row.innerHTML =\n '<svg class=\"ic\" aria-hidden=\"true\"><use href=\"#i-' +\n String(item.icon).replace(/[^a-z0-9-]/g, \"\") +\n '\"></use></svg>';\n row.appendChild(name);\n list.appendChild(row);\n });\n });\n highlight(0);\n }\n async function search() {\n const mine = ++seq;\n pal.setAttribute(\"data-loading\", \"\");\n try {\n const res = await fetch(\n \"/api/search?q=\" + encodeURIComponent(input.value),\n { headers: { \"x-requested-with\": \"co-maintainer\" } },\n );\n const result = await res.json();\n if (mine !== seq) return;\n draw(res.ok ? result : { groups: [] });\n } catch {\n if (mine === seq) draw({ groups: [] });\n } finally {\n if (mine === seq) pal.removeAttribute(\"data-loading\");\n }\n }\n function open() {\n if (!pal.hidden) return;\n returnFocus = document.activeElement;\n pal.hidden = false;\n overlay.hidden = false;\n input.value = \"\";\n input.focus();\n search();\n }\n function close() {\n if (pal.hidden) return;\n pal.hidden = true;\n overlay.hidden = true;\n seq++;\n pal.removeAttribute(\"data-loading\");\n if (returnFocus && returnFocus.focus) returnFocus.focus();\n }\n\n document.addEventListener(\"click\", function (ev) {\n if (ev.target && ev.target.closest && ev.target.closest(\"[data-palette]\")) {\n ev.preventDefault();\n open();\n }\n });\n overlay.addEventListener(\"click\", close);\n document.addEventListener(\"keydown\", function (ev) {\n if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === \"k\") {\n ev.preventDefault();\n if (pal.hidden) open();\n else close();\n return;\n }\n if (pal.hidden) return;\n if (ev.key === \"Escape\") {\n ev.preventDefault();\n close();\n } else if (ev.key === \"ArrowDown\") {\n ev.preventDefault();\n highlight(index + 1);\n } else if (ev.key === \"ArrowUp\") {\n ev.preventDefault();\n highlight(index - 1);\n } else if (ev.key === \"Enter\" && ev.target === input) {\n const row = items()[index];\n if (row && !pal.hasAttribute(\"data-loading\")) {\n ev.preventDefault();\n location.href = row.getAttribute(\"data-href\");\n }\n }\n });\n input.addEventListener(\"input\", function () {\n clearTimeout(timer);\n pal.setAttribute(\"data-loading\", \"\");\n timer = setTimeout(search, 120);\n });\n}\n\nfunction startLogPanels() {\n const panels = document.querySelectorAll(\"[data-log]\");\n for (let index = 0; index < panels.length; index++) {\n startLogPanel(panels[index]);\n }\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n // Theme: the head bootstrap already applied the remembered choice; this only\n // flips it and stores the new one.\n const themeButton = document.getElementById(\"theme\");\n if (themeButton) {\n themeButton.addEventListener(\"click\", function () {\n const dark = document.documentElement.classList.toggle(\"dark\");\n try {\n localStorage.setItem(\"theme\", dark ? \"dark\" : \"light\");\n } catch {\n // storage may be unavailable; the class still applies for this page\n }\n });\n }\n\n // Mobile drawer. `open` on the aside slides it in; the overlay closes it and\n // choosing a link closes it before navigating.\n const drawer = document.querySelector(\"aside.side\");\n const overlay = document.getElementById(\"overlay\");\n const menuButton = document.getElementById(\"menu\");\n function setDrawer(open) {\n if (drawer) drawer.classList.toggle(\"open\", open);\n if (overlay) overlay.classList.toggle(\"on\", open);\n }\n if (menuButton) {\n menuButton.addEventListener(\"click\", function () {\n setDrawer(!(drawer && drawer.classList.contains(\"open\")));\n });\n }\n if (overlay) {\n overlay.addEventListener(\"click\", function () {\n setDrawer(false);\n });\n }\n if (drawer) {\n drawer.addEventListener(\"click\", function (ev) {\n if (ev.target && ev.target.closest && ev.target.closest(\"a\")) {\n setDrawer(false);\n }\n });\n }\n\n startPalette();\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest ? ev.target.closest(\"[data-copy]\") : null;\n if (!btn) return;\n const box = btn.closest(\".code\");\n const span = box && box.querySelector(\"span:not(.lbl)\");\n if (!span) return;\n ev.preventDefault();\n copyText(\n span.textContent || \"\",\n function () {\n toast(\"Copied\");\n },\n function () {\n toast(\"Copy failed. Select the text and copy it by hand.\");\n },\n );\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-copy-doc]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n const id = btn.getAttribute(\"data-copy-doc\");\n const sources = document.querySelectorAll(\"[data-doc-source]\");\n let source = null;\n for (let index = 0; index < sources.length; index++) {\n if (sources[index].getAttribute(\"data-doc-source\") === id) {\n source = sources[index];\n break;\n }\n }\n if (!source) return;\n copyText(\n source.textContent || \"\",\n function () {\n toast(\"Copied\");\n },\n function () {\n toast(\"Copy failed. Select the text and copy it by hand.\");\n },\n );\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n startLogPanels();\n if (!document.getElementById(\"activity-root\")) return;\n const jobPanel = document.querySelector(\"[data-log]\");\n if (jobPanel) {\n if (jobPanel.getAttribute(\"data-live\") !== \"1\") return;\n const progress = document.querySelector(\"[data-job-progress]\");\n if (!progress) return;\n const refreshError = document.querySelector(\"[data-job-refresh-error]\");\n let refreshing = false;\n const refreshJob = async function () {\n if (document.hidden || refreshing) return;\n refreshing = true;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n cache: \"no-store\",\n });\n if (!res.ok) throw new Error(\"refresh failed\");\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.querySelector(\"[data-job-progress]\");\n // A finished job renders its result page, which has no progress\n // block: load it rather than keep the running stages and Stop.\n if (!next) {\n location.reload();\n return;\n }\n progress.innerHTML = next.innerHTML;\n if (refreshError) {\n refreshError.textContent = \"\";\n refreshError.hidden = true;\n }\n } catch {\n if (refreshError) {\n refreshError.textContent =\n \"Connection lost. Could not refresh this job. Reconnecting...\";\n refreshError.hidden = false;\n }\n } finally {\n refreshing = false;\n }\n };\n setInterval(refreshJob, 2000);\n return;\n }\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";
@@ -1,4 +1,5 @@
1
1
  import type { SetupItem } from "../../services/setup_checklist.ts";
2
+ import type { RepoState } from "../../services/repo_list.ts";
2
3
  export declare function renderLogin(opts: {
3
4
  next: string;
4
5
  error?: string;
@@ -11,11 +12,20 @@ export declare function renderLogin(opts: {
11
12
  }): Response;
12
13
  export declare function renderHome(username: string, rows: {
13
14
  fullName: string;
14
- statusKind: "ok" | "warn" | "err" | "run";
15
- status: string;
15
+ state: RepoState;
16
+ autoOn: boolean;
17
+ fromCli?: boolean;
16
18
  knowledge: string;
17
19
  knowledgeAt?: string;
18
- autoOn: boolean;
19
20
  reviews: string;
21
+ failed: number;
20
22
  cost: string;
21
- }[], checklist: SetupItem[]): Response;
23
+ }[], checklist: SetupItem[],
24
+ /** `rows` is already filtered; `total` and `reviewing` count every
25
+ * repository so the lead and the tabs do not shrink with the filter. */
26
+ filter: {
27
+ q: string;
28
+ status: string;
29
+ total: number;
30
+ reviewing: number;
31
+ }): Response;
@@ -1,4 +1,11 @@
1
- import { empty, html, layout, skSlot, text, when } from "./layout.js";
1
+ import { empty, html, layout, layoutFocus, skSlot, text, when, } from "./layout.js";
2
+ import { alert, badge, icon, segmented } from "./ui.js";
3
+ const STATE_BADGE = {
4
+ reviewing: badge("emerald", "Reviewing", { icon: "circle-check" }),
5
+ paused: badge("neutral", "Paused", { icon: "circle-pause" }),
6
+ "setting-up": badge("sky", "Setting up", { icon: "loader" }),
7
+ "setup-failed": badge("red", "Setup failed", { icon: "circle-alert" }),
8
+ };
2
9
  export function renderLogin(opts) {
3
10
  const err = opts.error
4
11
  ? `<p class="notice bad"><span class="txt">${text(opts.error)}</span></p>`
@@ -21,90 +28,117 @@ export function renderLogin(opts) {
21
28
  ? opts.hint?.trim() ||
22
29
  "Use the dashboard password printed when serve started."
23
30
  : "Sign in with your GitHub account.";
24
- return html(layout({
31
+ return html(layoutFocus({
25
32
  title: "Sign in · co-maintainer",
26
- body: `<div class="wrap" style="max-width:420px">
27
- <img class="brand" src="/logo.png" alt="co-maintainer">
33
+ body: `<img class="brand" src="/logo.png" alt="co-maintainer">
28
34
  <div class="pagehead"><div><h1>Sign in</h1>
29
35
  <p class="lead">${text(lead)}</p></div></div>
30
36
  ${err}
31
37
  <div class="card"><div class="bd">
32
38
  ${passwordForm}${divider}${githubButton}
33
- </div></div>
34
- </div>`,
39
+ </div></div>`,
35
40
  }));
36
41
  }
37
- export function renderHome(username, rows, checklist) {
38
- const autoCount = rows.filter((row) => row.autoOn).length;
39
- const lead = rows.length === 0
42
+ export function renderHome(username, rows, checklist,
43
+ /** `rows` is already filtered; `total` and `reviewing` count every
44
+ * repository so the lead and the tabs do not shrink with the filter. */
45
+ filter) {
46
+ const lead = filter.total === 0
40
47
  ? "No repositories yet. Add one to start."
41
- : `${rows.length} repositories · ${autoCount} reviewing pull requests automatically`;
48
+ : `${filter.total} repositories · ${filter.reviewing} reviewing pull requests automatically`;
42
49
  const remaining = checklist.filter((item) => !item.done);
43
- // The card is hidden entirely once everything is done, so a finished
44
- // install is not told to "finish" anything.
50
+ // One compact banner pointing at /setup, where the steps live. It is
51
+ // hidden entirely once everything is done, so a finished install is not
52
+ // told to "finish" anything.
45
53
  const setupCard = remaining.length === 0
46
54
  ? ""
47
- : `<div class="card" id="finish-setup">
48
- <div class="hd"><h2>Finish setup</h2>
49
- <span class="muted" style="margin-left:auto">${checklist.length - remaining.length}/${checklist.length} done</span></div>
50
- <div class="bd">
51
- <ul class="steps">
52
- ${checklist
53
- .map((item, index) => `<li class="${item.done ? "done" : ""}">
54
- <span class="n">${item.done ? "✓" : index + 1}</span>
55
- <div class="body"><b>${text(item.title)}</b>
56
- <span class="muted">${text(item.detail)}</span></div>
57
- <a class="btn sm" href="${item.href}">${text(item.linkLabel)}</a>
58
- </li>`)
59
- .join("")}
60
- </ul>
61
- </div>
55
+ : `<div id="finish-setup">${alert("amber", {
56
+ title: "Setup is not finished",
57
+ body: `${checklist.length - remaining.length}/${checklist.length} done · ${text(remaining[0].detail)}`,
58
+ icon: "list-checks",
59
+ action: `<a class="btn out sm" href="/setup">Continue${icon("arrow-right", "arr")}</a>`,
60
+ })}</div>`;
61
+ // Tabs keep the search and the search keeps the tab, so both filters
62
+ // combine without JS.
63
+ const tabHref = (status) => {
64
+ const params = new URLSearchParams();
65
+ if (status !== "all")
66
+ params.set("status", status);
67
+ if (filter.q)
68
+ params.set("q", filter.q);
69
+ const query = params.toString();
70
+ return query ? `/?${query}` : "/";
71
+ };
72
+ const current = filter.status === "reviewing" || filter.status === "paused"
73
+ ? filter.status
74
+ : "all";
75
+ const filters = `<div class="filters">
76
+ <form class="sbox" method="get" action="/" role="search">${icon("search")}<input class="inp" type="search" name="q" value="${text(filter.q)}" placeholder="Search repositories" aria-label="Search repositories">${current === "all"
77
+ ? ""
78
+ : `<input type="hidden" name="status" value="${current}">`}</form>
79
+ ${segmented([
80
+ { label: "All", href: tabHref("all"), on: current === "all" },
81
+ {
82
+ label: "Reviewing",
83
+ icon: "circle-check",
84
+ href: tabHref("reviewing"),
85
+ on: current === "reviewing",
86
+ },
87
+ {
88
+ label: "Paused",
89
+ icon: "circle-pause",
90
+ href: tabHref("paused"),
91
+ on: current === "paused",
92
+ },
93
+ ])}
62
94
  </div>`;
63
- const body = rows.length === 0
95
+ const body = filter.total === 0
64
96
  ? empty("No repositories", "Add a repository to generate knowledge and review pull requests.")
65
- : `<div class="card" data-async>
97
+ : rows.length === 0
98
+ ? `${filters}${empty("No repositories match", "Try another search or tab.")}`
99
+ : `${filters}<div class="card" data-async>
66
100
  ${skSlot("table")}
67
101
  <div class="bd flush">
68
102
  <table>
69
103
  <thead><tr>
70
- <th>Repository</th><th>Status</th><th>Knowledge</th><th>Auto review</th>
71
- <th class="num">Reviews</th><th class="num">Cost (30d)</th>
104
+ <th>Repository</th><th>Status</th><th>Knowledge</th>
105
+ <th class="num">Reviews (30d)</th><th class="num">Cost (30d)</th><th></th>
72
106
  </tr></thead>
73
107
  <tbody>
74
108
  ${rows
75
- .map((row) => `<tr>
76
- <td><a href="/repos/${text(row.fullName)}">${text(row.fullName)}</a></td>
77
- <td><span class="st ${row.statusKind}">${text(row.status)}</span></td>
109
+ .map((row) => `<tr>
110
+ <td><a class="strong" href="/repos/${text(row.fullName)}">${text(row.fullName)}</a><span class="sub">${row.fromCli
111
+ ? "Added from CLI"
112
+ : row.autoOn
113
+ ? "Automatic review on"
114
+ : "Automatic review off"}</span></td>
115
+ <td>${STATE_BADGE[row.state]}</td>
78
116
  <td>${text(row.knowledge)}${row.knowledgeAt
79
- ? `<div class="dim" style="font-size:13px">${when(row.knowledgeAt)}</div>`
80
- : ""}</td>
81
- <td>${row.autoOn
82
- ? `<button class="tg on" data-repo="${text(row.fullName)}" data-on="1"></button>`
83
- : `<button class="tg" data-repo="${text(row.fullName)}" data-on="0"></button>`}</td>
84
- <td class="num">${text(row.reviews)}</td>
117
+ ? `<div class="dim" style="font-size:13px">${when(row.knowledgeAt)}</div>`
118
+ : ""}</td>
119
+ <td class="num">${text(row.reviews)}${row.failed > 0
120
+ ? `<span class="sub">${row.failed} failed</span>`
121
+ : ""}</td>
85
122
  <td class="num">${text(row.cost)}</td>
123
+ <td class="num"><a class="btn out sm" href="/repos/${text(row.fullName)}">Open${icon("arrow-right", "arr")}</a></td>
86
124
  </tr>`)
87
- .join("")}
125
+ .join("")}
88
126
  </tbody>
89
127
  </table>
90
128
  </div>
91
- <div class="ft"><span>Showing ${rows.length} repositories</span></div>
129
+ <div class="ft"><span>Showing ${rows.length} of ${filter.total} repositories</span></div>
92
130
  </div>`;
93
131
  return html(layout({
94
132
  title: "Repositories · co-maintainer",
95
133
  username,
134
+ active: "/",
96
135
  body: `<div class="wrap">
97
136
  <div class="pagehead">
98
137
  <div><h1>Repositories</h1><p class="lead">${text(lead)}</p></div>
99
- <div class="actions">${rows.length === 0 ? `<a class="btn" href="/setup">Get started</a>` : ""}<a class="btn primary" href="/repos/new">Add repository</a></div>
138
+ <div class="actions">${rows.length === 0 ? `<a class="btn" href="/setup">Get started</a>` : ""}<a class="btn primary" href="/repos/new">${icon("plus")}Add repository</a></div>
100
139
  </div>
101
140
  ${setupCard}
102
141
  ${body}
103
- </div>
104
- <script>
105
- document.querySelectorAll(".tg[data-repo]").forEach(function(btn) {
106
- bindToggle(btn, "/api/repos/" + btn.getAttribute("data-repo"), "autoReview");
107
- });
108
- </script>`,
142
+ </div>`,
109
143
  }));
110
144
  }