@gnawbit/tabretake 0.4.1 → 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,610 @@
1
+ import { access, mkdir, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { parseCommand, parseViewport } from "./lib/options.mjs";
4
+ import { launchBrowser, loginAndSave, newContext } from "./lib/browser.mjs";
5
+ import { assertConfig } from "./lib/config.mjs";
6
+ import { navigate } from "./lib/navigation.mjs";
7
+ import { commandError, createReporter, requireInteractiveLogin } from "./lib/report.mjs";
8
+ import { resolveTheme } from "./lib/themes.mjs";
9
+ import { runPipeline } from "./run.mjs";
10
+
11
+ const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
12
+
13
+ function targetKey(event) {
14
+ if (event.selector) return `sel:${event.selector}`;
15
+ if (event.role && event.name) return `role:${event.role}:${event.name}`;
16
+ if (event.name) return `name:${event.name}`;
17
+ if (event.text) return `text:${event.text}`;
18
+ return "";
19
+ }
20
+
21
+ function defaultCaption(event) {
22
+ const label = String(event.label || event.name || event.text || "").replace(/\s+/g, " ").trim().slice(0, 32);
23
+ if (event.action === "type") return label ? `Enter ${label}` : "Enter text";
24
+ if (event.action === "select") return label ? `Choose ${label}` : "Choose option";
25
+ if (event.action === "focus") return label ? `Focus on ${label}` : "Focus on result";
26
+ if (event.action === "click") return label ? `Open ${label}` : "";
27
+ return "";
28
+ }
29
+
30
+ function toStep(event, pause) {
31
+ const step = { action: event.action };
32
+ if (event.selector) step.selector = event.selector;
33
+ else if (event.role) {
34
+ step.role = event.role;
35
+ if (event.name) step.name = event.name;
36
+ } else if (event.name) step.name = event.name;
37
+ else if (event.text) step.text = event.text;
38
+
39
+ if (event.action === "type" || event.action === "select") {
40
+ step.value = String(event.value ?? "");
41
+ } else if (event.action === "press") {
42
+ step.key = String(event.key || "Enter");
43
+ } else if (event.action === "wait") {
44
+ step.ms = Number(event.ms || 1000);
45
+ return step;
46
+ }
47
+
48
+ if (pause !== undefined) step.pause = pause;
49
+ const caption = event.caption !== undefined ? event.caption : defaultCaption(event);
50
+ if (caption) step.caption = caption;
51
+ if (event.action === "click" && !event.selector && !event.role && !event.name && !event.text) {
52
+ return null;
53
+ }
54
+ return step;
55
+ }
56
+
57
+ export function pushCapturedEvent(merged, item) {
58
+ if (!item || !item.action) return merged;
59
+ const prev = merged.at(-1);
60
+ const currKey = targetKey(item);
61
+ const prevKey = prev ? targetKey(prev) : "";
62
+
63
+ // Drop synthetic form-submit click (detail === 0) immediately following Enter press.
64
+ if (
65
+ item.action === "click" &&
66
+ item.syntheticDetail0 &&
67
+ prev?.action === "press" &&
68
+ prev.key === "Enter" &&
69
+ Number.isFinite(item.at) &&
70
+ Number.isFinite(prev.at) &&
71
+ item.at - prev.at <= 120
72
+ ) {
73
+ return merged;
74
+ }
75
+
76
+ if (item.action === "type" && prev?.action === "type" && currKey && currKey === prevKey) {
77
+ prev.value = item.value;
78
+ prev.at = item.at ?? prev.at;
79
+ return merged;
80
+ }
81
+ if (item.action === "type" && prev?.action === "click" && prev.isInput && currKey && currKey === prevKey) {
82
+ merged[merged.length - 1] = { ...item };
83
+ return merged;
84
+ }
85
+ if (item.action === "select" && prev?.action === "click" && prev.isSelect && currKey && currKey === prevKey) {
86
+ merged[merged.length - 1] = { ...item };
87
+ return merged;
88
+ }
89
+ if (item.action === "select" && prev?.action === "select" && currKey && currKey === prevKey) {
90
+ prev.value = item.value;
91
+ prev.label = item.label ?? prev.label;
92
+ prev.at = item.at ?? prev.at;
93
+ return merged;
94
+ }
95
+ merged.push({ ...item });
96
+ return merged;
97
+ }
98
+
99
+ export function buildCapturedStory({
100
+ url,
101
+ displayUrl,
102
+ viewport = { width: 1440, height: 810 },
103
+ preset,
104
+ scale = 1,
105
+ rawEvents = [],
106
+ }) {
107
+ const merged = [];
108
+ for (const item of rawEvents) {
109
+ pushCapturedEvent(merged, item);
110
+ }
111
+
112
+ const steps = [];
113
+ for (let i = 0; i < merged.length; i += 1) {
114
+ const curr = merged[i];
115
+ const next = merged[i + 1];
116
+ let pause;
117
+ if (curr.action !== "wait") {
118
+ if (curr.pause !== undefined) {
119
+ pause = curr.pause;
120
+ } else if (next && Number.isFinite(curr.at) && Number.isFinite(next.at)) {
121
+ const rounded = Math.round((next.at - curr.at) / 100) * 100;
122
+ pause = clamp(rounded, 350, 1800);
123
+ } else {
124
+ pause = curr.action === "focus" ? 1200 : i === merged.length - 1 ? 900 : 600;
125
+ }
126
+ }
127
+ const step = toStep(curr, pause);
128
+ if (step) steps.push(step);
129
+ }
130
+
131
+ if (steps.length === 0) {
132
+ steps.push({ action: "wait", ms: 1500 });
133
+ }
134
+
135
+ const parsedUrl = new URL(url);
136
+ const theme = resolveTheme({}, preset);
137
+ const story = {
138
+ url: parsedUrl.href,
139
+ displayUrl: displayUrl || parsedUrl.host,
140
+ viewport,
141
+ ...(scale === 2 ? { scale: 2 } : {}),
142
+ initialWait: 700,
143
+ tail: 1200,
144
+ brand: { preset: theme.preset, background: theme.background, accent: theme.accent },
145
+ steps,
146
+ };
147
+ return assertConfig(story, { kind: "story" });
148
+ }
149
+
150
+ function installCaptureScript(context) {
151
+ return context.addInitScript(() => {
152
+ if (window.__tabretakeCaptureInstalled) return;
153
+ window.__tabretakeCaptureInstalled = true;
154
+
155
+ const HUD_ID = "__tabretake_capture_hud";
156
+ let focusMode = false;
157
+ let stepCount = 0;
158
+ let lastSummary = "";
159
+ let statusNote = "";
160
+
161
+ let hudCountEl;
162
+ let hudFocusBtn;
163
+ let hudNoteEl;
164
+ const syncHud = () => {
165
+ if (hudCountEl) {
166
+ const suffix = lastSummary ? ` · ${lastSummary}` : "";
167
+ hudCountEl.textContent = `Capturing · ${stepCount} step${stepCount === 1 ? "" : "s"}${suffix}`;
168
+ }
169
+ if (hudFocusBtn) {
170
+ hudFocusBtn.textContent = focusMode ? "Click element to focus…" : "Pin focus";
171
+ hudFocusBtn.style.background = focusMode ? "#6c5ce7" : "rgba(255,255,255,0.1)";
172
+ }
173
+ if (hudNoteEl) {
174
+ hudNoteEl.textContent = statusNote;
175
+ hudNoteEl.style.display = statusNote ? "block" : "none";
176
+ }
177
+ };
178
+
179
+ const report = async (payload) => {
180
+ if (typeof window.__tabretakeCaptureReport === "function") {
181
+ const res = await window.__tabretakeCaptureReport(payload).catch(() => null);
182
+ if (res && typeof res.count === "number") {
183
+ stepCount = res.count;
184
+ lastSummary = res.lastSummary || "";
185
+ syncHud();
186
+ }
187
+ }
188
+ };
189
+
190
+ const isHudEvent = (event) => {
191
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [];
192
+ return path.some((node) => node && node.id === HUD_ID);
193
+ };
194
+
195
+ const escapeAttr = (value) => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
196
+ const cleanText = (value) => String(value || "").replace(/\s+/g, " ").trim();
197
+
198
+ function cssPath(el) {
199
+ if (!el || el.nodeType !== 1) return "";
200
+ if (el.id && document.querySelectorAll(`#${CSS.escape(el.id)}`).length === 1) {
201
+ return `#${CSS.escape(el.id)}`;
202
+ }
203
+ const parts = [];
204
+ let node = el;
205
+ while (node && node.nodeType === 1 && parts.length < 5) {
206
+ let part = node.tagName.toLowerCase();
207
+ if (node.classList && node.classList.length) {
208
+ part += "." + [...node.classList].slice(0, 2).map((c) => CSS.escape(c)).join(".");
209
+ }
210
+ const parent = node.parentElement;
211
+ if (parent) {
212
+ const siblings = [...parent.children].filter((c) => c.tagName === node.tagName);
213
+ if (siblings.length > 1) {
214
+ part += `:nth-of-type(${siblings.indexOf(node) + 1})`;
215
+ }
216
+ }
217
+ parts.unshift(part);
218
+ if (node.id && document.querySelectorAll(`#${CSS.escape(node.id)}`).length === 1) {
219
+ parts[0] = `#${CSS.escape(node.id)}`;
220
+ break;
221
+ }
222
+ node = parent;
223
+ }
224
+ return parts.join(" > ");
225
+ }
226
+
227
+ function controlLabel(el) {
228
+ const aria = cleanText(el.getAttribute?.("aria-label"));
229
+ if (aria) return aria;
230
+ if (el.labels?.length) {
231
+ const text = [...el.labels].map((l) => cleanText(l.textContent)).filter(Boolean).join(" ");
232
+ if (text) return text;
233
+ }
234
+ return cleanText(el.getAttribute?.("placeholder")) || cleanText(el.innerText || el.textContent);
235
+ }
236
+
237
+ function buildLocator(el) {
238
+ let target = el.closest?.("button, a, input, textarea, select, [role=button], [role=link], [role=tab], [role=textbox], [contenteditable='true'], [contenteditable=''], [contenteditable='plaintext-only']") || el;
239
+ const labelEl = target.closest?.("label");
240
+ if (labelEl?.control && target === el && !["INPUT", "TEXTAREA", "SELECT", "BUTTON", "A"].includes(target.tagName)) {
241
+ target = labelEl.control;
242
+ }
243
+ for (const attr of ["data-testid", "data-test", "data-cy"]) {
244
+ const val = target.getAttribute?.(attr);
245
+ if (val) {
246
+ const sel = `[${attr}="${escapeAttr(val)}"]`;
247
+ if (document.querySelectorAll(sel).length === 1) return { target, locator: { selector: sel } };
248
+ }
249
+ }
250
+ if (target.id && document.querySelectorAll(`#${CSS.escape(target.id)}`).length === 1) {
251
+ return { target, locator: { selector: `#${CSS.escape(target.id)}` } };
252
+ }
253
+ const tag = target.tagName.toLowerCase();
254
+ const nameAttr = target.getAttribute?.("name");
255
+ if ((tag === "input" || tag === "textarea" || tag === "select") && nameAttr) {
256
+ const sel = `${tag}[name="${escapeAttr(nameAttr)}"]`;
257
+ if (document.querySelectorAll(sel).length === 1) return { target, locator: { selector: sel } };
258
+ }
259
+ const explicitRole = target.getAttribute?.("role");
260
+ const role = explicitRole || (tag === "button" ? "button" : tag === "a" ? "link" : "");
261
+ const text = cleanText(target.innerText || target.getAttribute?.("aria-label"));
262
+ if ((role === "button" || role === "link") && text && text.length <= 40) {
263
+ const candidates = [...document.querySelectorAll("button, a, [role=button], [role=link]")]
264
+ .filter((node) => cleanText(node.innerText || node.getAttribute?.("aria-label")) === text);
265
+ if (candidates.length === 1) {
266
+ return { target, locator: { role, name: text } };
267
+ }
268
+ }
269
+ return { target, locator: { selector: cssPath(target) } };
270
+ }
271
+
272
+ const mountHud = () => {
273
+ if (!document.documentElement || document.getElementById(HUD_ID)) return;
274
+ const host = document.createElement("div");
275
+ host.id = HUD_ID;
276
+ let dockedTop = false;
277
+ host.style.cssText = "position:fixed;bottom:14px;right:14px;z-index:2147483647;font-family:system-ui,-apple-system,sans-serif;";
278
+ const shadow = host.attachShadow({ mode: "open" });
279
+ shadow.innerHTML = `
280
+ <style>
281
+ .bar { display:flex; align-items:center; gap:6px; padding:6px 10px; border-radius:11px;
282
+ background:rgba(13,17,23,0.92); color:#f1f5f9; border:1px solid rgba(255,255,255,0.14);
283
+ box-shadow:0 12px 32px rgba(0,0,0,0.45); font-size:12px; backdrop-filter:blur(8px); }
284
+ .dot { width:8px; height:8px; border-radius:50%; background:#ef4444; box-shadow:0 0 8px #ef4444; }
285
+ button { border:0; border-radius:7px; padding:4px 8px; color:#f8fafc; background:rgba(255,255,255,0.1);
286
+ cursor:pointer; font:inherit; font-weight:500; white-space:nowrap; }
287
+ button:hover { background:rgba(255,255,255,0.18); }
288
+ .save { background:#10b981; color:#052e16; font-weight:600; }
289
+ .save:hover { background:#34d399; }
290
+ .note { margin-top:6px; padding:6px 10px; border-radius:8px; background:rgba(120,53,15,0.95);
291
+ color:#fef3c7; font-size:11px; max-width:340px; display:none; }
292
+ </style>
293
+ <div class="bar">
294
+ <span class="dot"></span>
295
+ <span id="count">Capturing · 0 steps</span>
296
+ <button id="focus" type="button" title="Alt+F: capture a focus step without clicking through">Pin focus</button>
297
+ <button id="wait" type="button">+ Wait 1s</button>
298
+ <button id="undo" type="button">Undo</button>
299
+ <button id="flip" type="button" title="Move bar to top or bottom">↕</button>
300
+ <button id="save" class="save" type="button">Save &amp; Finish</button>
301
+ <button id="discard" type="button">Discard</button>
302
+ </div>
303
+ <div id="note" class="note"></div>
304
+ `;
305
+ hudCountEl = shadow.getElementById("count");
306
+ hudFocusBtn = shadow.getElementById("focus");
307
+ hudNoteEl = shadow.getElementById("note");
308
+ hudFocusBtn.addEventListener("click", () => { focusMode = !focusMode; syncHud(); });
309
+ shadow.getElementById("flip").addEventListener("click", () => {
310
+ dockedTop = !dockedTop;
311
+ host.style.top = dockedTop ? "14px" : "";
312
+ host.style.bottom = dockedTop ? "" : "14px";
313
+ });
314
+ shadow.getElementById("wait").addEventListener("click", () => {
315
+ stepCount += 1;
316
+ syncHud();
317
+ report({ kind: "step", action: "wait", ms: 1000, at: Date.now() });
318
+ });
319
+ shadow.getElementById("undo").addEventListener("click", () => {
320
+ if (stepCount > 0) stepCount -= 1;
321
+ syncHud();
322
+ report({ kind: "undo" });
323
+ });
324
+ shadow.getElementById("save").addEventListener("click", () => report({ kind: "finish" }));
325
+ shadow.getElementById("discard").addEventListener("click", () => report({ kind: "discard" }));
326
+ document.documentElement.appendChild(host);
327
+ syncHud();
328
+ report({ kind: "ping" });
329
+ };
330
+
331
+ if (document.documentElement) mountHud();
332
+ window.addEventListener("DOMContentLoaded", mountHud, true);
333
+
334
+ window.addEventListener("keydown", (event) => {
335
+ if (isHudEvent(event)) return;
336
+ if (event.altKey && (event.key === "f" || event.key === "F")) {
337
+ event.preventDefault();
338
+ focusMode = !focusMode;
339
+ syncHud();
340
+ return;
341
+ }
342
+ if (event.key === "Enter" || event.key === "Escape") {
343
+ stepCount += 1;
344
+ syncHud();
345
+ report({ kind: "step", action: "press", key: event.key, at: Date.now() });
346
+ }
347
+ }, true);
348
+
349
+ const handleText = (event) => {
350
+ if (isHudEvent(event)) return;
351
+ const el = event.target;
352
+ if (!el || el.nodeType !== 1) return;
353
+ if (el.tagName === "SELECT") return;
354
+ const inputType = (el.getAttribute?.("type") || "").toLowerCase();
355
+ if (inputType === "password") {
356
+ statusNote = "Password input ignored; use --login or --storage-state for authenticated demos.";
357
+ syncHud();
358
+ report({ kind: "password-skipped" });
359
+ return;
360
+ }
361
+ if (inputType === "checkbox" || inputType === "radio" || inputType === "button" || inputType === "submit") {
362
+ return;
363
+ }
364
+ const isEditable = el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable;
365
+ if (!isEditable) return;
366
+ const { target, locator } = buildLocator(el);
367
+ const value = el.tagName === "INPUT" || el.tagName === "TEXTAREA" ? el.value : (el.innerText || "");
368
+ stepCount += 1;
369
+ syncHud();
370
+ report({
371
+ kind: "step",
372
+ action: "type",
373
+ ...locator,
374
+ value,
375
+ label: controlLabel(target).slice(0, 40),
376
+ at: Date.now(),
377
+ });
378
+ };
379
+
380
+ document.addEventListener("input", handleText, true);
381
+
382
+ document.addEventListener("change", (event) => {
383
+ if (isHudEvent(event)) return;
384
+ const el = event.target;
385
+ if (!el || el.tagName !== "SELECT") return;
386
+ const { target, locator } = buildLocator(el);
387
+ const selectedOption = target.options?.[target.selectedIndex];
388
+ const optionLabel = cleanText(selectedOption?.label || selectedOption?.textContent || target.value);
389
+ stepCount += 1;
390
+ syncHud();
391
+ report({
392
+ kind: "step",
393
+ action: "select",
394
+ ...locator,
395
+ value: target.value,
396
+ label: optionLabel.slice(0, 40),
397
+ at: Date.now(),
398
+ });
399
+ }, true);
400
+
401
+ document.addEventListener("click", (event) => {
402
+ if (isHudEvent(event)) return;
403
+ const rawTarget = event.target;
404
+ if (!rawTarget || rawTarget.nodeType !== 1) return;
405
+ const { target, locator } = buildLocator(rawTarget);
406
+ if (!locator.selector && !locator.name && !locator.text) return;
407
+
408
+ if (focusMode) {
409
+ event.preventDefault();
410
+ event.stopImmediatePropagation();
411
+ focusMode = false;
412
+ stepCount += 1;
413
+ syncHud();
414
+ report({
415
+ kind: "step",
416
+ action: "focus",
417
+ ...locator,
418
+ label: controlLabel(target).slice(0, 40),
419
+ at: Date.now(),
420
+ });
421
+ return;
422
+ }
423
+
424
+ const tag = target.tagName.toLowerCase();
425
+ const inputType = (target.getAttribute?.("type") || "").toLowerCase();
426
+ if (tag === "input" && inputType === "password") return;
427
+ const isInput = (tag === "input" && !["checkbox", "radio", "button", "submit", "reset"].includes(inputType)) ||
428
+ tag === "textarea" || target.isContentEditable;
429
+ const isSelect = tag === "select";
430
+
431
+ stepCount += 1;
432
+ syncHud();
433
+ report({
434
+ kind: "step",
435
+ action: "click",
436
+ ...locator,
437
+ isInput,
438
+ isSelect,
439
+ syntheticDetail0: event.detail === 0,
440
+ label: controlLabel(target).slice(0, 40),
441
+ at: Date.now(),
442
+ });
443
+ }, true);
444
+ });
445
+ }
446
+
447
+ export async function runCaptureSession({
448
+ url,
449
+ viewport = { width: 1440, height: 810 },
450
+ preset,
451
+ scale = 1,
452
+ proxy,
453
+ storageState,
454
+ browser: browserMode = "auto",
455
+ headless = false,
456
+ onReady,
457
+ reporter,
458
+ } = {}) {
459
+ const rawEvents = [];
460
+ let passwordSkipped = false;
461
+ let discarded = false;
462
+ let settled = false;
463
+
464
+ const browser = await launchBrowser({ headless, proxy, browser: browserMode });
465
+ try {
466
+ const context = await newContext(browser, { viewport, storageState });
467
+ let resolveDone;
468
+ const done = new Promise((resolve) => { resolveDone = resolve; });
469
+ const finish = (isDiscarded = false) => {
470
+ if (settled) return;
471
+ settled = true;
472
+ discarded = isDiscarded;
473
+ resolveDone();
474
+ };
475
+
476
+ await context.exposeBinding("__tabretakeCaptureReport", (_source, payload) => {
477
+ if (!payload || typeof payload !== "object") return { count: rawEvents.length };
478
+ if (payload.kind === "step") {
479
+ pushCapturedEvent(rawEvents, payload);
480
+ } else if (payload.kind === "undo") {
481
+ rawEvents.pop();
482
+ } else if (payload.kind === "password-skipped") {
483
+ if (!passwordSkipped) {
484
+ passwordSkipped = true;
485
+ reporter?.log("Warning: password inputs are never written to story files; use --login / --storage-state.");
486
+ }
487
+ } else if (payload.kind === "finish") {
488
+ finish(false);
489
+ } else if (payload.kind === "discard") {
490
+ finish(true);
491
+ }
492
+ const last = rawEvents.at(-1);
493
+ const lastSummary = last ? `${last.action}` : "";
494
+ return { count: rawEvents.length, lastSummary };
495
+ });
496
+
497
+ await installCaptureScript(context);
498
+ const page = await context.newPage();
499
+
500
+ const checkPages = () => {
501
+ if (context.pages().length === 0) finish(false);
502
+ };
503
+ page.on("close", checkPages);
504
+ context.on("page", (extraPage) => extraPage.on("close", checkPages));
505
+ browser.on("disconnected", () => finish(false));
506
+
507
+ await navigate(page, url, { allowAuthErrors: Boolean(storageState) });
508
+ if (onReady) {
509
+ await onReady({ page, context, finish });
510
+ }
511
+ await done;
512
+ await context.close().catch(() => {});
513
+ } finally {
514
+ await browser.close().catch(() => {});
515
+ }
516
+
517
+ if (discarded) return { discarded: true, story: null, passwordSkipped };
518
+ const story = buildCapturedStory({ url, viewport, preset, scale, rawEvents });
519
+ return { discarded: false, story, passwordSkipped };
520
+ }
521
+
522
+ export async function capture(argv) {
523
+ const { values } = parseCommand("capture", argv);
524
+ requireInteractiveLogin(values);
525
+ const reporter = createReporter("capture", values.json);
526
+
527
+ if (!values.url) throw new Error("Provide --url https://your-app.com");
528
+ let parsedUrl;
529
+ try {
530
+ parsedUrl = new URL(values.url);
531
+ } catch {
532
+ throw new Error("Use a complete http:// or https:// URL");
533
+ }
534
+ if (!["http:", "https:"].includes(parsedUrl.protocol)) {
535
+ throw new Error("Use a complete http:// or https:// URL");
536
+ }
537
+
538
+ const outPath = path.resolve(values.out);
539
+ if (!values.force) {
540
+ try {
541
+ await access(outPath);
542
+ throw new Error("Story file already exists; pass --force to overwrite or choose another --out path");
543
+ } catch (error) {
544
+ if (error.code !== "ENOENT") throw error;
545
+ }
546
+ }
547
+
548
+ const viewport = parseViewport(values.viewport);
549
+ const scaleInput = values.scale === undefined ? 1 : (values.scale.trim() === "" ? NaN : Number(values.scale));
550
+ if (scaleInput !== 1 && scaleInput !== 2) {
551
+ throw commandError("INVALID_CONFIG", "scale / --scale must be 1 or 2", {
552
+ hint: "Choose 1 (standard) or 2 (HiDPI Retina).",
553
+ });
554
+ }
555
+ if (values.preset) resolveTheme({}, values.preset);
556
+
557
+ let storageState = values["storage-state"];
558
+ if (values.login) {
559
+ storageState = await loginAndSave(parsedUrl.href, {
560
+ proxy: values.proxy,
561
+ viewport,
562
+ browser: values.browser,
563
+ statePath: path.resolve(values["save-state"] || "auth.json"),
564
+ });
565
+ }
566
+
567
+ reporter.log("Browser opened for interactive capture. Perform your demo steps, then click 'Save & Finish'.");
568
+ const { discarded, story } = await runCaptureSession({
569
+ url: parsedUrl.href,
570
+ viewport,
571
+ preset: values.preset,
572
+ scale: scaleInput,
573
+ proxy: values.proxy,
574
+ storageState,
575
+ browser: values.browser,
576
+ reporter,
577
+ });
578
+
579
+ if (discarded || !story) {
580
+ throw commandError("CAPTURE_DISCARDED", "Interactive capture was discarded; no story file was written.", {
581
+ hint: "Re-run capture and click 'Save & Finish' to keep the recorded steps.",
582
+ });
583
+ }
584
+
585
+ await mkdir(path.dirname(outPath), { recursive: true });
586
+ await writeFile(outPath, JSON.stringify(story, null, 2) + "\n", values.force ? "utf8" : { flag: "wx" });
587
+ reporter.log(`Saved captured story (${story.steps.length} step(s)): ${outPath}`);
588
+
589
+ const artifacts = [{ kind: "story", path: outPath }];
590
+ let extraSummary = {};
591
+
592
+ if (values.run) {
593
+ const runResult = await runPipeline({
594
+ ...values,
595
+ config: outPath,
596
+ out: values["media-out"] || "demo",
597
+ }, { reporter });
598
+ artifacts.push(...runResult.artifacts);
599
+ extraSummary = {
600
+ duration: runResult.duration,
601
+ posterAt: runResult.posterAt,
602
+ ...(runResult.eventCount !== undefined ? { eventCount: runResult.eventCount } : {}),
603
+ };
604
+ } else {
605
+ reporter.log(`Next: tabretake run --config ${path.relative(process.cwd(), outPath)} --vertical`);
606
+ }
607
+
608
+ await reporter.success({ stepCount: story.steps.length, ...extraSummary, artifacts });
609
+ return outPath;
610
+ }
package/scripts/cli.mjs CHANGED
@@ -9,33 +9,38 @@ Usage:
9
9
  tabretake capabilities [--json]
10
10
  tabretake doctor [--json]
11
11
  tabretake validate --config demo.json [--json]
12
- tabretake init --url <url> [--out demo.json]
12
+ tabretake init --url <url> [--out demo.json] [--auto] [--preset midnight|daylight|paper|slate]
13
+ tabretake capture --url <url> [--out demo.json] [--run] [--vertical] [--preset <name>]
13
14
  tabretake plan --url <url> [--out plan.json] [--login] [--storage-state auth.json]
14
15
  tabretake record --config demo.json [--out demo] [--login] [--storage-state auth.json]
15
16
  tabretake preview --config demo.json [--headless] [--json]
16
- tabretake render --config demo.json [--out demo] [--video recording.mp4] [--vertical] [--no-gif]
17
+ tabretake render --config demo.json [--out demo] [--video recording.mp4] [--vertical] [--no-gif] [--preset <name>]
18
+ tabretake run --config demo.json [--out demo] [--vertical] [--preset <name>]
19
+ tabretake mark --video recording.mp4 [--out story-video.json] [--preset <name>]
17
20
  tabretake serve [--port 4173] [--dir examples/site]
18
- tabretake demo [--story readme|onboarding|release] [--out demo]
21
+ tabretake demo [--story readme|onboarding|release] [--out demo] [--preset <name>]
19
22
 
20
23
  Examples:
21
- tabretake init --url https://your-app.com
22
- tabretake plan --url https://your-app.com
23
- tabretake record --config demo.json
24
- tabretake render --config demo.json
25
- tabretake serve
24
+ tabretake capture --url https://your-app.com --run --vertical
25
+ tabretake init --url https://your-app.com --auto
26
+ tabretake run --config demo.json --vertical
27
+ tabretake mark --video recording.mp4
26
28
  tabretake record --config examples/story.json --out demo
27
29
 
28
30
  Options:
29
- --json Machine-readable results for init, plan, record and render.
31
+ --json Machine-readable results for init, plan, record, render, run, capture and mark.
30
32
  --login Open a visible browser so you can log in once.
31
33
  --storage-state Reuse a saved Playwright storage state (cookies/localStorage).
32
34
  --proxy Proxy server, e.g. http://127.0.0.1:10808
33
35
  --viewport Viewport, e.g. 1440x810 (default from config)
36
+ --scale Device pixel scale for crisp zoom: 1 (default) or 2 (HiDPI Retina)
34
37
  --headed Watch the recording happen (default false)
35
38
  --vertical Also render a 9:16 vertical video + GIF.
36
39
  --vertical-zoom Override portrait focus zoom (1–10; otherwise uses --zoom).
37
40
  --video Use an existing screen recording; the config needs "marks".
38
41
  --no-gif Skip GIF export.
42
+ --browser Browser channel: auto (default), chromium, chrome or msedge.
43
+ --preset Brand theme preset: midnight, daylight, paper or slate.
39
44
  --poster-at Choose the poster time in output seconds, e.g. 4.5.
40
45
  --zoom-duration Ease between click targets in seconds (default 0.35; 0 for cuts).
41
46
  `;
@@ -75,6 +80,18 @@ export async function main(argv) {
75
80
  const { init } = await import("./init.mjs");
76
81
  return init(rest);
77
82
  }
83
+ case "capture": {
84
+ const { capture } = await import("./capture.mjs");
85
+ return capture(rest);
86
+ }
87
+ case "run": {
88
+ const { run } = await import("./run.mjs");
89
+ return run(rest);
90
+ }
91
+ case "mark": {
92
+ const { mark } = await import("./mark.mjs");
93
+ return mark(rest);
94
+ }
78
95
  case "doctor": {
79
96
  const { doctor } = await import("./doctor.mjs");
80
97
  return doctor(rest);
package/scripts/demo.mjs CHANGED
@@ -31,8 +31,14 @@ export async function demo(argv) {
31
31
  server.url,
32
32
  "--out",
33
33
  values.out,
34
+ ...(values.browser ? ["--browser", values.browser] : []),
35
+ ]);
36
+ await render([
37
+ "--config",
38
+ path.join(values.out, "record.json"),
39
+ "--vertical",
40
+ ...(values.preset ? ["--preset", values.preset] : []),
34
41
  ]);
35
- await render(["--config", path.join(values.out, "record.json"), "--vertical"]);
36
42
  } finally {
37
43
  await server.close();
38
44
  }