decklight 0.5.0 → 0.6.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 +4 -1
- package/SPEC.md +78 -12
- package/cli/agents.mjs +45 -0
- package/cli/commit-message.mjs +350 -0
- package/cli/decklight.mjs +7 -0
- package/cli/dev.mjs +35 -13
- package/cli/edit.mjs +139 -11
- package/cli/git.mjs +348 -0
- package/cli/history.mjs +145 -0
- package/cli/init.mjs +162 -2
- package/cli/marketplace.mjs +123 -17
- package/cli/port-conflict.mjs +41 -6
- package/cli/present.mjs +297 -12
- package/cli/restore.mjs +120 -4
- package/cli/serve.mjs +24 -0
- package/cli/skill-content.mjs +9 -0
- package/cli/theme.mjs +78 -11
- package/cli/upstream.mjs +256 -0
- package/dist/decklight.css +290 -2
- package/dist/decklight.js +67 -64
- package/dist/decklight.js.map +4 -4
- package/package.json +1 -1
- package/tools/deck-html.mjs +34 -0
- package/tools/tts-engines.mjs +186 -9
- package/tools/tts-setup.mjs +1 -8
- package/tools/video.mjs +44 -12
- package/tools/voiceover-server.mjs +95 -4
- package/tools/voiceover.mjs +2 -12
package/cli/edit.mjs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// `edit` out loud — author spawns this module directly:
|
|
8
8
|
//
|
|
9
9
|
// node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
|
|
10
|
-
// [--commit-every <seconds>] [--agent <name>]
|
|
10
|
+
// [--commit-every <seconds>] [--agent <name>] [--commit-messages]
|
|
11
11
|
//
|
|
12
12
|
// It binds 127.0.0.1 and nothing else. The phone remote used to be here behind
|
|
13
13
|
// `--remote`, which meant a clicker cost you an editing server on the LAN;
|
|
@@ -46,14 +46,14 @@
|
|
|
46
46
|
// `decklight author` asks interactively before passing --git down.
|
|
47
47
|
|
|
48
48
|
import { createServer } from 'node:http';
|
|
49
|
-
import { readFileSync, writeFileSync, watch, existsSync } from 'node:fs';
|
|
49
|
+
import { readFileSync, writeFileSync, mkdirSync, watch, existsSync } from 'node:fs';
|
|
50
50
|
import { resolve, sep, basename } from 'node:path';
|
|
51
51
|
import { spawn } from 'node:child_process';
|
|
52
52
|
import { agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent } from './agents.mjs';
|
|
53
53
|
import { exitWhenOrphaned } from './supervise.mjs';
|
|
54
54
|
import { argReader, isMain } from '../tools/args.mjs';
|
|
55
55
|
import { NOTES_ASIDE, locateSlide, sectionChildRanges } from '../tools/deck-html.mjs';
|
|
56
|
-
import { deckHistory, restoreDeck, deckAt, withBaseHref } from './restore.mjs';
|
|
56
|
+
import { deckHistory, decorateHistory, restoreDeck, deckAt, withBaseHref } from './restore.mjs';
|
|
57
57
|
import { escapeHtml, sseChannel, staticFiles, listenTakingOverIfNeeded, allowEditRequest } from './serve.mjs';
|
|
58
58
|
import { configureEngine, loadCredentials, forgetCredentials, redactAnswers, validateSchema, provenance, BRIDGE_ADDR, CONFIGURED, UNREACHABLE, PREREQUISITE } from './wizard.mjs';
|
|
59
59
|
|
|
@@ -197,13 +197,14 @@ export function createHistory(limit = 200) {
|
|
|
197
197
|
// The plumbing lives in git.mjs now; imported for editMain's use below and
|
|
198
198
|
// re-exported so long-standing importers (init, the tests) keep finding it
|
|
199
199
|
// where edit grew it.
|
|
200
|
-
import { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit, resolveGitMode, shouldCommit, commitSubject, oneline } from './git.mjs';
|
|
200
|
+
import { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit, lastCommitSha, resolveGitMode, shouldCommit, commitSubject, exitPushLine, oneline, remoteLine, remoteState, unpushed } from './git.mjs';
|
|
201
|
+
import { describeCommit, messagesLine } from './commit-message.mjs';
|
|
201
202
|
export { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit };
|
|
202
203
|
|
|
203
204
|
export async function editMain(args) {
|
|
204
205
|
if (args.includes('--help') || args.includes('-h') || !args.filter((a) => !a.startsWith('-')).length) {
|
|
205
206
|
console.log(`usage: node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
|
|
206
|
-
[--commit-every <seconds>] [--agent <name>]
|
|
207
|
+
[--commit-every <seconds>] [--agent <name>] [--commit-messages]
|
|
207
208
|
serves the cwd, live-reloads the deck on change, and accepts edits from the
|
|
208
209
|
player: notes (right-click a slide's background), per-slide layout (L/⇧L),
|
|
209
210
|
element edit mode (E, then right-click an element), undo/redo (Z/⇧Z), agent asks (A)
|
|
@@ -260,6 +261,41 @@ export async function editMain(args) {
|
|
|
260
261
|
const noGit = args.includes('--no-git');
|
|
261
262
|
const wantGit = args.includes('--git');
|
|
262
263
|
const commitEvery = Math.max(5, Number(opt('--commit-every', 300)) || 300);
|
|
264
|
+
// --commit-messages: an agent writes the subject decklight would otherwise
|
|
265
|
+
// template. Opt-in, because it sends the deck's diffs to whichever agent CLI
|
|
266
|
+
// is installed and most of them are cloud-backed — a permission decklight
|
|
267
|
+
// does not infer from what happens to be on PATH.
|
|
268
|
+
const wantMessages = args.includes('--commit-messages');
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Every commit decklight authors ITSELF goes through here — the cadence, the
|
|
272
|
+
* session bookends, the save that clears the way before an agent edit.
|
|
273
|
+
*
|
|
274
|
+
* One funnel, because the amend has to happen right after the commit while
|
|
275
|
+
* the sha is still the tip, and a second call site that forgot to ask would
|
|
276
|
+
* silently be the one that keeps saying "autosave". Commits made from an
|
|
277
|
+
* AGENT'S OWN message do not come through here: they already say what
|
|
278
|
+
* happened, and asking an agent to rewrite an agent's sentence is a call
|
|
279
|
+
* that buys nothing.
|
|
280
|
+
*
|
|
281
|
+
* The describe is deliberately unawaited. The commit has landed by the time
|
|
282
|
+
* this returns, which is the whole contract of autocommit — the subject is
|
|
283
|
+
* an improvement that arrives late or not at all.
|
|
284
|
+
*/
|
|
285
|
+
function ownCommit(message) {
|
|
286
|
+
const made = message === undefined
|
|
287
|
+
? gitAutocommit(deckPath, root)
|
|
288
|
+
: gitAutocommit(deckPath, root, message);
|
|
289
|
+
if (!made) return false;
|
|
290
|
+
const sha = lastCommitSha;
|
|
291
|
+
if (wantMessages && sha) {
|
|
292
|
+
const template = message ?? `decklight: autosave ${basename(deckPath)}`;
|
|
293
|
+
describeCommit({ cwd: root, sha, deckPath, template, agent: agentPref })
|
|
294
|
+
.then((subject) => { if (subject) console.log(` git: subject → "${subject}"`); })
|
|
295
|
+
.catch(() => { /* the commit stands; the wording was the optional part */ });
|
|
296
|
+
}
|
|
297
|
+
return true;
|
|
298
|
+
}
|
|
263
299
|
// timer (default, unchanged) · agent (one commit per agent edit) · off
|
|
264
300
|
const gitMode = resolveGitMode(args);
|
|
265
301
|
let gitOn = false;
|
|
@@ -274,21 +310,34 @@ export async function editMain(args) {
|
|
|
274
310
|
}
|
|
275
311
|
if (inGitRepo(root)) {
|
|
276
312
|
gitOn = true;
|
|
277
|
-
|
|
313
|
+
ownCommit(`decklight: start editing ${basename(deckPath)}`);
|
|
278
314
|
// The cadence is the backstop, and it runs in agent mode too: an agent
|
|
279
315
|
// job only ever sees edits IT made, so hand edits — and any agent driven
|
|
280
316
|
// from outside the A flow — would otherwise reach git only via the
|
|
281
317
|
// Ctrl-C bookend, which a crash skips. It is held back while a job is in
|
|
282
318
|
// flight so nothing commits a half-finished agent run.
|
|
283
319
|
setInterval(() => {
|
|
284
|
-
if (shouldCommit(gitMode, { kind: 'timer', agentBusy: !!agentJob }))
|
|
320
|
+
if (shouldCommit(gitMode, { kind: 'timer', agentBusy: !!agentJob })) ownCommit();
|
|
285
321
|
}, commitEvery * 1000).unref();
|
|
286
322
|
console.log(gitMode === 'agent'
|
|
287
323
|
? ` git: committing ${deckRel} once per agent edit with the agent's own message, every ${commitEvery}s otherwise (and on Ctrl-C)`
|
|
288
324
|
: ` git: auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`);
|
|
289
325
|
}
|
|
290
326
|
}
|
|
291
|
-
const finalCommit = () => {
|
|
327
|
+
const finalCommit = () => {
|
|
328
|
+
if (!gitOn) return;
|
|
329
|
+
// Not ownCommit: this runs inside the SIGINT handler and the process exits
|
|
330
|
+
// immediately after, so there is no later for an amend to arrive in. The
|
|
331
|
+
// bookend keeps its literal subject, which is true anyway.
|
|
332
|
+
gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`);
|
|
333
|
+
// The last moment anyone is looking. Synchronous and fetch-free on purpose:
|
|
334
|
+
// this runs inside the SIGINT handler, and a network call there would hang
|
|
335
|
+
// a Ctrl-C — the worst possible place to hang.
|
|
336
|
+
try {
|
|
337
|
+
const line = exitPushLine(remoteState(root));
|
|
338
|
+
if (line) console.log(line);
|
|
339
|
+
} catch { /* a reminder is never worth failing an exit over */ }
|
|
340
|
+
};
|
|
292
341
|
process.on('SIGINT', () => { finalCommit(); process.exit(0); });
|
|
293
342
|
process.on('SIGTERM', () => { finalCommit(); process.exit(0); });
|
|
294
343
|
|
|
@@ -306,6 +355,14 @@ export async function editMain(args) {
|
|
|
306
355
|
if (agentPref && !agents.some((a) => a.name === agentPref)) {
|
|
307
356
|
console.log(` agent: ${agentUnavailable(agentPref, agents)}`);
|
|
308
357
|
}
|
|
358
|
+
// Said out loud, every session it is on: this is the switch that starts
|
|
359
|
+
// sending the deck somewhere, and a capability nobody is reminded of is one
|
|
360
|
+
// they stop counting on being off. Printed HERE rather than up with the other
|
|
361
|
+
// git lines because it names the agent, and the roster is only resolved now.
|
|
362
|
+
if (gitOn && wantMessages) {
|
|
363
|
+
const who = agents.find((a) => a.name === agentPref) ?? agents[0];
|
|
364
|
+
console.log(` ${messagesLine(who?.name ?? null)}`);
|
|
365
|
+
}
|
|
309
366
|
|
|
310
367
|
// ── live reload: watch the deck, broadcast SSE (debounced — editors fire
|
|
311
368
|
// multiple fs events per save) ─────────────────────────────────────────
|
|
@@ -450,7 +507,7 @@ export async function editMain(args) {
|
|
|
450
507
|
// under the agent's message, and a history that misattributes authorship is
|
|
451
508
|
// worse than one that only says "autosave".
|
|
452
509
|
if (gitOn && shouldCommit(gitMode, { kind: 'bookend' })
|
|
453
|
-
&&
|
|
510
|
+
&& ownCommit(`decklight: save before ${cmd.name} edits ${basename(deckPath)}`)) {
|
|
454
511
|
console.log(' git: committed your outstanding changes first');
|
|
455
512
|
}
|
|
456
513
|
const before = readDeck();
|
|
@@ -517,6 +574,9 @@ export async function editMain(args) {
|
|
|
517
574
|
return json(200, {
|
|
518
575
|
ok: true, deck: deckUrl, name: basename(deckPath),
|
|
519
576
|
...history.counts(), git: gitOn,
|
|
577
|
+
// What the player's one push nudge reads. Computed once, like everything
|
|
578
|
+
// else on ping: the toast is threshold-driven, not live.
|
|
579
|
+
remote: gitOn ? remoteState(root) : null,
|
|
520
580
|
agents: agents.map((a) => ({ name: a.name, label: a.label })),
|
|
521
581
|
// which one A reaches for, so the picker opens on it rather than
|
|
522
582
|
// defaulting to the first detected agent every session (#125)
|
|
@@ -534,8 +594,31 @@ export async function editMain(args) {
|
|
|
534
594
|
// historical revisions of the deck, which is nobody else's business.
|
|
535
595
|
if (req.method === 'GET' && url.pathname === '/edit/history') {
|
|
536
596
|
if (!gitOn) return json(409, { ok: false, error: 'git is off for this session — there is no history' });
|
|
537
|
-
try {
|
|
538
|
-
|
|
597
|
+
try {
|
|
598
|
+
// One round trip serves the whole overlay: the commits, which of them
|
|
599
|
+
// exist nowhere but this machine, and where the branch stands. All of
|
|
600
|
+
// it is a LOCAL read — `unpushed` and `@{u}` read remote-tracking
|
|
601
|
+
// refs, so opening the history never touches the network (SPEC
|
|
602
|
+
// PRESENTING).
|
|
603
|
+
// `slides` is what that version WAS, `add`/`del` what it CHANGED —
|
|
604
|
+
// the two questions a hash and a subject cannot answer, and the ones
|
|
605
|
+
// that tell "tightened the wording" apart from "cut four slides"
|
|
606
|
+
// before you restore it rather than after.
|
|
607
|
+
const entries = decorateHistory(deckHistory(deckPath, root), deckPath, root);
|
|
608
|
+
const remote = remoteState(root);
|
|
609
|
+
// `pushed` is null for "not a question worth answering here", and the
|
|
610
|
+
// two cases are different: git could not tell us, or there is no
|
|
611
|
+
// remote at all — in which case EVERY commit is unpushed and marking
|
|
612
|
+
// all of them is a wall of arrows saying what the footer says once.
|
|
613
|
+
const local = ['no-remote', 'ambiguous-remote'].includes(remote.state) ? null : unpushed(root);
|
|
614
|
+
const set = local ? new Set(local) : null;
|
|
615
|
+
for (const e of entries) e.pushed = set ? !set.has(e.full) : null;
|
|
616
|
+
// The LINE is computed here, not in the player: cli/git.mjs is Node
|
|
617
|
+
// (it spawns git), the runtime has zero dependencies and cannot
|
|
618
|
+
// import it, and duplicating the wording in the browser is how the
|
|
619
|
+
// four places that talk about unpushed work start disagreeing.
|
|
620
|
+
return json(200, { ok: true, entries, remote: { ...remote, line: remoteLine(remote) } });
|
|
621
|
+
} catch (e) { return json(500, { ok: false, error: oneline(e) }); }
|
|
539
622
|
}
|
|
540
623
|
if (req.method === 'GET' && url.pathname === '/edit/at') {
|
|
541
624
|
if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
|
|
@@ -587,6 +670,51 @@ export async function editMain(args) {
|
|
|
587
670
|
console.log(` ${dir} → ${JSON.stringify(history.counts())}`);
|
|
588
671
|
return json(200, { ok: true, ...history.counts() });
|
|
589
672
|
}
|
|
673
|
+
// ── ⇧V offline recordings (PRESENTING) ───────────────────────────────
|
|
674
|
+
// The player used to hand every stitched slide to the browser's DOWNLOAD
|
|
675
|
+
// path, which is why a deck's voice arrived as thirty slide-NN.wav in
|
|
676
|
+
// whatever folder the OS calls Downloads — never the deck's, and on
|
|
677
|
+
// Windows not even near it. `bundle` only ever looks NEXT TO THE DECK, so
|
|
678
|
+
// the recording was finished and in the wrong place, and the last step
|
|
679
|
+
// was moving files by hand. In author mode the server that already owns
|
|
680
|
+
// the deck file writes them itself.
|
|
681
|
+
//
|
|
682
|
+
// Ahead of the shared body read below because this body is BINARY and
|
|
683
|
+
// megabytes of it: a slide of speech is ~48 kB a second, so the string
|
|
684
|
+
// concat and its 1 MB ceiling would both be wrong.
|
|
685
|
+
if (req.method === 'POST' && url.pathname === '/edit/record') {
|
|
686
|
+
const slide = Number(url.searchParams.get('slide'));
|
|
687
|
+
const kind = url.searchParams.get('kind');
|
|
688
|
+
if (!Number.isInteger(slide) || slide < 1 || slide > 9999) return json(400, { ok: false, error: 'bad slide' });
|
|
689
|
+
if (kind !== 'wav' && kind !== 'visemes') return json(400, { ok: false, error: 'bad kind' });
|
|
690
|
+
// The player names the FOLDER (its own `narration.files`, so a recorded
|
|
691
|
+
// set lands where that deck already plays from) and nothing else: the
|
|
692
|
+
// file name is built here, so no request can choose one. The folder is
|
|
693
|
+
// contained to the served root by the same rule staticFiles reads by —
|
|
694
|
+
// and `..`, absolute paths and Windows drive letters are refused before
|
|
695
|
+
// it, because `resolve` would happily swallow all three.
|
|
696
|
+
const want = url.searchParams.get('dir') || 'voiceover';
|
|
697
|
+
const bad = want.length > 200 || /^[/\\]/.test(want) || /^[a-zA-Z]:/.test(want)
|
|
698
|
+
|| want.split(/[/\\]/).includes('..');
|
|
699
|
+
const dir = bad ? null : resolve(deckPath, '..', want);
|
|
700
|
+
if (!dir || (!dir.startsWith(root + sep) && dir !== root)) {
|
|
701
|
+
return json(400, { ok: false, error: 'the recording folder must sit inside the deck\'s own directory' });
|
|
702
|
+
}
|
|
703
|
+
const name = `slide-${String(slide).padStart(2, '0')}.${kind === 'wav' ? 'wav' : 'visemes.json'}`;
|
|
704
|
+
const chunks = [];
|
|
705
|
+
let size = 0;
|
|
706
|
+
for await (const chunk of req) {
|
|
707
|
+
size += chunk.length;
|
|
708
|
+
if (size > 64e6) return json(413, { ok: false, error: 'recording too large' });
|
|
709
|
+
chunks.push(chunk);
|
|
710
|
+
}
|
|
711
|
+
try {
|
|
712
|
+
mkdirSync(dir, { recursive: true });
|
|
713
|
+
writeFileSync(resolve(dir, name), Buffer.concat(chunks));
|
|
714
|
+
} catch (e) { return json(500, { ok: false, error: oneline(e) }); }
|
|
715
|
+
console.log(` recorded ${want}/${name} (${Math.round(size / 1024)} kB)`);
|
|
716
|
+
return json(200, { ok: true, dir: want, file: name });
|
|
717
|
+
}
|
|
590
718
|
let body = '';
|
|
591
719
|
if (req.method === 'POST') {
|
|
592
720
|
for await (const chunk of req) { body += chunk; if (body.length > 1e6) throw new Error('too large'); }
|
package/cli/git.mjs
CHANGED
|
@@ -120,7 +120,19 @@ export function commitSubject(raw, fallback) {
|
|
|
120
120
|
return /^-/.test(capped) ? `agent: ${capped}` : capped;
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
+
/**
|
|
124
|
+
* The sha of the commit `gitAutocommit` last made, or null.
|
|
125
|
+
*
|
|
126
|
+
* Kept beside the commit rather than returned in its place because every
|
|
127
|
+
* existing caller treats the return value as a boolean — "did anything land" —
|
|
128
|
+
* and widening that to an object would put a truthiness question in front of
|
|
129
|
+
* the safety net. `--commit-messages` is the only caller that needs the sha,
|
|
130
|
+
* and it reads it immediately.
|
|
131
|
+
*/
|
|
132
|
+
export let lastCommitSha = null;
|
|
133
|
+
|
|
123
134
|
export function gitAutocommit(deckPath, cwd, message = `decklight: autosave ${basename(deckPath)}`) {
|
|
135
|
+
lastCommitSha = null;
|
|
124
136
|
try {
|
|
125
137
|
if (!git(['status', '--porcelain', '--', deckPath], cwd)) return false;
|
|
126
138
|
git(['add', '--', deckPath], cwd);
|
|
@@ -133,9 +145,345 @@ export function gitAutocommit(deckPath, cwd, message = `decklight: autosave ${ba
|
|
|
133
145
|
git(['-c', 'user.name=decklight', '-c', 'user.email=decklight@localhost',
|
|
134
146
|
'commit', '-m', message, '--', deckPath], cwd);
|
|
135
147
|
}
|
|
148
|
+
try { lastCommitSha = git(['rev-parse', 'HEAD'], cwd); } catch { lastCommitSha = null; }
|
|
136
149
|
return true;
|
|
137
150
|
} catch (e) {
|
|
138
151
|
console.error(` git autocommit failed: ${oneline(e)}`);
|
|
139
152
|
return false;
|
|
140
153
|
}
|
|
141
154
|
}
|
|
155
|
+
|
|
156
|
+
// ── the remote half ────────────────────────────────────────────────────────
|
|
157
|
+
//
|
|
158
|
+
// Everything above is LOCAL: does a repo exist, is the tree dirty, commit it.
|
|
159
|
+
// That was the whole vocabulary, and it is why decklight could commit
|
|
160
|
+
// diligently for a week and never once mention that none of it existed anywhere
|
|
161
|
+
// but this laptop.
|
|
162
|
+
//
|
|
163
|
+
// Two rules govern this section, and both are learned rather than assumed:
|
|
164
|
+
//
|
|
165
|
+
// NEVER A HANG. `GIT_TERMINAL_PROMPT=0` is what cloneMarketplace already uses,
|
|
166
|
+
// and it is HALF the answer: it stops git's own prompts and the https askpass,
|
|
167
|
+
// while an `ssh://` remote will still sit forever on a host-key or passphrase
|
|
168
|
+
// question nobody is there to type. `ssh -oBatchMode=yes` is the other half.
|
|
169
|
+
// Blanking the askpass variables stops a GUI credential window opening behind a
|
|
170
|
+
// headless probe, without disabling real credential HELPERS (osxkeychain,
|
|
171
|
+
// libsecret), which is what makes a private remote work at all.
|
|
172
|
+
//
|
|
173
|
+
// NEVER A FETCH YOU DID NOT ASK FOR. cli/marketplace.mjs already decided this
|
|
174
|
+
// for catalogs — "nothing ever pulls into it, which is what keeps decklight out
|
|
175
|
+
// of the credential-helper trap a background `git pull` walks into" — and the
|
|
176
|
+
// same holds here. Everything the author loop reads (`unpushed`, `@{u}`) is a
|
|
177
|
+
// LOCAL read of remote-tracking refs and needs no network at all. `behind` is
|
|
178
|
+
// therefore as fresh as your last fetch, and saying so is better than fetching
|
|
179
|
+
// behind someone's back.
|
|
180
|
+
|
|
181
|
+
/** The env every remote-touching git call runs under. See the note above. */
|
|
182
|
+
export function noPromptEnv(env = process.env) {
|
|
183
|
+
const { GIT_ASKPASS, SSH_ASKPASS, ...rest } = env;
|
|
184
|
+
return {
|
|
185
|
+
...rest,
|
|
186
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
187
|
+
GIT_SSH_COMMAND: rest.GIT_SSH_COMMAND ?? 'ssh -oBatchMode=yes -oConnectTimeout=5',
|
|
188
|
+
GCM_INTERACTIVE: 'Never',
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* `git rev-list --left-right --count @{u}...HEAD` → `{ ahead, behind }`.
|
|
194
|
+
*
|
|
195
|
+
* THE LEFT COUNT IS `behind`. With `A...B` the left side is what is reachable
|
|
196
|
+
* from A and not B; A is the upstream, so the left number is what the upstream
|
|
197
|
+
* has and you do not. Getting this backwards is the classic bug in this command
|
|
198
|
+
* — it type-checks, it looks right, and it reports your unpushed work as the
|
|
199
|
+
* other side's — so the parse is its own function with its own test.
|
|
200
|
+
*/
|
|
201
|
+
export function parseAheadBehind(out) {
|
|
202
|
+
const parts = String(out ?? '').trim().split(/\s+/);
|
|
203
|
+
if (parts.length !== 2) return null;
|
|
204
|
+
const [behind, ahead] = parts.map(Number);
|
|
205
|
+
if (!Number.isInteger(behind) || !Number.isInteger(ahead) || behind < 0 || ahead < 0) return null;
|
|
206
|
+
return { ahead, behind };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Which remote to speak of when a command has to name one.
|
|
211
|
+
*
|
|
212
|
+
* Pure, because "several remotes and none called origin" is a real repository
|
|
213
|
+
* and guessing there would put someone's work on the wrong host.
|
|
214
|
+
*/
|
|
215
|
+
export function preferredRemote(names = []) {
|
|
216
|
+
if (!names.length) return { name: null, state: 'none' };
|
|
217
|
+
if (names.includes('origin')) return { name: 'origin', state: 'ok' };
|
|
218
|
+
if (names.length === 1) return { name: names[0], state: 'ok' };
|
|
219
|
+
return { name: null, state: 'ambiguous' };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Why a remote operation failed, as a word.
|
|
224
|
+
*
|
|
225
|
+
* The distinction that matters is `denied` versus `offline`: one means "your
|
|
226
|
+
* credentials do not open this", the other "nothing was reachable", and telling
|
|
227
|
+
* someone to check their network when the answer is a missing key wastes the
|
|
228
|
+
* ten minutes before a talk. `offline` also covers the timeout, because a
|
|
229
|
+
* remote that did not answer inside the bound is indistinguishable from one
|
|
230
|
+
* that is not there — and both are answers rather than hangs.
|
|
231
|
+
*/
|
|
232
|
+
export function classifyRemoteError(e) {
|
|
233
|
+
const text = String(e?.stderr || e?.message || e || '');
|
|
234
|
+
if (e?.signal || /\bETIMEDOUT\b|timed out/i.test(text)) return 'offline';
|
|
235
|
+
if (/could not resolve host|could not resolve hostname|network is unreachable|connection refused|connection timed out|failed to connect|unable to access/i.test(text)) return 'offline';
|
|
236
|
+
if (/authentication failed|permission denied|could not read (username|password)|terminal prompts disabled|access denied|\b403\b/i.test(text)) return 'denied';
|
|
237
|
+
if (/repository not found|does not appear to be a git repository|\b404\b/i.test(text)) return 'gone';
|
|
238
|
+
return 'unknown';
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Is this string safe to hand to `git remote add` as a URL?
|
|
243
|
+
*
|
|
244
|
+
* The leading-dash refusal is the point: `git remote add origin
|
|
245
|
+
* --upload-pack=…` is an argument, not a URL, and `git remote add` offers no
|
|
246
|
+
* `--` terminator to hide behind. Same reasoning as commitSubject's dash rule.
|
|
247
|
+
*/
|
|
248
|
+
export function looksLikeGitUrl(s) {
|
|
249
|
+
const v = String(s ?? '').trim();
|
|
250
|
+
if (!v || v.startsWith('-')) return false;
|
|
251
|
+
if (/^(https?|ssh|git|file):\/\//i.test(v)) return true;
|
|
252
|
+
if (/^[\w.-]+@[\w.-]+:[^\s]+$/.test(v)) return true; // scp form: git@host:owner/repo
|
|
253
|
+
return v.startsWith('/'); // a local path is a remote too
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// ── the probes, and the one object that answers "where does this stand?" ────
|
|
257
|
+
|
|
258
|
+
/** Is git installed at all? `inGitRepo` swallows ENOENT, so it cannot tell you. */
|
|
259
|
+
export function gitAvailable(cwd = process.cwd(), exec = execFileSync) {
|
|
260
|
+
try { git(['--version'], cwd, exec); return true; } catch { return false; }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Every remote's name, or `[]` — a repository with none is normal, not an error. */
|
|
264
|
+
export function remoteNames(cwd, run = git) {
|
|
265
|
+
try { return run(['remote'], cwd).split('\n').map((s) => s.trim()).filter(Boolean); }
|
|
266
|
+
catch { return []; }
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** A remote's URL, for display only. Nothing branches on it. */
|
|
270
|
+
export function remoteUrl(name, cwd, run = git) {
|
|
271
|
+
try { return run(['remote', 'get-url', name], cwd) || null; } catch { return null; }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* What HEAD is: a branch, a detached commit, or nothing committed yet.
|
|
276
|
+
*
|
|
277
|
+
* The order is the correctness. An unborn HEAD (`git init`, nothing committed)
|
|
278
|
+
* has a symbolic-ref but no commit, so asking about the commit first is what
|
|
279
|
+
* distinguishes it from a detached one.
|
|
280
|
+
*/
|
|
281
|
+
export function headState(cwd, run = git) {
|
|
282
|
+
try { run(['rev-parse', '--verify', '--quiet', 'HEAD'], cwd); }
|
|
283
|
+
catch { return { state: 'unborn', branch: null }; }
|
|
284
|
+
try {
|
|
285
|
+
const branch = run(['symbolic-ref', '--short', '-q', 'HEAD'], cwd);
|
|
286
|
+
return branch ? { state: 'ok', branch } : { state: 'detached', branch: null };
|
|
287
|
+
} catch { return { state: 'detached', branch: null }; }
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** The branch's upstream (`origin/main`), or null when it tracks nothing. */
|
|
291
|
+
export function upstreamOf(cwd, run = git) {
|
|
292
|
+
try { return run(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], cwd) || null; }
|
|
293
|
+
catch { return null; }
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** `{ ahead, behind }` against the upstream, or null. A LOCAL read — no fetch. */
|
|
297
|
+
export function aheadBehind(cwd, run = git) {
|
|
298
|
+
try { return parseAheadBehind(run(['rev-list', '--left-right', '--count', '@{u}...HEAD'], cwd)); }
|
|
299
|
+
catch { return null; }
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Commits that exist on no remote at all — the number the UI should show.
|
|
304
|
+
*
|
|
305
|
+
* Deliberately not `ahead`. This needs NO upstream, so a freshly added remote
|
|
306
|
+
* with nothing pushed still gets a truthful count where `@{u}` would simply
|
|
307
|
+
* fail; with no remotes at all it degrades to "every commit", which is exactly
|
|
308
|
+
* right ("none of this exists anywhere else"); and it is per-commit, so an
|
|
309
|
+
* overlay can mark the rows rather than print a number.
|
|
310
|
+
*/
|
|
311
|
+
export function unpushed(cwd, run = git) {
|
|
312
|
+
try { return run(['rev-list', 'HEAD', '--not', '--remotes'], cwd).split('\n').filter(Boolean); }
|
|
313
|
+
catch { return null; }
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Where this repository stands, as one object. Never throws, never networks.
|
|
318
|
+
*
|
|
319
|
+
* Resolution is ordered and short-circuits, because each state makes the next
|
|
320
|
+
* question meaningless: you cannot be behind a remote you do not have, and you
|
|
321
|
+
* cannot be ahead of an upstream when HEAD is not on a branch.
|
|
322
|
+
*/
|
|
323
|
+
export function remoteState(cwd, { run = git, exec = execFileSync } = {}) {
|
|
324
|
+
const nothing = { remote: null, url: null, branch: null, upstream: null, ahead: null, behind: null, unpushed: null, why: null };
|
|
325
|
+
if (!gitAvailable(cwd, exec)) return { ...nothing, state: 'no-git' };
|
|
326
|
+
if (!inGitRepo(cwd, exec)) return { ...nothing, state: 'no-repo' };
|
|
327
|
+
|
|
328
|
+
const head = headState(cwd, run);
|
|
329
|
+
if (head.state === 'unborn') return { ...nothing, state: 'unborn' };
|
|
330
|
+
|
|
331
|
+
const local = unpushed(cwd, run);
|
|
332
|
+
const base = { ...nothing, branch: head.branch, unpushed: local ? local.length : null };
|
|
333
|
+
if (head.state === 'detached') return { ...base, state: 'detached' };
|
|
334
|
+
|
|
335
|
+
const picked = preferredRemote(remoteNames(cwd, run));
|
|
336
|
+
if (picked.state === 'none') return { ...base, state: 'no-remote' };
|
|
337
|
+
if (picked.state === 'ambiguous') return { ...base, state: 'ambiguous-remote' };
|
|
338
|
+
|
|
339
|
+
const withRemote = { ...base, remote: picked.name, url: remoteUrl(picked.name, cwd, run) };
|
|
340
|
+
const upstream = upstreamOf(cwd, run);
|
|
341
|
+
if (!upstream) return { ...withRemote, state: 'no-upstream' };
|
|
342
|
+
|
|
343
|
+
const counts = aheadBehind(cwd, run);
|
|
344
|
+
if (!counts) return { ...withRemote, upstream, state: 'unreadable', why: 'could not count against the upstream' };
|
|
345
|
+
return { ...withRemote, upstream, ...counts, state: 'ok' };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ── the words ──────────────────────────────────────────────────────────────
|
|
349
|
+
//
|
|
350
|
+
// Four places tell you about unpushed work — a toast while authoring, a line
|
|
351
|
+
// when author mode exits, the history overlay's footer, and `decklight
|
|
352
|
+
// history` — and they must not disagree. So none of them writes a sentence:
|
|
353
|
+
// they all call one of the three functions below. A wording change is then a
|
|
354
|
+
// diff in one file with a test beside it, rather than four strings that were
|
|
355
|
+
// the same in March.
|
|
356
|
+
|
|
357
|
+
/** The push command that would actually work here, given what is set up. */
|
|
358
|
+
const pushCommand = (s) => (s.state === 'no-upstream'
|
|
359
|
+
? `git push -u ${s.remote} ${s.branch}`
|
|
360
|
+
: 'git push');
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Is there something to nudge about, and how much? `null` for "say nothing".
|
|
364
|
+
*
|
|
365
|
+
* The `ahead === 0` row returning null is the do-not-nag guarantee, and it is
|
|
366
|
+
* stated here rather than at each call site so it cannot be forgotten at one of
|
|
367
|
+
* them. A repository with NO remote also returns null: telling someone to push
|
|
368
|
+
* when there is nowhere to push is noise, and that nudge belongs to `init`.
|
|
369
|
+
*/
|
|
370
|
+
export function pushHint(s) {
|
|
371
|
+
if (!s || ['no-git', 'no-repo', 'unborn', 'unreadable'].includes(s.state)) return null;
|
|
372
|
+
if (s.state === 'detached') return { kind: 'detached', n: 0, text: 'detached HEAD — there is no branch to push' };
|
|
373
|
+
if (s.state === 'no-remote' || s.state === 'ambiguous-remote') return null;
|
|
374
|
+
const n = s.state === 'ok' ? s.ahead : s.unpushed;
|
|
375
|
+
if (!n) return null;
|
|
376
|
+
return { kind: s.state === 'ok' ? 'unpushed' : 'no-upstream', n, text: `↑${n} unpushed — ${pushCommand(s)}` };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* The line author mode prints on its way out, or null for a clean exit.
|
|
381
|
+
*
|
|
382
|
+
* This one DOES speak up when there is no remote, unlike `pushHint` — the end
|
|
383
|
+
* of a session is the moment when "this only exists here" is worth knowing, and
|
|
384
|
+
* it is said once rather than every few minutes.
|
|
385
|
+
*/
|
|
386
|
+
export function exitPushLine(s) {
|
|
387
|
+
if (!s) return null;
|
|
388
|
+
if (s.state === 'no-remote' || s.state === 'ambiguous-remote') {
|
|
389
|
+
return s.unpushed
|
|
390
|
+
? ` this deck's history is only on this machine — back it up: git remote add origin <url>`
|
|
391
|
+
: null;
|
|
392
|
+
}
|
|
393
|
+
const hint = pushHint(s);
|
|
394
|
+
if (!hint || !hint.n) return null;
|
|
395
|
+
return ` ↑${hint.n} commit${hint.n === 1 ? '' : 's'} only on this machine — ${pushCommand(s)}`;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** The one-line readout `decklight history` and the overlay footer both show. */
|
|
399
|
+
export function remoteLine(s) {
|
|
400
|
+
if (!s) return '';
|
|
401
|
+
switch (s.state) {
|
|
402
|
+
case 'no-git': return 'git is not installed';
|
|
403
|
+
case 'no-repo': return 'not in a git repository';
|
|
404
|
+
case 'unborn': return 'nothing committed yet';
|
|
405
|
+
case 'detached': return `detached HEAD · ${s.unpushed ?? 0} commits here`;
|
|
406
|
+
case 'no-remote': return `${s.branch} · no remote — this history is only on this machine`;
|
|
407
|
+
case 'ambiguous-remote': return `${s.branch} · several remotes, none named origin — push by name`;
|
|
408
|
+
case 'no-upstream': return s.unpushed
|
|
409
|
+
? `${s.branch} → no upstream (${s.remote} exists) · ↑${s.unpushed} never pushed`
|
|
410
|
+
: `${s.branch} → no upstream — ${s.remote} exists but this branch tracks nothing`;
|
|
411
|
+
case 'unreadable': return `${s.branch} → ${s.upstream} · could not be counted`;
|
|
412
|
+
default: {
|
|
413
|
+
const bits = [`${s.branch} → ${s.upstream}`];
|
|
414
|
+
if (s.ahead) bits.push(`↑${s.ahead} unpushed`);
|
|
415
|
+
if (s.behind) bits.push(`↓${s.behind} behind`);
|
|
416
|
+
if (!s.ahead && !s.behind) bits.push('all pushed');
|
|
417
|
+
return bits.join(' · ');
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// ── what else rides along ──────────────────────────────────────────────────
|
|
423
|
+
//
|
|
424
|
+
// A fast-forward updates the WHOLE working tree. If the deck shares a
|
|
425
|
+
// repository with anything else, "update the deck" quietly means "update the
|
|
426
|
+
// source tree, the CI config and the scripts too" — and the person clicking is
|
|
427
|
+
// thinking about a slide.
|
|
428
|
+
//
|
|
429
|
+
// The measure is deliberately what a given change WOULD touch rather than what
|
|
430
|
+
// the repository contains, because that is the number worth interrupting for:
|
|
431
|
+
// a repo that holds only a deck stays silent, and one that holds a product says
|
|
432
|
+
// so with the file names.
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Split a list of paths into the deck's own and everything else.
|
|
436
|
+
*
|
|
437
|
+
* Pure, and the definition of "the deck's own" is the interesting part: the
|
|
438
|
+
* deck file plus anything under the directory it lives in. Themes, images and
|
|
439
|
+
* narration travel WITH a deck and are not a surprise; `src/server.js` is.
|
|
440
|
+
* Paths arrive relative to the repository root, which is how git reports them.
|
|
441
|
+
*/
|
|
442
|
+
export function splitDeckPaths(paths = [], deckRelPath = '') {
|
|
443
|
+
const deck = String(deckRelPath).replace(/^\.\//, '');
|
|
444
|
+
const dir = deck.includes('/') ? `${deck.slice(0, deck.lastIndexOf('/'))}/` : '';
|
|
445
|
+
const own = [];
|
|
446
|
+
const foreign = [];
|
|
447
|
+
for (const p of paths) {
|
|
448
|
+
const rel = String(p).replace(/^\.\//, '');
|
|
449
|
+
if (!rel) continue;
|
|
450
|
+
(rel === deck || (dir && rel.startsWith(dir)) ? own : foreign).push(rel);
|
|
451
|
+
}
|
|
452
|
+
return { own, foreign };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* What pulling `range` would change, and how much of it is not the deck.
|
|
457
|
+
*
|
|
458
|
+
* `range` is `HEAD..@{u}` for a pull; the same shape answers "what would be
|
|
459
|
+
* pushed" for a range the other way round. Unreadable is `null` — a warning
|
|
460
|
+
* nobody can compute must not become a warning nobody can dismiss.
|
|
461
|
+
*/
|
|
462
|
+
export function foreignChanges(cwd, deckRelPath, range = 'HEAD..@{u}', run = git) {
|
|
463
|
+
let paths;
|
|
464
|
+
try { paths = run(['diff', '--name-only', range], cwd).split('\n').filter(Boolean); }
|
|
465
|
+
catch { return null; }
|
|
466
|
+
const { own, foreign } = splitDeckPaths(paths, deckRelPath);
|
|
467
|
+
return { total: paths.length, own, foreign };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* The warning itself, or null when there is nothing surprising to say.
|
|
472
|
+
*
|
|
473
|
+
* Names three files and counts the rest: a wall of paths is skimmed, and three
|
|
474
|
+
* is enough to recognise what kind of repository this is. The recommendation is
|
|
475
|
+
* the last line because it is the fix, not the finding.
|
|
476
|
+
*/
|
|
477
|
+
export function foreignWarning(changes, { verb = 'pull', scope = 'the whole working tree' } = {}) {
|
|
478
|
+
if (!changes || !changes.foreign.length) return null;
|
|
479
|
+
const { total, foreign } = changes;
|
|
480
|
+
const shown = foreign.slice(0, 3).join(' · ');
|
|
481
|
+
const more = foreign.length > 3 ? ` · … ${foreign.length - 3} more` : '';
|
|
482
|
+
return [
|
|
483
|
+
`this ${verb} would change ${total} file${total === 1 ? '' : 's'}, `
|
|
484
|
+
+ `${foreign.length} of them not the deck:`,
|
|
485
|
+
` ${shown}${more}`,
|
|
486
|
+
`a ${verb} updates ${scope} — if that is not what you want here, keep the deck`
|
|
487
|
+
+ ' in a repository of its own',
|
|
488
|
+
];
|
|
489
|
+
}
|