git-tm 2.0.0 → 2.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.
- package/README.md +1 -1
- package/package.json +6 -2
- package/src/cli.js +24 -4
- package/src/edit.js +6 -1
- package/src/index.js +1 -1
- package/src/public/app.css +5 -0
- package/src/public/index.html +1 -0
- package/src/public/js/diff.js +9 -0
- package/src/public/js/edit.js +1 -1
- package/src/public/js/history.js +13 -0
- package/src/public/js/main.js +46 -4
- package/src/public/js/reflog.js +24 -7
- package/src/public/js/ui.js +46 -1
- package/src/server.js +63 -35
- package/src/types/index.d.ts +2 -2
- package/src/types/server.d.ts +36 -0
package/README.md
CHANGED
|
@@ -142,7 +142,7 @@ Edit mode is built to be hard to regret:
|
|
|
142
142
|
- **Your work stays safe.** Message, author and squash edits never touch your working tree. Drop and revert refuse if you have staged changes, and stop if anything conflicts, leaving everything as it was.
|
|
143
143
|
- **Pushed commits** can be rewritten only after a clear warning: it means a force-push and a different history for everyone else. git-tm never pushes for you.
|
|
144
144
|
|
|
145
|
-
Each edit is printed in the terminal with its backup id. Drop and revert need Git 2.40 or newer.
|
|
145
|
+
Each edit is printed in the terminal with its backup id. Drop and revert need Git 2.40 or newer. git-tm keeps backups for your last 200 edits per repository and removes older ones automatically (`git for-each-ref refs/git-tm/backups/` lists them, `git update-ref -d <ref>` removes one).
|
|
146
146
|
|
|
147
147
|
## Use it from code
|
|
148
148
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "git-tm",
|
|
3
|
-
"version": "2.
|
|
4
|
-
"description": "Explore any Git repository in your browser: commit graph, diffs, blame, insights
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "Explore any Git repository in your browser: commit graph, syntax-highlighted diffs, blame, reflog recovery, insights, time travel, and opt-in safe history editing. Zero dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
7
7
|
"types": "./src/types/index.d.ts",
|
|
@@ -59,6 +59,10 @@
|
|
|
59
59
|
"history-viewer",
|
|
60
60
|
"diff",
|
|
61
61
|
"blame",
|
|
62
|
+
"reflog",
|
|
63
|
+
"rebase",
|
|
64
|
+
"edit-history",
|
|
65
|
+
"syntax-highlighting",
|
|
62
66
|
"compare",
|
|
63
67
|
"cli",
|
|
64
68
|
"developer-tools",
|
package/src/cli.js
CHANGED
|
@@ -208,8 +208,21 @@ async function main() {
|
|
|
208
208
|
|
|
209
209
|
const shownHost = ["127.0.0.1", "::1", "0.0.0.0", "::"].includes(values.host) ? "localhost" : values.host;
|
|
210
210
|
const url = `http://${shownHost}:${actual}`;
|
|
211
|
-
const info = await
|
|
211
|
+
const [info, remotesOut] = await Promise.all([
|
|
212
|
+
repo.info().catch(() => ({})),
|
|
213
|
+
repo.run(["remote", "-v"]).catch(() => ""),
|
|
214
|
+
]);
|
|
212
215
|
const where = info.branch ?? (info.head ? info.head.slice(0, 7) : "no commits yet");
|
|
216
|
+
const remotes = [];
|
|
217
|
+
const seenRemotes = new Set();
|
|
218
|
+
for (const line of remotesOut.split("\n")) {
|
|
219
|
+
const m = line.match(/^(\S+)\t(\S+)\s+\((fetch|push)\)$/);
|
|
220
|
+
if (!m || seenRemotes.has(m[1])) continue;
|
|
221
|
+
seenRemotes.add(m[1]);
|
|
222
|
+
// Never leak embedded credentials from remote URLs to the terminal.
|
|
223
|
+
const cleanUrl = m[2].replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]+@/i, "$1");
|
|
224
|
+
remotes.push([m[1], cleanUrl]);
|
|
225
|
+
}
|
|
213
226
|
|
|
214
227
|
const reload = async () => {
|
|
215
228
|
if (reloading || stopping) return;
|
|
@@ -238,10 +251,17 @@ async function main() {
|
|
|
238
251
|
console.log();
|
|
239
252
|
console.log(` ${c.accent(c.bold("git-tm"))} ${c.dim(`v${pkg.version}`)}`);
|
|
240
253
|
console.log();
|
|
241
|
-
console.log(` ${c.dim("repo")} ${tildify(repo.root)} ${c.dim(`(${where})`)}`);
|
|
242
|
-
|
|
254
|
+
console.log(` ${c.dim("repo ")} ${tildify(repo.root)} ${c.dim(`(${where})`)}`);
|
|
255
|
+
if (remotes.length) {
|
|
256
|
+
const padName = Math.max(...remotes.map(([n]) => n.length));
|
|
257
|
+
remotes.forEach(([name, rUrl], i) => {
|
|
258
|
+
const label = i === 0 ? c.dim("remote") : " ";
|
|
259
|
+
console.log(` ${label} ${name.padEnd(padName)} ${c.dim(rUrl)}`);
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
console.log(` ${c.dim("url ")} ${c.cyan(url)}`);
|
|
243
263
|
if (actual !== port && port !== 0) console.log(` ${c.dim(`port ${port} was busy, using ${actual}`)}`);
|
|
244
|
-
if (values.edit) console.log(` ${c.yellow("edit")} on: history can be changed. Every edit is backed up and can be undone. Mind the timeline.`);
|
|
264
|
+
if (values.edit) console.log(` ${c.yellow("edit ")} on: history can be changed. Every edit is backed up and can be undone. Mind the timeline.`);
|
|
245
265
|
console.log();
|
|
246
266
|
|
|
247
267
|
if (values.open) openBrowser(url);
|
package/src/edit.js
CHANGED
|
@@ -382,14 +382,19 @@ async function readLog(repo) {
|
|
|
382
382
|
async function writeLog(repo, entries) {
|
|
383
383
|
const file = await logPath(repo);
|
|
384
384
|
await mkdir(path.dirname(file), { recursive: true });
|
|
385
|
+
const kept = entries.slice(-MAX_LOG);
|
|
386
|
+
const evicted = entries.length > MAX_LOG ? entries.slice(0, entries.length - MAX_LOG) : [];
|
|
385
387
|
const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
386
388
|
try {
|
|
387
|
-
await writeFile(tmp, JSON.stringify(
|
|
389
|
+
await writeFile(tmp, JSON.stringify(kept, null, 2) + "\n");
|
|
388
390
|
await rename(tmp, file);
|
|
389
391
|
} catch (e) {
|
|
390
392
|
await unlink(tmp).catch(() => {});
|
|
391
393
|
throw e;
|
|
392
394
|
}
|
|
395
|
+
for (const e of evicted) {
|
|
396
|
+
if (e?.id) await removeBackup(repo, e.id);
|
|
397
|
+
}
|
|
393
398
|
}
|
|
394
399
|
|
|
395
400
|
const newId = () => `${Date.now()}-${randomBytes(2).toString("hex")}`;
|
package/src/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Public API. The CLI is src/cli.js; everything here can be imported as `git-tm`.
|
|
2
2
|
export { openRepo, git, GitError, WORKTREE, webUrl } from "./git.js";
|
|
3
|
-
export { createServer, listen } from "./server.js";
|
|
3
|
+
export { createServer, createApiHandler, listen } from "./server.js";
|
|
4
4
|
export { planEdit, applyEdit, listBackups, undoEdit } from "./edit.js";
|
|
5
5
|
export { createLayout, layout } from "./public/js/graph.js";
|
package/src/public/app.css
CHANGED
package/src/public/index.html
CHANGED
|
@@ -66,6 +66,7 @@
|
|
|
66
66
|
<dt><kbd>/</kbd></dt><dd>Search</dd>
|
|
67
67
|
<dt><kbd>Esc</kbd></dt><dd>Close panel / clear search</dd>
|
|
68
68
|
<dt><kbd>g</kbd> <kbd>h</kbd> / <kbd>c</kbd> / <kbd>r</kbd> / <kbd>i</kbd></dt><dd>History / Compare / Reflog / Insights</dd>
|
|
69
|
+
<dt><kbd>e</kbd></dt><dd>Edit selected commit (in edit mode)</dd>
|
|
69
70
|
</dl>
|
|
70
71
|
<h2>Search syntax</h2>
|
|
71
72
|
<dl>
|
package/src/public/js/diff.js
CHANGED
|
@@ -328,6 +328,14 @@ export async function mountChanges(el, opts) {
|
|
|
328
328
|
const auto = files.length <= 8 && total <= 600 ? files.length : files.length <= 30 ? 1 : 0;
|
|
329
329
|
$$(".file", el).slice(0, auto).forEach((sec) => toggle(sec, true));
|
|
330
330
|
}
|
|
331
|
+
syncExpandBtn();
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function syncExpandBtn() {
|
|
335
|
+
const btn = $('[data-act="expand-all"]', el);
|
|
336
|
+
if (!btn) return;
|
|
337
|
+
const secs = $$(".file", el);
|
|
338
|
+
btn.textContent = secs.length && secs.every((s) => s.classList.contains("open")) ? "Collapse all" : "Expand all";
|
|
331
339
|
}
|
|
332
340
|
|
|
333
341
|
async function toggle(sec, open) {
|
|
@@ -337,6 +345,7 @@ export async function mountChanges(el, opts) {
|
|
|
337
345
|
body.hidden = !willOpen;
|
|
338
346
|
head.setAttribute("aria-expanded", String(willOpen));
|
|
339
347
|
sec.classList.toggle("open", willOpen);
|
|
348
|
+
syncExpandBtn();
|
|
340
349
|
if (willOpen && !body.dataset.loaded) await loadPatch(sec);
|
|
341
350
|
}
|
|
342
351
|
|
package/src/public/js/edit.js
CHANGED
|
@@ -342,7 +342,7 @@ export function mountBackups(container, app) {
|
|
|
342
342
|
</div>
|
|
343
343
|
<div class="edit-backup-actions">
|
|
344
344
|
${b.canUndo
|
|
345
|
-
? html`<button class="btn btn-sm" data-undo="${b.id}">${b.op === "undo" ? "Redo" : "Undo"}</button>`
|
|
345
|
+
? html`<button class="btn btn-sm" data-undo="${b.id}" title="${b.op === "undo" ? `Redo: put ${b.branch} back to how it was before this undo` : `Undo: put ${b.branch} back to how it was before this edit`}">${b.op === "undo" ? "Redo" : "Undo"}</button>`
|
|
346
346
|
: restoring === b.id
|
|
347
347
|
? html`<form class="edit-restore" data-restore="${b.id}">
|
|
348
348
|
<input name="branch" value="restore/${b.branch}-${b.id.slice(-4)}" aria-label="New branch name" autocomplete="off" />
|
package/src/public/js/history.js
CHANGED
|
@@ -376,6 +376,13 @@ export function createHistory(app) {
|
|
|
376
376
|
else app.navigate(`#/commit/${s.commits[s.selected].hash}`);
|
|
377
377
|
} else if (e.key === "t") {
|
|
378
378
|
setPicking(!travel.picking);
|
|
379
|
+
} else if (e.key === "e" && app.repo?.edit) {
|
|
380
|
+
const target = (openHash && openHash !== WORKTREE && s.commits.find((c) => c.hash === openHash)) || (s.selected >= 0 ? s.commits[s.selected] : null);
|
|
381
|
+
if (!target || target.hash === WORKTREE || target.worktree) return;
|
|
382
|
+
e.preventDefault();
|
|
383
|
+
api("commit", { rev: target.hash })
|
|
384
|
+
.then((res) => openEdit(app, res.commit))
|
|
385
|
+
.catch((err) => toast(`Could not load the commit: ${err.message}`, "error"));
|
|
379
386
|
}
|
|
380
387
|
}
|
|
381
388
|
|
|
@@ -436,6 +443,12 @@ export function createHistory(app) {
|
|
|
436
443
|
return {
|
|
437
444
|
el,
|
|
438
445
|
reload,
|
|
446
|
+
/** Draw the open commit again, for example after edit mode was switched on or off. */
|
|
447
|
+
redrawDetail() {
|
|
448
|
+
if (!openHash) return;
|
|
449
|
+
detailCtl?.destroy?.();
|
|
450
|
+
detailCtl = renderDetail(pane, app, openHash, {});
|
|
451
|
+
},
|
|
439
452
|
open,
|
|
440
453
|
onKey,
|
|
441
454
|
show: () => requestAnimationFrame(() => paint(true)),
|
package/src/public/js/main.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { api, html, raw, $, $$, icons, toast, storage, copyText, openContextMenu, WORKTREE } from "./ui.js";
|
|
1
|
+
import { api, html, raw, $, $$, icons, toast, storage, copyText, openContextMenu, clearAvatars, historyWriteState, WORKTREE } from "./ui.js";
|
|
2
2
|
import { createHistory } from "./history.js";
|
|
3
3
|
import { createCompare } from "./compare.js";
|
|
4
4
|
import { createReflog } from "./reflog.js";
|
|
@@ -50,6 +50,7 @@ const app = {
|
|
|
50
50
|
app.views.reflog.invalidate();
|
|
51
51
|
app.views.insights.invalidate();
|
|
52
52
|
if (app.current === "reflog") app.views.reflog.load();
|
|
53
|
+
else if (app.current === "compare") route();
|
|
53
54
|
},
|
|
54
55
|
};
|
|
55
56
|
|
|
@@ -103,17 +104,21 @@ async function onSearch(e) {
|
|
|
103
104
|
|
|
104
105
|
// ------------------------------------------------------------------ header + sidebar
|
|
105
106
|
|
|
107
|
+
// In the VS Code extension, edit mode is a setting rather than a command-line flag.
|
|
108
|
+
const inVsCode = Boolean(globalThis.gitTmBridge);
|
|
109
|
+
|
|
106
110
|
function renderRepo() {
|
|
107
111
|
const r = app.repo;
|
|
108
112
|
const where = r.branch ?? (r.head ? `detached at ${r.head.slice(0, 7)}` : "no commits yet");
|
|
109
113
|
$("#repo").innerHTML = String(html`<span class="repo-name" title="${r.root}">${r.name}</span>
|
|
110
114
|
<span class="repo-branch" title="Current branch">${raw(icons.branch)}${where}</span>
|
|
111
|
-
${r.edit ? html`<span class="edit-badge" title="Started with --edit: history can be changed. Every edit is backed up and can be undone.">Edit mode</span>` : ""}`);
|
|
115
|
+
${r.edit ? html`<span class="edit-badge" title="${inVsCode ? "gitTm.enableEditMode is on" : "Started with --edit"}: history can be changed. Every edit is backed up and can be undone.">Edit mode</span>` : ""}`);
|
|
112
116
|
document.title = `${r.name} · Git Time Machine`;
|
|
113
117
|
const mb = $("#mode-banner");
|
|
114
118
|
if (mb) {
|
|
115
119
|
if (r.edit) {
|
|
116
120
|
mb.className = "mode-banner edit";
|
|
121
|
+
mb.dataset.mode = "edit";
|
|
117
122
|
mb.hidden = false;
|
|
118
123
|
mb.innerHTML = String(html`<span><strong>Edit mode active</strong> — read-only protection is off. History can be rewritten here; every edit is previewed and backed up for Undo.</span>`);
|
|
119
124
|
mb.onclick = null;
|
|
@@ -121,8 +126,11 @@ function renderRepo() {
|
|
|
121
126
|
const show = !storage.get("hide-edit-hint", false);
|
|
122
127
|
mb.className = "mode-banner";
|
|
123
128
|
mb.hidden = !show;
|
|
124
|
-
|
|
125
|
-
|
|
129
|
+
// Redraw when switching from edit mode (the setting can change while the page is open).
|
|
130
|
+
if (show && mb.dataset.mode !== "read-only") {
|
|
131
|
+
mb.dataset.mode = "read-only";
|
|
132
|
+
const how = inVsCode ? html`Turn on the <code>gitTm.enableEditMode</code> setting` : html`Restart with <code>git-tm --edit</code>`;
|
|
133
|
+
mb.innerHTML = String(html`<span><strong>Read-only mode</strong> — want to reword, squash, drop, or revert commits? ${how}</span>
|
|
126
134
|
<button class="icon-btn" data-act="dismiss-mode" title="Dismiss" aria-label="Dismiss">${raw(icons.close)}</button>`);
|
|
127
135
|
mb.onclick = (e) => {
|
|
128
136
|
if (e.target.closest("[data-act=dismiss-mode]")) {
|
|
@@ -282,8 +290,18 @@ let offline = false;
|
|
|
282
290
|
|
|
283
291
|
async function poll() {
|
|
284
292
|
if (document.hidden && !offline) return;
|
|
293
|
+
// While git-tm itself moves a branch, or if it did during this request, the change isn't news:
|
|
294
|
+
// afterEdit() picks up the new state.
|
|
295
|
+
const before = historyWriteState();
|
|
296
|
+
if (before.busy) return;
|
|
285
297
|
try {
|
|
286
298
|
const { fingerprint: fp } = await api("state");
|
|
299
|
+
const after = historyWriteState();
|
|
300
|
+
if (after.seq !== before.seq) return;
|
|
301
|
+
if (fp === after.fingerprint && fp !== fingerprint) {
|
|
302
|
+
fingerprint = fp; // the state right after git-tm's own edit
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
287
305
|
if (fingerprint && fp !== fingerprint) {
|
|
288
306
|
await app.reloadRepo();
|
|
289
307
|
showBanner("changed");
|
|
@@ -386,6 +404,8 @@ function onKey(e) {
|
|
|
386
404
|
return;
|
|
387
405
|
}
|
|
388
406
|
if (typing || e.metaKey || e.ctrlKey || e.altKey) return;
|
|
407
|
+
// A modal dialog (Edit) is open: its own buttons handle the keyboard, not the views behind it.
|
|
408
|
+
if (document.querySelector("dialog[open]")) return;
|
|
389
409
|
if (pendingG) {
|
|
390
410
|
pendingG = false;
|
|
391
411
|
const to = { h: "#/", c: "#/compare", r: "#/reflog", i: "#/insights" }[e.key];
|
|
@@ -471,6 +491,28 @@ async function boot() {
|
|
|
471
491
|
setInterval(poll, 3000);
|
|
472
492
|
poll();
|
|
473
493
|
document.addEventListener("visibilitychange", poll);
|
|
494
|
+
|
|
495
|
+
// VS Code extension: open filtered (File History), retarget an open panel, or pick up changed settings.
|
|
496
|
+
const applyQuery = (q) => {
|
|
497
|
+
if (typeof q !== "string") return;
|
|
498
|
+
$("#search").value = q;
|
|
499
|
+
app.setFilter(q.trim() ? parseQuery(q) : null);
|
|
500
|
+
};
|
|
501
|
+
if (globalThis.gitTmBridge?.initialQuery) applyQuery(globalThis.gitTmBridge.initialQuery);
|
|
502
|
+
window.addEventListener("gtm-query", (e) => applyQuery(e.detail));
|
|
503
|
+
window.addEventListener("gtm-refresh", async () => {
|
|
504
|
+
try {
|
|
505
|
+
clearAvatars(); // refilled by the next responses if avatars are still on
|
|
506
|
+
await app.reloadRepo();
|
|
507
|
+
app.views.history.reload();
|
|
508
|
+
app.views.history.redrawDetail(); // its Edit button follows the setting
|
|
509
|
+
app.views.reflog.invalidate();
|
|
510
|
+
app.views.insights.invalidate();
|
|
511
|
+
if (app.current !== "history") route();
|
|
512
|
+
} catch (err) {
|
|
513
|
+
toast(err.message, "error");
|
|
514
|
+
}
|
|
515
|
+
});
|
|
474
516
|
}
|
|
475
517
|
|
|
476
518
|
boot();
|
package/src/public/js/reflog.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Reflog view: recent HEAD movements and read-only recovery of lost commits.
|
|
2
2
|
|
|
3
|
-
import { api, html, raw, $, avatar, refBadges, relTime, fullDate, short, plural, icons, copyText, loading, errorBox, empty } from "./ui.js";
|
|
3
|
+
import { api, html, raw, $, avatar, refBadges, relTime, fullDate, short, plural, icons, copyText, openContextMenu, loading, errorBox, empty } from "./ui.js";
|
|
4
4
|
import { mountBackups } from "./edit.js";
|
|
5
5
|
|
|
6
6
|
const PAGE = 200;
|
|
@@ -18,12 +18,12 @@ const ACTION_KIND = {
|
|
|
18
18
|
branch: "move",
|
|
19
19
|
};
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
// Commands use the full hash: a 7-character one can match several objects in big repositories.
|
|
22
|
+
export function rescueCommands(hash) {
|
|
23
23
|
return [
|
|
24
|
-
{ cmd: `git branch rescue-${
|
|
25
|
-
{ cmd: `git cherry-pick ${
|
|
26
|
-
{ cmd: `git checkout ${
|
|
24
|
+
{ cmd: `git branch rescue-${short(hash)} ${hash}`, note: "Create a new branch pointing at this commit (safest)" },
|
|
25
|
+
{ cmd: `git cherry-pick ${hash}`, note: "Apply this commit onto your current branch" },
|
|
26
|
+
{ cmd: `git checkout ${hash}`, note: "Inspect this commit in detached HEAD" },
|
|
27
27
|
];
|
|
28
28
|
}
|
|
29
29
|
|
|
@@ -147,7 +147,7 @@ export function createReflog(app) {
|
|
|
147
147
|
drawFull();
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
-
// Edits made in edit mode, with Undo, shown above the reflog
|
|
150
|
+
// Edits made in edit mode, with Undo, shown above the reflog while edit mode is on.
|
|
151
151
|
// One element per load, moved into place on each redraw, so typing in the filter doesn't refetch it.
|
|
152
152
|
let backupsEl = null;
|
|
153
153
|
function backupsSlot() {
|
|
@@ -227,6 +227,23 @@ export function createReflog(app) {
|
|
|
227
227
|
}
|
|
228
228
|
});
|
|
229
229
|
|
|
230
|
+
el.addEventListener("contextmenu", (e) => {
|
|
231
|
+
const item = e.target.closest(".reflog-item");
|
|
232
|
+
if (!item) return;
|
|
233
|
+
const entry = entries.find((x) => x.index === Number(item.dataset.index));
|
|
234
|
+
if (!entry) return;
|
|
235
|
+
const isHead = app.repo?.head && entry.hash === app.repo.head;
|
|
236
|
+
const rescueCmd = rescueCommands(entry.hash)[0].cmd;
|
|
237
|
+
openContextMenu(e, [
|
|
238
|
+
{ label: "Open commit", icon: icons.file, onClick: () => app.navigate(`#/commit/${entry.hash}`) },
|
|
239
|
+
!isHead && app.repo?.head ? { label: "Compare to HEAD", icon: icons.compare, onClick: () => app.navigate(`#/compare/${entry.hash}..HEAD`) } : null,
|
|
240
|
+
"sep",
|
|
241
|
+
{ label: `Copy SHA (${short(entry.hash)})`, icon: icons.copy, onClick: () => copyText(entry.hash, "Commit SHA copied") },
|
|
242
|
+
entry.orphaned ? "sep" : null,
|
|
243
|
+
entry.orphaned ? { label: "Copy rescue command", icon: icons.copy, cls: "warn", onClick: () => copyText(rescueCmd, "Rescue command copied") } : null,
|
|
244
|
+
]);
|
|
245
|
+
});
|
|
246
|
+
|
|
230
247
|
el.addEventListener("input", (e) => {
|
|
231
248
|
if (e.target.id === "reflog-filter") {
|
|
232
249
|
query = e.target.value;
|
package/src/public/js/ui.js
CHANGED
|
@@ -4,12 +4,57 @@ export const WORKTREE = "WORKTREE";
|
|
|
4
4
|
|
|
5
5
|
const avatarMap = Object.create(null);
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
/** Forget avatar URLs (after avatars were turned off). */
|
|
8
|
+
export function clearAvatars() {
|
|
9
|
+
for (const k of Object.keys(avatarMap)) delete avatarMap[k];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Requests that move branches. Change polling ignores results that overlap one, since git-tm
|
|
13
|
+
// itself made that change (see poll() in main.js).
|
|
14
|
+
let historyWrites = 0;
|
|
15
|
+
let historyWriteSeq = 0;
|
|
16
|
+
let ownFingerprint = null;
|
|
17
|
+
/**
|
|
18
|
+
* { busy, seq, fingerprint }: busy while an apply or undo runs; seq changes whenever one starts or
|
|
19
|
+
* ends; fingerprint is the repository state right after git-tm's latest write.
|
|
20
|
+
*/
|
|
21
|
+
export const historyWriteState = () => ({ busy: historyWrites > 0, seq: historyWriteSeq, fingerprint: ownFingerprint });
|
|
22
|
+
|
|
23
|
+
export async function api(path, params = {}, opts = {}) {
|
|
24
|
+
const writes = path === "edit/apply" || path === "edit/undo";
|
|
25
|
+
if (!writes) return request(path, params, opts);
|
|
26
|
+
historyWrites++;
|
|
27
|
+
historyWriteSeq++;
|
|
28
|
+
try {
|
|
29
|
+
const data = await request(path, params, opts);
|
|
30
|
+
try {
|
|
31
|
+
ownFingerprint = (await request("state")).fingerprint;
|
|
32
|
+
} catch {
|
|
33
|
+
/* the next poll may show the banner; harmless */
|
|
34
|
+
}
|
|
35
|
+
return data;
|
|
36
|
+
} finally {
|
|
37
|
+
historyWrites--;
|
|
38
|
+
historyWriteSeq++;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function request(path, params = {}, { method = "GET", body } = {}) {
|
|
8
43
|
const qs = new URLSearchParams();
|
|
9
44
|
for (const [k, v] of Object.entries(params)) {
|
|
10
45
|
if (v !== undefined && v !== null && v !== "" && v !== false) qs.set(k, v === true ? "1" : String(v));
|
|
11
46
|
}
|
|
12
47
|
const query = qs.toString();
|
|
48
|
+
// Inside the VS Code extension there is no HTTP server: requests go to the extension host over postMessage.
|
|
49
|
+
const bridge = globalThis.gitTmBridge;
|
|
50
|
+
if (bridge && typeof bridge.request === "function") {
|
|
51
|
+
const res = await bridge.request({ method, path: `/api/${path}`, query, body });
|
|
52
|
+
const data = res?.data ?? {};
|
|
53
|
+
const status = res?.status ?? 500;
|
|
54
|
+
if (status !== 200) throw Object.assign(new Error(data.error || `Request failed (${status})`), { status, conflicts: data.conflicts });
|
|
55
|
+
if (data.avatars) Object.assign(avatarMap, data.avatars);
|
|
56
|
+
return data;
|
|
57
|
+
}
|
|
13
58
|
const url = `/api/${path}${query ? `?${query}` : ""}`;
|
|
14
59
|
let res;
|
|
15
60
|
try {
|
package/src/server.js
CHANGED
|
@@ -62,16 +62,17 @@ function attachAvatars(enabled, ...lists) {
|
|
|
62
62
|
return map;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
65
|
+
/**
|
|
66
|
+
* The JSON API without a transport: the HTTP server and the VS Code extension both use it, so
|
|
67
|
+
* routes, validation and edit tokens live in one place.
|
|
68
|
+
* handle({ method, path, query, body }) resolves to { status, data } and never throws.
|
|
69
|
+
* `body` is a parsed object, or a function returning a promise of one (read only by routes that need it).
|
|
70
|
+
*/
|
|
71
|
+
export function createApiHandler(repo, { avatars = true, edit = false, onEdit, onLog, editOffMessage } = {}) {
|
|
71
72
|
// Previewed plans, by one-time token, so apply can only move a branch to a tip git-tm computed.
|
|
72
73
|
const plans = new Map();
|
|
73
74
|
const requireEdit = () => {
|
|
74
|
-
if (!edit) throw new GitError("Edit mode is off. Start git-tm with --edit to change history.", 403);
|
|
75
|
+
if (!edit) throw new GitError(editOffMessage || "Edit mode is off. Start git-tm with --edit to change history.", 403);
|
|
75
76
|
};
|
|
76
77
|
|
|
77
78
|
const bool = (v) => v === "1" || v === "true";
|
|
@@ -134,9 +135,9 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1", edit =
|
|
|
134
135
|
requireEdit();
|
|
135
136
|
return { backups: await listBackups(repo) };
|
|
136
137
|
},
|
|
137
|
-
"POST /api/edit/preview": async (q,
|
|
138
|
+
"POST /api/edit/preview": async (q, readBody) => {
|
|
138
139
|
requireEdit();
|
|
139
|
-
const body = await
|
|
140
|
+
const body = await readBody();
|
|
140
141
|
const plan = await planEdit(repo, {
|
|
141
142
|
type: body.op,
|
|
142
143
|
commit: body.commit,
|
|
@@ -151,9 +152,9 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1", edit =
|
|
|
151
152
|
plans.set(token, { plan, expires: now + PLAN_TTL });
|
|
152
153
|
return { token, plan };
|
|
153
154
|
},
|
|
154
|
-
"POST /api/edit/apply": async (q,
|
|
155
|
+
"POST /api/edit/apply": async (q, readBody) => {
|
|
155
156
|
requireEdit();
|
|
156
|
-
const body = await
|
|
157
|
+
const body = await readBody();
|
|
157
158
|
const entry = typeof body.token === "string" ? plans.get(body.token) : null;
|
|
158
159
|
if (!entry || entry.expires < Date.now()) throw new GitError("This preview has expired. Preview the edit again.", 400);
|
|
159
160
|
// A double click must not run the same edit twice (duplicate backups and log entries).
|
|
@@ -169,15 +170,55 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1", edit =
|
|
|
169
170
|
onEdit?.({ ...result, op: entry.plan.type, summary: entry.plan.summary, count: entry.plan.rewritten.length || entry.plan.added.length });
|
|
170
171
|
return result;
|
|
171
172
|
},
|
|
172
|
-
"POST /api/edit/undo": async (q,
|
|
173
|
+
"POST /api/edit/undo": async (q, readBody) => {
|
|
173
174
|
requireEdit();
|
|
174
|
-
const body = await
|
|
175
|
+
const body = await readBody();
|
|
175
176
|
const result = await undoEdit(repo, body.id, { newBranch: body.newBranch });
|
|
176
177
|
onEdit?.({ ...result, op: body.newBranch ? "restore" : "undo" });
|
|
177
178
|
return result;
|
|
178
179
|
},
|
|
179
180
|
};
|
|
180
181
|
|
|
182
|
+
// A broken logger must never fail a request, or get the same request logged twice by the error path.
|
|
183
|
+
const logRequest = (event) => {
|
|
184
|
+
if (!onLog || event.path === "/api/state") return;
|
|
185
|
+
try {
|
|
186
|
+
onLog(event);
|
|
187
|
+
} catch (err) {
|
|
188
|
+
console.error(`onLog failed: ${err?.stack || err}`);
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
/** True when `method path` is a known endpoint. */
|
|
194
|
+
has: (method, path) => Object.hasOwn(routes, `${method} ${path}`),
|
|
195
|
+
async handle({ method = "GET", path, query, body } = {}) {
|
|
196
|
+
const started = performance.now();
|
|
197
|
+
const q = query instanceof URLSearchParams ? query : new URLSearchParams(query || "");
|
|
198
|
+
const route = routes[`${method} ${path}`];
|
|
199
|
+
if (!route) return { status: 404, data: { error: "Unknown endpoint" } };
|
|
200
|
+
const readBody = typeof body === "function" ? body : async () => checkObject(body ?? {});
|
|
201
|
+
try {
|
|
202
|
+
const data = await route(q, readBody);
|
|
203
|
+
logRequest({ method, path, query: q, status: 200, ms: Math.round(performance.now() - started) });
|
|
204
|
+
return { status: 200, data };
|
|
205
|
+
} catch (err) {
|
|
206
|
+
const status = err instanceof GitError ? err.status : 500;
|
|
207
|
+
if (status >= 500) console.error(`${method} ${path}: ${err instanceof GitError ? err.message : err?.stack || err}`);
|
|
208
|
+
logRequest({ method, path, query: q, status, ms: Math.round(performance.now() - started), error: err?.message });
|
|
209
|
+
return { status, data: { error: err?.message || "Internal error", ...(err?.conflicts ? { conflicts: err.conflicts } : {}) } };
|
|
210
|
+
}
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function createServer(repo, { avatars = true, host = "127.0.0.1", edit = false, onEdit, onLog } = {}) {
|
|
216
|
+
const staticCache = new Map();
|
|
217
|
+
const checkHost = LOOPBACK.has(host);
|
|
218
|
+
// Changing history from another device is a different risk from reading it: edit mode is local only.
|
|
219
|
+
if (edit && !checkHost) throw new Error("Edit mode only works on a loopback host (127.0.0.1, localhost or ::1)");
|
|
220
|
+
const api = createApiHandler(repo, { avatars, edit, onEdit, onLog });
|
|
221
|
+
|
|
181
222
|
async function serveStatic(res, pathname) {
|
|
182
223
|
let rel = "index.html";
|
|
183
224
|
if (pathname !== "/") {
|
|
@@ -203,19 +244,7 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1", edit =
|
|
|
203
244
|
res.end(body);
|
|
204
245
|
}
|
|
205
246
|
|
|
206
|
-
// A broken logger must never fail a request, or get the same request logged twice by the error path.
|
|
207
|
-
const logRequest = (event) => {
|
|
208
|
-
if (!onLog || event.path === "/api/state") return;
|
|
209
|
-
try {
|
|
210
|
-
onLog(event);
|
|
211
|
-
} catch (err) {
|
|
212
|
-
console.error(`onLog failed: ${err?.stack || err}`);
|
|
213
|
-
}
|
|
214
|
-
};
|
|
215
|
-
|
|
216
247
|
return http.createServer(async (req, res) => {
|
|
217
|
-
let apiUrl = null;
|
|
218
|
-
const started = onLog ? performance.now() : 0;
|
|
219
248
|
try {
|
|
220
249
|
if (checkHost) {
|
|
221
250
|
const h = (req.headers.host || "").toLowerCase().replace(/:\d+$/, "");
|
|
@@ -226,20 +255,15 @@ export function createServer(repo, { avatars = true, host = "127.0.0.1", edit =
|
|
|
226
255
|
if (req.method !== "GET" && req.method !== "HEAD") return send(res, 405, "Method not allowed");
|
|
227
256
|
return await serveStatic(res, url.pathname);
|
|
228
257
|
}
|
|
229
|
-
|
|
230
|
-
const route = routes[`${req.method} ${url.pathname}`];
|
|
231
|
-
if (!route) return json(res, 404, { error: "Unknown endpoint" });
|
|
258
|
+
if (!api.has(req.method, url.pathname)) return json(res, 404, { error: "Unknown endpoint" });
|
|
232
259
|
// Simple CSRF guard: browsers will not send this custom header cross-origin without a preflight.
|
|
233
260
|
if (req.method !== "GET" && req.headers["x-git-tm"] !== "1") return json(res, 403, { error: "Forbidden" });
|
|
234
|
-
const data = await
|
|
235
|
-
json(res,
|
|
236
|
-
logRequest({ method: req.method, path: url.pathname, query: url.searchParams, status: 200, ms: Math.round(performance.now() - started) });
|
|
261
|
+
const { status, data } = await api.handle({ method: req.method, path: url.pathname, query: url.searchParams, body: () => readJson(req) });
|
|
262
|
+
json(res, status, data);
|
|
237
263
|
} catch (err) {
|
|
238
|
-
|
|
239
|
-
if (status >= 500) console.error(`${req.method} ${req.url}: ${err instanceof GitError ? err.message : err.stack}`);
|
|
240
|
-
if (apiUrl) logRequest({ method: req.method, path: apiUrl.pathname, query: apiUrl.searchParams, status, ms: Math.round(performance.now() - started), error: err.message });
|
|
264
|
+
console.error(`${req.method} ${req.url}: ${err?.stack || err}`);
|
|
241
265
|
if (res.headersSent) res.destroy();
|
|
242
|
-
else json(res,
|
|
266
|
+
else json(res, 500, { error: "Internal error" });
|
|
243
267
|
}
|
|
244
268
|
});
|
|
245
269
|
}
|
|
@@ -261,6 +285,10 @@ async function readJson(req) {
|
|
|
261
285
|
} catch {
|
|
262
286
|
throw new GitError("Invalid JSON body", 400);
|
|
263
287
|
}
|
|
288
|
+
return checkObject(data);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function checkObject(data) {
|
|
264
292
|
if (!data || typeof data !== "object" || Array.isArray(data)) throw new GitError("Expected a JSON object", 400);
|
|
265
293
|
return data;
|
|
266
294
|
}
|
package/src/types/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export * from "./git.js";
|
|
2
|
-
export { createServer, listen } from "./server.js";
|
|
3
|
-
export type { ServerOptions } from "./server.js";
|
|
2
|
+
export { createServer, createApiHandler, listen } from "./server.js";
|
|
3
|
+
export type { ServerOptions, ApiHandler, ApiHandlerOptions, ApiRequest, ApiResponse } from "./server.js";
|
|
4
4
|
export { planEdit, applyEdit, listBackups, undoEdit } from "./edit.js";
|
|
5
5
|
export type { EditType, EditOptions, EditPlan, EditResult, EditBackup } from "./edit.js";
|
|
6
6
|
export { createLayout, layout } from "./graph.js";
|
package/src/types/server.d.ts
CHANGED
|
@@ -14,6 +14,42 @@ export interface ServerOptions {
|
|
|
14
14
|
onLog?: (event: { method: string; path: string; query: URLSearchParams; status: number; ms: number; error?: string }) => void;
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
export interface ApiHandlerOptions {
|
|
18
|
+
/** Include avatar URLs in responses. Default true. */
|
|
19
|
+
avatars?: boolean;
|
|
20
|
+
/** Enable the /api/edit/* routes. The caller decides who can reach the handler. Default false. */
|
|
21
|
+
edit?: boolean;
|
|
22
|
+
/** Error message for edit routes while edit mode is off. */
|
|
23
|
+
editOffMessage?: string;
|
|
24
|
+
onEdit?: ServerOptions["onEdit"];
|
|
25
|
+
onLog?: ServerOptions["onLog"];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ApiRequest {
|
|
29
|
+
method?: "GET" | "POST";
|
|
30
|
+
/** For example "/api/history". */
|
|
31
|
+
path: string;
|
|
32
|
+
query?: URLSearchParams | string | Record<string, string>;
|
|
33
|
+
/** A parsed JSON object, or a function that resolves to one (read only by routes that need a body). */
|
|
34
|
+
body?: object | (() => Promise<object>);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ApiResponse {
|
|
38
|
+
status: number;
|
|
39
|
+
/** The route's result, or { error, conflicts? } when status is not 200. */
|
|
40
|
+
data: any;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface ApiHandler {
|
|
44
|
+
/** True when `method path` is a known endpoint. */
|
|
45
|
+
has(method: string, path: string): boolean;
|
|
46
|
+
/** Run one API request. Never rejects: errors come back with a 4xx/5xx status. */
|
|
47
|
+
handle(request: ApiRequest): Promise<ApiResponse>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The git-tm JSON API without a transport, shared by createServer() and the VS Code extension. */
|
|
51
|
+
export function createApiHandler(repo: Repo, options?: ApiHandlerOptions): ApiHandler;
|
|
52
|
+
|
|
17
53
|
/** An HTTP server for the git-tm web interface and its JSON API. Call listen() to start it. */
|
|
18
54
|
export function createServer(repo: Repo, options?: ServerOptions): Server;
|
|
19
55
|
|