@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.
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,14 +115,38 @@ 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 } = {}) {
132
- const browser = await launchBrowser({ headless, proxy });
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
+ } = {}) {
149
+ const browser = await launchBrowser({ headless, proxy, browser: browserMode });
133
150
  try {
134
151
  const context = await newContext(browser, { viewport, storageState });
135
152
  const page = await context.newPage();
@@ -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 {
@@ -160,12 +177,13 @@ export async function plan(argv) {
160
177
 
161
178
  let storageState = values["storage-state"];
162
179
  if (values.login) {
163
- storageState = await loginAndSave(values.url, { proxy: values.proxy, viewport });
180
+ storageState = await loginAndSave(values.url, { proxy: values.proxy, viewport, browser: values.browser });
164
181
  }
165
182
 
166
183
  const browser = await launchBrowser({
167
184
  headless: values.headless || !values.login,
168
185
  proxy: values.proxy,
186
+ browser: values.browser,
169
187
  });
170
188
 
171
189
  let manifest;
@@ -215,21 +233,3 @@ export async function plan(argv) {
215
233
  }
216
234
  await reporter.success(manifest);
217
235
  }
218
-
219
- async function loginAndSave(url, { proxy, viewport }) {
220
- const browser = await launchBrowser({ headless: false, proxy });
221
- try {
222
- const context = await newContext(browser, { viewport });
223
- const page = await context.newPage();
224
- await navigate(page, url, { allowAuthErrors: true });
225
- console.log("\nA browser window is open. Log in, then come back here.");
226
- await waitForEnter("Press Enter when you are logged in... ");
227
- const statePath = path.resolve("auth.json");
228
- await context.storageState({ path: statePath });
229
- console.log(`Saved login state to ${statePath}\n`);
230
- await context.close();
231
- return statePath;
232
- } finally {
233
- await browser.close();
234
- }
235
- }
@@ -1,33 +1,25 @@
1
1
  import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { parseCommand } from "./lib/options.mjs";
3
+ import { parseCommand, parseViewport } from "./lib/options.mjs";
4
4
  import {
5
5
  clickAndType,
6
6
  dragBy,
7
7
  hover,
8
8
  installCursor,
9
9
  launchBrowser,
10
+ loginAndSave,
10
11
  moveAndClick,
11
- newContext,
12
+ openRecordedPage,
12
13
  resolveLocator,
14
+ selectOption,
13
15
  } from "./lib/browser.mjs";
14
- import { waitForEnter } from "./lib/tty.mjs";
15
16
  import { assertConfig, readConfig } from "./lib/config.mjs";
16
17
  import { commandError, createReporter, requireInteractiveLogin } from "./lib/report.mjs";
17
18
  import { navigate } from "./lib/navigation.mjs";
19
+ import { resolveTheme } from "./lib/themes.mjs";
18
20
 
19
- function parseViewport(value, fallback = { width: 1440, height: 810 }) {
20
- if (value === undefined) return fallback;
21
- if (!/^[1-9]\d*x[1-9]\d*$/.test(value)) throw new Error("--viewport must be WIDTHxHEIGHT with positive integers");
22
- const [width, height] = value.split("x").map(Number);
23
- return { width, height };
24
- }
25
-
26
- export async function record(argv, command = "record") {
21
+ export async function executeRecord(values, { command = "record", reporter = createReporter(command, Boolean(values?.json)) } = {}) {
27
22
  const preview = command === "preview";
28
- const { values } = parseCommand(command, argv);
29
- requireInteractiveLogin(values);
30
- const reporter = createReporter(command, values.json);
31
23
  const screenshots = [];
32
24
 
33
25
  if (!values.config && !values.url) {
@@ -47,11 +39,21 @@ export async function record(argv, command = "record") {
47
39
  width: 1440,
48
40
  height: 810,
49
41
  });
50
- assertConfig({ ...config, url, viewport }, { kind: "story" });
51
- const scale = 1;
42
+ const scaleInput = values.scale === undefined
43
+ ? (config.scale ?? 1)
44
+ : (String(values.scale).trim() === "" ? NaN : Number(values.scale));
45
+ if (scaleInput !== 1 && scaleInput !== 2) {
46
+ throw commandError("INVALID_CONFIG", "scale / --scale must be 1 or 2", {
47
+ hint: "Choose 1 (standard) or 2 (HiDPI Retina).",
48
+ });
49
+ }
50
+ const scale = scaleInput;
51
+ assertConfig({ ...config, url, viewport, scale }, { kind: "story" });
52
52
  const steps = config.steps || [];
53
53
  if (steps.length === 0) throw new Error("Config has no steps");
54
54
 
55
+ const theme = resolveTheme(config.brand, values.preset);
56
+
55
57
  const outDir = path.resolve(values.out || config.out || "demo");
56
58
  const rawDir = path.join(outDir, "raw");
57
59
  if (!preview) {
@@ -65,6 +67,7 @@ export async function record(argv, command = "record") {
65
67
  storageState = await loginAndSave(url, {
66
68
  proxy: values.proxy,
67
69
  viewport,
70
+ browser: values.browser,
68
71
  statePath: path.resolve(values["save-state"] || "auth.json"),
69
72
  });
70
73
  }
@@ -72,6 +75,8 @@ export async function record(argv, command = "record") {
72
75
  const browser = await launchBrowser({
73
76
  headless: preview ? values.headless : !values.headed,
74
77
  proxy: values.proxy,
78
+ browser: values.browser,
79
+ scale,
75
80
  });
76
81
 
77
82
  let videoPath = null;
@@ -81,14 +86,14 @@ export async function record(argv, command = "record") {
81
86
 
82
87
  try {
83
88
  const videoStartedAt = Date.now();
84
- const context = await newContext(browser, {
89
+ const { context, page } = await openRecordedPage(browser, {
85
90
  viewport,
91
+ scale,
86
92
  videoDir: preview ? undefined : rawDir,
87
93
  storageState,
88
94
  });
89
- const page = await context.newPage();
90
95
 
91
- await installCursor(page);
96
+ await installCursor(page, { accent: theme.accent });
92
97
 
93
98
  events = [];
94
99
 
@@ -152,6 +157,24 @@ export async function record(argv, command = "record") {
152
157
  break;
153
158
  }
154
159
 
160
+ case "select": {
161
+ const locator = await resolveLocator(page, step);
162
+ const value = String(step.value ?? step.text ?? "");
163
+ const point = await selectOption(page, locator, value, 0, Number(step.timeout ?? 20000));
164
+ events.push({
165
+ t,
166
+ tEnd: Date.now() - startedAt,
167
+ zoom: step.zoom !== false,
168
+ action: "select",
169
+ x: point.x,
170
+ y: point.y,
171
+ caption: step.caption || "",
172
+ label: value,
173
+ });
174
+ await page.waitForTimeout(Number(step.pause ?? 500));
175
+ break;
176
+ }
177
+
155
178
  case "hover": {
156
179
  const locator = await resolveLocator(page, step);
157
180
  const point = await hover(page, locator, 0);
@@ -301,8 +324,11 @@ export async function record(argv, command = "record") {
301
324
 
302
325
  if (preview) {
303
326
  reporter.log(`Preview completed ${steps.length} step(s).`);
304
- await reporter.success({ duration: timelineDuration, stepCount: steps.length, artifacts: screenshots });
305
- return;
327
+ return {
328
+ summary: { duration: timelineDuration, stepCount: steps.length, artifacts: screenshots },
329
+ record: null,
330
+ recordPath: null,
331
+ };
306
332
  }
307
333
 
308
334
  const recordingPath = path.join(outDir, "recording.webm");
@@ -327,26 +353,27 @@ export async function record(argv, command = "record") {
327
353
  reporter.log(`Record: ${recordPath}`);
328
354
  reporter.log(`\nNext: tabretake render --config ${path.relative(process.cwd(), recordPath)}`);
329
355
  reporter.log(` (or pass the original --config path)\n`);
330
- await reporter.success({ duration: timelineDuration, eventCount: events.length, artifacts: [
331
- { kind: "video", path: recordingPath }, { kind: "timeline", path: recordPath }, ...screenshots,
332
- ] });
333
356
 
334
- return record;
357
+ return {
358
+ summary: {
359
+ duration: timelineDuration,
360
+ eventCount: events.length,
361
+ artifacts: [
362
+ { kind: "video", path: recordingPath },
363
+ { kind: "timeline", path: recordPath },
364
+ ...screenshots,
365
+ ],
366
+ },
367
+ record,
368
+ recordPath,
369
+ };
335
370
  }
336
371
 
337
- async function loginAndSave(url, { proxy, viewport, statePath }) {
338
- const browser = await launchBrowser({ headless: false, proxy });
339
- try {
340
- const context = await newContext(browser, { viewport });
341
- const page = await context.newPage();
342
- await navigate(page, url, { allowAuthErrors: true });
343
- console.log("\nA browser window is open. Log in, then come back here.");
344
- await waitForEnter("Press Enter when you are logged in... ");
345
- await context.storageState({ path: statePath });
346
- console.log(`Saved login state to ${statePath}\n`);
347
- await context.close();
348
- return statePath;
349
- } finally {
350
- await browser.close();
351
- }
372
+ export async function record(argv, command = "record") {
373
+ const { values } = parseCommand(command, argv);
374
+ requireInteractiveLogin(values);
375
+ const reporter = createReporter(command, values.json);
376
+ const result = await executeRecord(values, { command, reporter });
377
+ await reporter.success(result.summary);
378
+ return result.record;
352
379
  }