@gnawbit/tabretake 0.4.2 → 0.5.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.
@@ -0,0 +1,503 @@
1
+ import { spawn } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import { createReadStream } from "node:fs";
4
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
5
+ import { createServer } from "node:http";
6
+ import path from "node:path";
7
+ import { parseCommand } from "./lib/options.mjs";
8
+ import { assertConfig, inspectConfig } from "./lib/config.mjs";
9
+ import { probe } from "./lib/ffmpeg.mjs";
10
+ import { commandError, createReporter } from "./lib/report.mjs";
11
+ import { resolveTheme } from "./lib/themes.mjs";
12
+ import { executeRender } from "./render.mjs";
13
+
14
+ const VIDEO_MIME = {
15
+ ".mp4": "video/mp4",
16
+ ".webm": "video/webm",
17
+ ".mov": "video/quicktime",
18
+ ".m4v": "video/mp4",
19
+ ".mkv": "video/x-matroska",
20
+ };
21
+
22
+ function openSystemBrowser(url) {
23
+ try {
24
+ if (process.platform === "win32") {
25
+ spawn("cmd", ["/c", "start", "", url], { detached: true, stdio: "ignore", windowsHide: true }).unref();
26
+ } else if (process.platform === "darwin") {
27
+ spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
28
+ } else {
29
+ spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
30
+ }
31
+ } catch {
32
+ // Ignore errors when a desktop browser launcher is unavailable.
33
+ }
34
+ }
35
+
36
+ async function readJsonBody(req, limitBytes = 1024 * 1024) {
37
+ const chunks = [];
38
+ let total = 0;
39
+ for await (const chunk of req) {
40
+ total += chunk.length;
41
+ if (total > limitBytes) throw new Error("Request body too large");
42
+ chunks.push(chunk);
43
+ }
44
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
45
+ }
46
+
47
+ function renderMarkHtml({ token, duration, width, height, preset, videoName, initialMarks = [], initialDisplayUrl = "your-app.com" }) {
48
+ const bootstrap = JSON.stringify({
49
+ token,
50
+ duration,
51
+ width,
52
+ height,
53
+ preset: preset || "midnight",
54
+ videoName,
55
+ initialMarks,
56
+ initialDisplayUrl,
57
+ })
58
+ .replace(/</g, "\\u003c");
59
+ return `<!doctype html>
60
+ <html lang="en">
61
+ <head>
62
+ <meta charset="utf-8">
63
+ <meta name="viewport" content="width=device-width,initial-scale=1">
64
+ <title>TabRetake Mark Studio</title>
65
+ <style>
66
+ :root { --bg:#0b0f17; --panel:#121826; --line:#243046; --text:#eef2f8; --muted:#94a3b8; --accent:#6c5ce7; }
67
+ * { box-sizing:border-box; }
68
+ body { margin:0; font-family:system-ui,-apple-system,sans-serif; background:var(--bg); color:var(--text); min-height:100vh; display:flex; flex-direction:column; }
69
+ header { display:flex; align-items:center; justify-content:space-between; padding:12px 20px; border-bottom:1px solid var(--line); background:var(--panel); }
70
+ header h1 { font-size:15px; margin:0; }
71
+ .meta { color:var(--muted); font-size:12px; }
72
+ main { display:grid; grid-template-columns:1.6fr 1fr; gap:16px; padding:16px 20px; flex:1; min-height:0; }
73
+ @media (max-width:900px) { main { grid-template-columns:1fr; } }
74
+ .stage { display:flex; flex-direction:column; gap:12px; }
75
+ .player-wrap { position:relative; background:#000; border-radius:12px; overflow:hidden; border:1px solid var(--line); display:flex; align-items:center; justify-content:center; }
76
+ video { display:block; max-width:100%; max-height:68vh; width:100%; }
77
+ .overlay { position:absolute; inset:0; cursor:crosshair; }
78
+ .pin { position:absolute; width:20px; height:20px; border-radius:50%; border:2px solid #fff; background:rgba(108,92,231,0.55); transform:translate(-50%,-50%); pointer-events:none; box-shadow:0 0 0 4px rgba(108,92,231,0.28); }
79
+ .controls { display:flex; flex-wrap:wrap; align-items:center; gap:8px; background:var(--panel); padding:10px 12px; border-radius:10px; border:1px solid var(--line); font-size:13px; }
80
+ .controls button, .actions button { border:0; border-radius:8px; padding:7px 12px; font:inherit; cursor:pointer; background:#1e293b; color:var(--text); }
81
+ .controls button:hover, .actions button:hover { background:#334155; }
82
+ .primary { background:var(--accent)!important; color:#fff!important; font-weight:600; }
83
+ .done { background:#10b981!important; color:#052e16!important; font-weight:600; }
84
+ .sidebar { display:flex; flex-direction:column; gap:12px; background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:14px; }
85
+ .marks { display:flex; flex-direction:column; gap:10px; overflow:auto; max-height:56vh; }
86
+ .mark-row { border:1px solid var(--line); border-radius:9px; padding:10px; background:#0e1420; display:flex; flex-direction:column; gap:8px; }
87
+ .mark-head { display:flex; justify-content:space-between; align-items:center; font-size:12px; color:var(--muted); }
88
+ input, select { width:100%; padding:7px 9px; border-radius:7px; border:1px solid var(--line); background:#090d14; color:var(--text); font:inherit; font-size:13px; }
89
+ .row-opts { display:flex; gap:8px; align-items:center; font-size:12px; color:var(--muted); }
90
+ .row-opts label { display:flex; align-items:center; gap:4px; cursor:pointer; }
91
+ .actions { display:flex; flex-wrap:wrap; gap:8px; margin-top:auto; }
92
+ .status { font-size:12px; color:#93c5fd; min-height:18px; word-break:break-word; }
93
+ </style>
94
+ </head>
95
+ <body>
96
+ <header>
97
+ <h1>TabRetake Mark Studio</h1>
98
+ <div class="meta" id="meta"></div>
99
+ </header>
100
+ <main>
101
+ <section class="stage">
102
+ <div class="player-wrap">
103
+ <video id="video" src="/video" preload="metadata"></video>
104
+ <div class="overlay" id="overlay" title="Click anywhere on the frame to add a zoom mark"></div>
105
+ </div>
106
+ <div class="controls">
107
+ <button id="play" type="button">Play / Pause</button>
108
+ <button id="back" type="button">-0.1s</button>
109
+ <button id="fwd" type="button">+0.1s</button>
110
+ <input id="seek" type="range" min="0" max="1" step="0.02" value="0" style="flex:1;min-width:140px">
111
+ <span id="time">0.00s</span>
112
+ </div>
113
+ <div class="meta">Tip: Click directly on the video frame to place a mark at the current timestamp. Space toggles play/pause.</div>
114
+ </section>
115
+ <aside class="sidebar">
116
+ <div class="row-opts">
117
+ <label style="flex:1">Display URL <input id="displayUrl" value="your-app.com"></label>
118
+ <label style="width:130px">Preset
119
+ <select id="preset">
120
+ <option value="midnight">midnight</option>
121
+ <option value="daylight">daylight</option>
122
+ <option value="paper">paper</option>
123
+ <option value="slate">slate</option>
124
+ </select>
125
+ </label>
126
+ </div>
127
+ <div class="marks" id="marks"></div>
128
+ <div class="row-opts"><label><input id="vertical" type="checkbox" checked> Also render 9:16 vertical</label></div>
129
+ <div class="status" id="status">Click the video frame to add your first mark.</div>
130
+ <div class="actions">
131
+ <button id="save" type="button">Save JSON</button>
132
+ <button id="render" class="primary" type="button">Save &amp; Render</button>
133
+ <button id="done" class="done" type="button">Finish &amp; Close</button>
134
+ </div>
135
+ </aside>
136
+ </main>
137
+ <script>
138
+ const BOOT = ${bootstrap};
139
+ const video = document.getElementById("video");
140
+ const overlay = document.getElementById("overlay");
141
+ const seek = document.getElementById("seek");
142
+ const timeEl = document.getElementById("time");
143
+ const marksEl = document.getElementById("marks");
144
+ const statusEl = document.getElementById("status");
145
+ const presetEl = document.getElementById("preset");
146
+ const displayUrlEl = document.getElementById("displayUrl");
147
+ const verticalEl = document.getElementById("vertical");
148
+ presetEl.value = BOOT.preset;
149
+ displayUrlEl.value = BOOT.initialDisplayUrl || "your-app.com";
150
+ document.getElementById("meta").textContent = BOOT.videoName + " · " + BOOT.width + "×" + BOOT.height + " · " + BOOT.duration.toFixed(2) + "s";
151
+
152
+ let marks = Array.isArray(BOOT.initialMarks) ? BOOT.initialMarks.map((m) => ({
153
+ t: Number(m.t || 0),
154
+ x: Number(m.x ?? 0.5),
155
+ y: Number(m.y ?? 0.5),
156
+ duration: Number(m.duration ?? 0.2),
157
+ caption: m.caption || "",
158
+ zoom: m.zoom !== false,
159
+ })) : [];
160
+ const round3 = (n) => Math.round(n * 1000) / 1000;
161
+ const round2 = (n) => Math.round(n * 100) / 100;
162
+
163
+ function syncTime() {
164
+ const cur = video.currentTime || 0;
165
+ const dur = video.duration || BOOT.duration || 1;
166
+ seek.max = String(dur);
167
+ seek.value = String(cur);
168
+ timeEl.textContent = cur.toFixed(2) + "s / " + dur.toFixed(2) + "s";
169
+ }
170
+
171
+ function renderMarks() {
172
+ overlay.innerHTML = "";
173
+ marksEl.innerHTML = "";
174
+ marks.sort((a, b) => a.t - b.t);
175
+ marks.forEach((mark, i) => {
176
+ const pin = document.createElement("div");
177
+ pin.className = "pin";
178
+ pin.style.left = (mark.x * 100) + "%";
179
+ pin.style.top = (mark.y * 100) + "%";
180
+ overlay.appendChild(pin);
181
+
182
+ const row = document.createElement("div");
183
+ row.className = "mark-row";
184
+ row.innerHTML = \`
185
+ <div class="mark-head">
186
+ <button type="button" data-jump="\${i}" style="padding:2px 7px;background:#1e293b;color:#fff;border:0;border-radius:5px;cursor:pointer">t = \${mark.t.toFixed(2)}s (\${mark.x}, \${mark.y})</button>
187
+ <button type="button" data-del="\${i}" style="padding:2px 7px;background:#7f1d1d;color:#fecaca;border:0;border-radius:5px;cursor:pointer">Remove</button>
188
+ </div>
189
+ <input placeholder="Caption (optional)" value="">
190
+ <div class="row-opts">
191
+ <label><input type="checkbox" \${mark.zoom === false ? "" : "checked"}> Zoom in</label>
192
+ <label>Delay (s) <input type="number" step="0.1" min="0" value="\${mark.duration}" style="width:70px"></label>
193
+ </div>\`;
194
+ const [capInput, zoomCheck, durInput] = row.querySelectorAll("input");
195
+ capInput.value = mark.caption || "";
196
+ capInput.addEventListener("input", () => { mark.caption = capInput.value; });
197
+ zoomCheck.addEventListener("change", () => { mark.zoom = zoomCheck.checked; });
198
+ durInput.addEventListener("input", () => { mark.duration = Math.max(0, Number(durInput.value || 0)); });
199
+ row.querySelector("[data-jump]").addEventListener("click", () => { video.currentTime = mark.t; syncTime(); });
200
+ row.querySelector("[data-del]").addEventListener("click", () => { marks.splice(i, 1); renderMarks(); });
201
+ marksEl.appendChild(row);
202
+ });
203
+ }
204
+
205
+ overlay.addEventListener("click", (e) => {
206
+ video.pause();
207
+ const rect = overlay.getBoundingClientRect();
208
+ const x = round3(Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width)));
209
+ const y = round3(Math.min(1, Math.max(0, (e.clientY - rect.top) / rect.height)));
210
+ const t = round2(video.currentTime || 0);
211
+ marks.push({ t, x, y, duration: 0.2, caption: "", zoom: true });
212
+ renderMarks();
213
+ statusEl.textContent = "Added mark at t=" + t.toFixed(2) + "s (" + x + ", " + y + ")";
214
+ });
215
+
216
+ document.getElementById("play").addEventListener("click", () => video.paused ? video.play() : video.pause());
217
+ document.getElementById("back").addEventListener("click", () => { video.pause(); video.currentTime = Math.max(0, video.currentTime - 0.1); syncTime(); });
218
+ document.getElementById("fwd").addEventListener("click", () => { video.pause(); video.currentTime = Math.min(video.duration || BOOT.duration, video.currentTime + 0.1); syncTime(); });
219
+ seek.addEventListener("input", () => { video.currentTime = Number(seek.value); syncTime(); });
220
+ video.addEventListener("timeupdate", syncTime);
221
+ video.addEventListener("loadedmetadata", syncTime);
222
+ window.addEventListener("keydown", (e) => {
223
+ if (e.target.tagName === "INPUT" || e.target.tagName === "SELECT") return;
224
+ if (e.code === "Space") { e.preventDefault(); video.paused ? video.play() : video.pause(); }
225
+ });
226
+
227
+ async function postJson(endpoint, body) {
228
+ const res = await fetch(endpoint, {
229
+ method: "POST",
230
+ headers: { "Content-Type": "application/json", "x-tabretake-token": BOOT.token },
231
+ body: JSON.stringify(body),
232
+ });
233
+ const data = await res.json();
234
+ if (!res.ok) throw new Error(data.error || "Request failed");
235
+ return data;
236
+ }
237
+
238
+ const payload = () => ({
239
+ displayUrl: displayUrlEl.value.trim() || "your-app.com",
240
+ preset: presetEl.value,
241
+ marks: marks.map((m) => ({
242
+ t: m.t, x: m.x, y: m.y, duration: m.duration,
243
+ ...(m.caption ? { caption: m.caption } : {}),
244
+ ...(m.zoom === false ? { zoom: false } : {}),
245
+ })),
246
+ });
247
+
248
+ document.getElementById("save").addEventListener("click", async () => {
249
+ try {
250
+ const res = await postJson("/api/save", payload());
251
+ statusEl.textContent = "Saved " + res.markCount + " mark(s) to " + res.path;
252
+ } catch (err) { statusEl.textContent = "Error: " + err.message; }
253
+ });
254
+ document.getElementById("render").addEventListener("click", async () => {
255
+ statusEl.textContent = verticalEl.checked ? "Rendering 16:9 + 9:16..." : "Rendering 16:9...";
256
+ try {
257
+ const res = await postJson("/api/render", { ...payload(), vertical: verticalEl.checked });
258
+ const dir = res.renderDir ? " into " + res.renderDir : "";
259
+ statusEl.textContent = "Rendered " + res.artifacts.length + " artifact(s)" + dir + ".";
260
+ } catch (err) { statusEl.textContent = "Error: " + err.message; }
261
+ });
262
+ if (marks.length > 0) renderMarks();
263
+ document.getElementById("done").addEventListener("click", async () => {
264
+ await postJson("/api/save", payload()).catch(() => {});
265
+ await postJson("/api/done", {}).catch(() => {});
266
+ statusEl.textContent = "Done! You can close this tab.";
267
+ });
268
+ </script>
269
+ </body>
270
+ </html>`;
271
+ }
272
+
273
+ export function buildMarksConfig({ videoPath, outPath, displayUrl, preset, marks = [] }) {
274
+ const rel = path.relative(path.dirname(outPath), videoPath);
275
+ const video = rel && !path.isAbsolute(rel) ? rel.replace(/\\/g, "/") : videoPath;
276
+ const theme = resolveTheme({}, preset);
277
+ const config = {
278
+ displayUrl: displayUrl || "your-app.com",
279
+ video,
280
+ brand: { preset: theme.preset, background: theme.background, accent: theme.accent },
281
+ marks: marks.map((m) => ({
282
+ t: Number(m.t ?? 0),
283
+ ...(m.duration !== undefined ? { duration: Number(m.duration) } : {}),
284
+ ...(m.x !== undefined ? { x: Number(m.x) } : {}),
285
+ ...(m.y !== undefined ? { y: Number(m.y) } : {}),
286
+ ...(m.caption ? { caption: String(m.caption) } : {}),
287
+ ...(m.zoom === false ? { zoom: false } : {}),
288
+ ...(m.label ? { label: String(m.label) } : {}),
289
+ })),
290
+ };
291
+ return assertConfig(config, { kind: "marks" });
292
+ }
293
+
294
+ export async function startMarkServer({
295
+ videoPath,
296
+ outPath,
297
+ preset,
298
+ mediaOut,
299
+ port = 0,
300
+ reporter,
301
+ } = {}) {
302
+ const resolvedVideo = path.resolve(videoPath);
303
+ const resolvedOut = path.resolve(outPath || "story-video.json");
304
+ const info = await probe(resolvedVideo);
305
+ const stream = (info.streams || []).find((s) => s.codec_type === "video");
306
+ const width = Number(stream?.width || 0);
307
+ const height = Number(stream?.height || 0);
308
+ const duration = Number(info.format?.duration || 0);
309
+ if (!width || !height || !duration) {
310
+ throw new Error(`Could not read video metadata: ${resolvedVideo}`);
311
+ }
312
+
313
+ const token = crypto.randomBytes(16).toString("hex");
314
+ const artifacts = new Map();
315
+ let resolveDone;
316
+ const donePromise = new Promise((resolve) => { resolveDone = resolve; });
317
+
318
+ let initialMarks = [];
319
+ let initialDisplayUrl = "your-app.com";
320
+ let initialPreset = preset;
321
+ try {
322
+ const existing = JSON.parse(await readFile(resolvedOut, "utf8"));
323
+ if (inspectConfig(existing, { kind: "marks" }).ok) {
324
+ initialMarks = existing.marks || [];
325
+ if (existing.displayUrl) initialDisplayUrl = existing.displayUrl;
326
+ if (!initialPreset && existing.brand?.preset) initialPreset = existing.brand.preset;
327
+ artifacts.set(resolvedOut, { kind: "marks", path: resolvedOut });
328
+ }
329
+ } catch {
330
+ // No readable existing marks file; start fresh.
331
+ }
332
+
333
+ const saveConfig = async (body) => {
334
+ const cfg = buildMarksConfig({
335
+ videoPath: resolvedVideo,
336
+ outPath: resolvedOut,
337
+ displayUrl: body.displayUrl,
338
+ preset: body.preset || preset,
339
+ marks: body.marks || [],
340
+ });
341
+ await mkdir(path.dirname(resolvedOut), { recursive: true });
342
+ await writeFile(resolvedOut, JSON.stringify(cfg, null, 2) + "\n", "utf8");
343
+ artifacts.set(resolvedOut, { kind: "marks", path: resolvedOut });
344
+ return cfg;
345
+ };
346
+
347
+ const server = createServer(async (req, res) => {
348
+ const reqUrl = (req.url || "/").split("?")[0];
349
+ try {
350
+ if (req.method === "GET" && reqUrl === "/") {
351
+ const html = renderMarkHtml({
352
+ token,
353
+ duration,
354
+ width,
355
+ height,
356
+ preset: initialPreset,
357
+ videoName: path.basename(resolvedVideo),
358
+ initialMarks,
359
+ initialDisplayUrl,
360
+ });
361
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
362
+ res.end(html);
363
+ return;
364
+ }
365
+
366
+ if (req.method === "GET" && reqUrl === "/video") {
367
+ const fileStat = await stat(resolvedVideo);
368
+ const total = fileStat.size;
369
+ const ext = path.extname(resolvedVideo).toLowerCase();
370
+ const mime = VIDEO_MIME[ext] || "application/octet-stream";
371
+ const range = req.headers.range;
372
+ if (range) {
373
+ const match = /^bytes=(\d*)-(\d*)$/.exec(range);
374
+ if (!match) {
375
+ res.writeHead(416, { "Content-Range": `bytes */${total}` }).end();
376
+ return;
377
+ }
378
+ const start = match[1] ? Number(match[1]) : 0;
379
+ const end = match[2] ? Math.min(total - 1, Number(match[2])) : total - 1;
380
+ if (start > end || start >= total) {
381
+ res.writeHead(416, { "Content-Range": `bytes */${total}` }).end();
382
+ return;
383
+ }
384
+ res.writeHead(206, {
385
+ "Content-Range": `bytes ${start}-${end}/${total}`,
386
+ "Accept-Ranges": "bytes",
387
+ "Content-Length": end - start + 1,
388
+ "Content-Type": mime,
389
+ });
390
+ createReadStream(resolvedVideo, { start, end }).pipe(res);
391
+ return;
392
+ }
393
+ res.writeHead(200, {
394
+ "Accept-Ranges": "bytes",
395
+ "Content-Length": total,
396
+ "Content-Type": mime,
397
+ });
398
+ createReadStream(resolvedVideo).pipe(res);
399
+ return;
400
+ }
401
+
402
+ if (req.method === "POST") {
403
+ if (req.headers["x-tabretake-token"] !== token) {
404
+ res.writeHead(403, { "Content-Type": "application/json" });
405
+ res.end(JSON.stringify({ error: "Forbidden" }));
406
+ return;
407
+ }
408
+ const body = await readJsonBody(req);
409
+ if (reqUrl === "/api/save") {
410
+ const cfg = await saveConfig(body);
411
+ res.writeHead(200, { "Content-Type": "application/json" });
412
+ res.end(JSON.stringify({ ok: true, path: resolvedOut, markCount: cfg.marks.length }));
413
+ return;
414
+ }
415
+ if (reqUrl === "/api/render") {
416
+ await saveConfig(body);
417
+ const renderDir = mediaOut || (path.dirname(resolvedOut) === process.cwd() ? "demo" : path.join(path.dirname(resolvedOut), "demo"));
418
+ const renderRes = await executeRender({
419
+ config: resolvedOut,
420
+ out: renderDir,
421
+ vertical: Boolean(body.vertical),
422
+ preset: body.preset || preset,
423
+ "no-gif": Boolean(body.noGif),
424
+ zoom: String(body.zoom ?? "1.28"),
425
+ }, { reporter: reporter || createReporter("render", false) });
426
+ for (const item of renderRes.summary.artifacts) artifacts.set(item.path, item);
427
+ res.writeHead(200, { "Content-Type": "application/json" });
428
+ res.end(JSON.stringify({ ok: true, path: resolvedOut, renderDir: path.resolve(renderDir), artifacts: renderRes.summary.artifacts }));
429
+ return;
430
+ }
431
+ if (reqUrl === "/api/done") {
432
+ res.writeHead(200, { "Content-Type": "application/json" });
433
+ res.end(JSON.stringify({ ok: true }));
434
+ resolveDone();
435
+ return;
436
+ }
437
+ }
438
+
439
+ res.writeHead(404).end("Not found");
440
+ } catch (error) {
441
+ res.writeHead(400, { "Content-Type": "application/json" });
442
+ res.end(JSON.stringify({ error: error.message }));
443
+ }
444
+ });
445
+
446
+ await new Promise((resolve, reject) => {
447
+ server.once("error", reject);
448
+ server.listen(Number(port || 0), "127.0.0.1", resolve);
449
+ });
450
+
451
+ const url = `http://127.0.0.1:${server.address().port}/`;
452
+ return {
453
+ server,
454
+ url,
455
+ token,
456
+ waitForDone: () => donePromise,
457
+ getArtifacts: () => [...artifacts.values()],
458
+ close: () => new Promise((resolve) => server.close(resolve)),
459
+ };
460
+ }
461
+
462
+ export async function mark(argv) {
463
+ const { values } = parseCommand("mark", argv);
464
+ const reporter = createReporter("mark", values.json);
465
+
466
+ if (!values.video) {
467
+ throw commandError("VIDEO_REQUIRED", "Provide --video recording.mp4", {
468
+ hint: "Pass the path to an existing MP4 or WebM screen recording.",
469
+ });
470
+ }
471
+ if (values.preset) resolveTheme({}, values.preset);
472
+
473
+ const session = await startMarkServer({
474
+ videoPath: values.video,
475
+ outPath: values.out,
476
+ preset: values.preset,
477
+ mediaOut: values["media-out"],
478
+ port: Number(values.port || 0),
479
+ reporter,
480
+ });
481
+
482
+ reporter.log(`Mark studio running at ${session.url}`);
483
+ if (!values["no-open"]) {
484
+ openSystemBrowser(session.url);
485
+ }
486
+ reporter.log("Click the video frame to place marks, then click 'Finish & Close'.");
487
+
488
+ const onSignal = () => session.close().finally(() => process.exit(0));
489
+ process.once("SIGINT", onSignal);
490
+ process.once("SIGTERM", onSignal);
491
+
492
+ try {
493
+ await session.waitForDone();
494
+ } finally {
495
+ process.removeListener("SIGINT", onSignal);
496
+ process.removeListener("SIGTERM", onSignal);
497
+ await session.close();
498
+ }
499
+
500
+ const artifacts = session.getArtifacts();
501
+ await reporter.success({ artifacts });
502
+ return session.url;
503
+ }
package/scripts/plan.mjs CHANGED
@@ -1,19 +1,12 @@
1
1
  import { mkdir, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { parseCommand } from "./lib/options.mjs";
4
- import { launchBrowser, newContext } from "./lib/browser.mjs";
5
- import { waitForEnter } from "./lib/tty.mjs";
3
+ import { parseCommand, parseViewport } from "./lib/options.mjs";
4
+ import { launchBrowser, loginAndSave, newContext } from "./lib/browser.mjs";
6
5
  import { createReporter, requireInteractiveLogin } from "./lib/report.mjs";
7
6
  import { navigate } from "./lib/navigation.mjs";
8
7
 
9
- function parseViewport(value) {
10
- if (!value) return { width: 1440, height: 810 };
11
- const [w, h] = value.split("x").map(Number);
12
- return { width: w || 1440, height: h || 810 };
13
- }
14
-
15
- export async function collectElements(page) {
16
- return page.evaluate(() => {
8
+ export async function collectElements(page, { includeHints = false } = {}) {
9
+ return page.evaluate((withHints) => {
17
10
  function cssPath(el) {
18
11
  if (!el || el.nodeType !== 1) return "";
19
12
  if (el.id) return `#${CSS.escape(el.id)}`;
@@ -99,7 +92,7 @@ export async function collectElements(page) {
99
92
  .trim()
100
93
  .slice(0, 140);
101
94
 
102
- return {
95
+ const item = {
103
96
  tag: el.tagName.toLowerCase(),
104
97
  type: el.getAttribute("type") || "",
105
98
  role: el.getAttribute("role") || "",
@@ -122,13 +115,37 @@ export async function collectElements(page) {
122
115
  selector: cssPath(el),
123
116
  visible,
124
117
  };
118
+ if (withHints) {
119
+ const rawHref = el.tagName === "A" ? (el.getAttribute("href") || "").trim() : "";
120
+ const hintSource = `${text} ${el.getAttribute("aria-label") || ""} ${el.getAttribute("placeholder") || ""}`;
121
+ const cls = typeof el.className === "string" ? el.className : "";
122
+ item._hints = {
123
+ inNav: Boolean(el.closest("nav, aside, footer, [role=navigation]")),
124
+ inMain: Boolean(el.closest("main, form, [role=main], [role=dialog]")),
125
+ inForm: Boolean(el.closest("form")),
126
+ hiddenContainer: Boolean(el.closest("[aria-hidden='true'], [inert]")) || style.pointerEvents === "none",
127
+ emptyHref: el.tagName === "A" && (!rawHref || rawHref === "#" || rawHref.startsWith("javascript:")),
128
+ isPrimary: el.getAttribute("type") === "submit" ||
129
+ /\b(primary|cta|submit|create|new|add|start|save|launch)\b/i.test(`${cls} ${text}`),
130
+ isDestructive: /\b(delete|remove|destroy|logout|log out|sign out|cancel|close|reset|clear)\b/i.test(hintSource),
131
+ isSearch: el.getAttribute("type") === "search" || /\bsearch\b/i.test(hintSource),
132
+ };
133
+ }
134
+ return item;
125
135
  })
126
136
  .filter((el) => el.visible)
127
137
  .slice(0, 300);
128
- });
138
+ }, includeHints);
129
139
  }
130
140
 
131
- export async function extractPlan(url, { viewport = { width: 1440, height: 810 }, proxy, storageState, headless = true, browser: browserMode } = {}) {
141
+ export async function extractPlan(url, {
142
+ viewport = { width: 1440, height: 810 },
143
+ proxy,
144
+ storageState,
145
+ headless = true,
146
+ browser: browserMode,
147
+ includeHints = false,
148
+ } = {}) {
132
149
  const browser = await launchBrowser({ headless, proxy, browser: browserMode });
133
150
  try {
134
151
  const context = await newContext(browser, { viewport, storageState });
@@ -137,7 +154,7 @@ export async function extractPlan(url, { viewport = { width: 1440, height: 810 }
137
154
  await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
138
155
  await page.waitForTimeout(800);
139
156
  const title = await page.title();
140
- const elements = await collectElements(page);
157
+ const elements = await collectElements(page, { includeHints });
141
158
  await context.close();
142
159
  return { title, elements };
143
160
  } finally {
@@ -216,21 +233,3 @@ export async function plan(argv) {
216
233
  }
217
234
  await reporter.success(manifest);
218
235
  }
219
-
220
- async function loginAndSave(url, { proxy, viewport, browser: browserMode }) {
221
- const browser = await launchBrowser({ headless: false, proxy, browser: browserMode });
222
- try {
223
- const context = await newContext(browser, { viewport });
224
- const page = await context.newPage();
225
- await navigate(page, url, { allowAuthErrors: true });
226
- console.log("\nA browser window is open. Log in, then come back here.");
227
- await waitForEnter("Press Enter when you are logged in... ");
228
- const statePath = path.resolve("auth.json");
229
- await context.storageState({ path: statePath });
230
- console.log(`Saved login state to ${statePath}\n`);
231
- await context.close();
232
- return statePath;
233
- } finally {
234
- await browser.close();
235
- }
236
- }