deictic 0.3.0 → 0.4.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.
Files changed (175) hide show
  1. package/API.md +31 -19
  2. package/README.md +6 -26
  3. package/dist/annotations/client.d.ts +1 -1
  4. package/dist/annotations/client.js +1 -1
  5. package/dist/annotations/index.d.ts +2 -101
  6. package/dist/annotations/index.js +1 -22
  7. package/dist/astro.d.ts +1 -1
  8. package/dist/astro.js +1 -1
  9. package/dist/cli.d.ts +1 -0
  10. package/dist/cli.js +37 -0
  11. package/dist/cli.js.map +1 -0
  12. package/dist/index.js +1 -10
  13. package/dist/logs/client.d.ts +1 -1
  14. package/dist/logs/client.js +1 -1
  15. package/dist/logs/index.d.ts +2 -18
  16. package/dist/logs/index.js +1 -21
  17. package/dist/network/client.d.ts +1 -1
  18. package/dist/network/client.js +1 -1
  19. package/dist/network/index.d.ts +1 -1
  20. package/dist/network/index.js +1 -37
  21. package/dist/recommended/index.d.ts +7 -7
  22. package/dist/recommended/index.js +1 -26
  23. package/dist/recordings/client.d.ts +1 -1
  24. package/dist/recordings/client.js +1 -1
  25. package/dist/recordings/index.d.ts +1 -1
  26. package/dist/screenshots/client.d.ts +1 -1
  27. package/dist/screenshots/client.js +1 -108
  28. package/dist/screenshots/dom.d.ts +1 -1
  29. package/dist/screenshots/dom.js +1 -1
  30. package/dist/screenshots/index.d.ts +1 -1
  31. package/dist/screenshots/index.js +1 -98
  32. package/dist/screenshots/rrweb.d.ts +2 -1
  33. package/dist/screenshots/rrweb.d.ts.map +1 -1
  34. package/dist/screenshots/rrweb.js +6 -2
  35. package/dist/screenshots/rrweb.js.map +1 -1
  36. package/dist/shared/annotations.js +22 -0
  37. package/dist/shared/annotations.js.map +1 -0
  38. package/dist/shared/board.js +190 -0
  39. package/dist/shared/board.js.map +1 -0
  40. package/dist/shared/client.js +108 -0
  41. package/dist/{screenshots → shared}/client.js.map +1 -1
  42. package/dist/shared/endpoints.js +4 -1
  43. package/dist/shared/endpoints.js.map +1 -1
  44. package/dist/shared/find.js +156 -0
  45. package/dist/shared/find.js.map +1 -0
  46. package/dist/shared/frame.js +75 -0
  47. package/dist/shared/frame.js.map +1 -0
  48. package/dist/shared/index.d.ts +5 -0
  49. package/dist/shared/index.d.ts.map +1 -1
  50. package/dist/shared/index2.d.ts +85 -84
  51. package/dist/shared/index2.d.ts.map +1 -1
  52. package/dist/shared/index3.d.ts +83 -89
  53. package/dist/shared/index3.d.ts.map +1 -1
  54. package/dist/shared/index4.d.ts +98 -50
  55. package/dist/shared/index4.d.ts.map +1 -1
  56. package/dist/shared/index5.d.ts +13 -215
  57. package/dist/shared/index5.d.ts.map +1 -1
  58. package/dist/shared/index6.d.ts +55 -61
  59. package/dist/shared/index6.d.ts.map +1 -1
  60. package/dist/shared/index7.d.ts +224 -0
  61. package/dist/shared/index7.d.ts.map +1 -0
  62. package/dist/shared/index8.d.ts +52 -0
  63. package/dist/shared/index8.d.ts.map +1 -0
  64. package/dist/shared/index9.d.ts +70 -0
  65. package/dist/shared/index9.d.ts.map +1 -0
  66. package/dist/shared/init.js +472 -0
  67. package/dist/shared/init.js.map +1 -0
  68. package/dist/shared/local.js +165 -0
  69. package/dist/shared/local.js.map +1 -0
  70. package/dist/shared/logs.js +22 -0
  71. package/dist/shared/logs.js.map +1 -0
  72. package/dist/shared/network.js +39 -0
  73. package/dist/shared/network.js.map +1 -0
  74. package/dist/shared/packages.js +125 -0
  75. package/dist/shared/packages.js.map +1 -0
  76. package/dist/shared/playwright.js +36 -9
  77. package/dist/shared/playwright.js.map +1 -1
  78. package/dist/shared/recommended.js +26 -0
  79. package/dist/shared/recommended.js.map +1 -0
  80. package/dist/shared/recording.js +316 -0
  81. package/dist/shared/recording.js.map +1 -0
  82. package/dist/shared/recordings.js +2 -1
  83. package/dist/shared/recordings.js.map +1 -1
  84. package/dist/shared/screenshots.js +108 -0
  85. package/dist/shared/screenshots.js.map +1 -0
  86. package/dist/shared/src.js +10 -0
  87. package/dist/shared/src.js.map +1 -0
  88. package/dist/shared/task.js +108 -0
  89. package/dist/shared/task.js.map +1 -0
  90. package/dist/shared/tasks.js +33 -191
  91. package/dist/shared/tasks.js.map +1 -1
  92. package/dist/shared/transcribe.js +128 -0
  93. package/dist/shared/transcribe.js.map +1 -0
  94. package/dist/shared/vb.js +13 -0
  95. package/dist/shared/vb.js.map +1 -0
  96. package/dist/shared/vite.d.ts +16 -0
  97. package/dist/shared/vite.d.ts.map +1 -0
  98. package/dist/shared/vite.js +61 -0
  99. package/dist/shared/vite.js.map +1 -0
  100. package/dist/shared/voice.js +84 -0
  101. package/dist/{voice/index.js.map → shared/voice.js.map} +1 -1
  102. package/dist/shared/voice2.js +90 -0
  103. package/dist/shared/voice2.js.map +1 -0
  104. package/dist/shared/watch.js +209 -0
  105. package/dist/shared/watch.js.map +1 -0
  106. package/dist/shared/watchers.js +62 -0
  107. package/dist/shared/watchers.js.map +1 -0
  108. package/dist/tailwind/client.d.ts +1 -1
  109. package/dist/tailwind/client.js +1 -1
  110. package/dist/tailwind/index.d.ts +1 -1
  111. package/dist/tailwind/index.js +1 -1
  112. package/dist/tasks/client.d.ts +1 -1
  113. package/dist/tasks/client.d.ts.map +1 -1
  114. package/dist/tasks/client.js +45 -8
  115. package/dist/tasks/client.js.map +1 -1
  116. package/dist/tasks/index.d.ts +1 -1
  117. package/dist/tasks/index.js +3 -1
  118. package/dist/vite.d.ts +2 -15
  119. package/dist/vite.js +2 -60
  120. package/dist/voice/client.d.ts +1 -1
  121. package/dist/voice/client.js +1 -1
  122. package/dist/voice/index.d.ts +2 -52
  123. package/dist/voice/index.js +1 -84
  124. package/package.json +6 -9
  125. package/skills/deictic/SKILL.md +27 -42
  126. package/skills/deictic/references/recordings.md +9 -108
  127. package/skills/deictic/references/tasks.md +21 -107
  128. package/skills/deictic/references/watch.md +13 -66
  129. package/src/cli/board.ts +204 -0
  130. package/src/cli/bun.ts +133 -0
  131. package/src/cli/edit.ts +56 -0
  132. package/src/cli/find.ts +147 -0
  133. package/src/cli/frame.ts +90 -0
  134. package/src/cli/init.ts +388 -0
  135. package/src/cli/recording.ts +383 -0
  136. package/src/cli/task.ts +126 -0
  137. package/src/cli/transcribe.ts +129 -0
  138. package/src/cli/vb.ts +11 -0
  139. package/src/cli/voice.ts +59 -0
  140. package/src/cli/watch.ts +221 -0
  141. package/src/cli.ts +37 -0
  142. package/src/index.ts +5 -0
  143. package/src/plugins/logs/index.ts +1 -0
  144. package/src/plugins/network/index.ts +1 -0
  145. package/src/plugins/recordings/index.ts +1 -0
  146. package/src/plugins/screenshots/client.ts +3 -2
  147. package/src/plugins/screenshots/index.ts +10 -3
  148. package/src/plugins/screenshots/playwright.ts +34 -7
  149. package/src/plugins/screenshots/rrweb.ts +5 -1
  150. package/src/plugins/tasks/client.ts +62 -7
  151. package/src/plugins/tasks/index.ts +41 -20
  152. package/src/plugins/tasks/local.ts +19 -6
  153. package/src/plugins/tasks/watchers.ts +41 -6
  154. package/src/tools/endpoints.ts +3 -0
  155. package/src/tools/packages.ts +107 -0
  156. package/dist/annotations/index.d.ts.map +0 -1
  157. package/dist/annotations/index.js.map +0 -1
  158. package/dist/index.js.map +0 -1
  159. package/dist/logs/index.d.ts.map +0 -1
  160. package/dist/logs/index.js.map +0 -1
  161. package/dist/network/index.js.map +0 -1
  162. package/dist/recommended/index.js.map +0 -1
  163. package/dist/screenshots/index.js.map +0 -1
  164. package/dist/vite.d.ts.map +0 -1
  165. package/dist/vite.js.map +0 -1
  166. package/dist/voice/index.d.ts.map +0 -1
  167. package/skills/deictic/references/install.md +0 -103
  168. package/skills/deictic/scripts/frame.mjs +0 -62
  169. package/skills/deictic/scripts/lib.mjs +0 -277
  170. package/skills/deictic/scripts/recording.mjs +0 -266
  171. package/skills/deictic/scripts/task.mjs +0 -113
  172. package/skills/deictic/scripts/transcribe.mjs +0 -93
  173. package/skills/deictic/scripts/vb.mjs +0 -12
  174. package/skills/deictic/scripts/voice.mjs +0 -50
  175. package/skills/deictic/scripts/watch.mjs +0 -115
@@ -1,62 +0,0 @@
1
- #!/usr/bin/env node
2
- // Screenshots of a recording at moments of it, as its replay page shows them (marks and pointer included),
3
- // at the recorded viewport's size. By default: just after each change to the marks, and the end.
4
- // Usage: frame.mjs <task | replay URL | recording ID | file> [--at 4.2 ...] [--every 2] [--out dir] [--base url]
5
- // Needs the dev server running (it serves the replay) and Playwright (playwright-core or playwright) in the project.
6
- import { mkdirSync } from 'node:fs';
7
- import { tmpdir } from 'node:os';
8
- import { join, resolve } from 'node:path';
9
-
10
- import { clock, fail, fromProject, loadRecording, parseArgs } from './lib.mjs';
11
-
12
- const { options, rest } = parseArgs(process.argv.slice(2));
13
- const { kept, id, replay } = await loadRecording(rest[0], Number(options.nth?.[0] ?? 1));
14
- const base = options.base?.[0];
15
- // The replay is served by the dev server that recorded it, under deictic's routes.
16
- const page = base
17
- ? `${base.replace(/\/$/, '')}/__deictic/plugins/recordings/replay/${id}`
18
- : (replay ?? `${new URL(kept.page).origin}/__deictic/plugins/recordings/replay/${id}`);
19
-
20
- const t0 = kept.events[0].timestamp;
21
- let times = (options.at ?? []).map(Number);
22
- if (options.every) for (let t = 0; t <= kept.duration / 1000; t += Number(options.every[0])) times.push(t);
23
- if (times.length === 0) {
24
- // Just after each change to the marks, so it's drawn, then the end.
25
- const marks = kept.events.filter((e) => e.type === 5 && e.data.tag === 'deictic.annotations' && (e.data.payload.svg ?? '') !== '');
26
- times = [...marks.map((e) => (e.timestamp - t0 + 50) / 1000), kept.duration / 1000];
27
- }
28
- times = [...new Set(times.map((t) => Math.min(Math.max(0, t), kept.duration / 1000)))].sort((a, b) => a - b);
29
- if (times.some((t) => !Number.isFinite(t))) fail('--at and --every take seconds: --at 4.2');
30
-
31
- const out = resolve(options.out?.[0] ?? join(tmpdir(), 'deictic-frames', id));
32
- mkdirSync(out, { recursive: true });
33
-
34
- const { chromium } = await fromProject('playwright-core', 'playwright');
35
- let browser;
36
- for (const channel of [undefined, 'chrome', 'msedge']) {
37
- try {
38
- browser = await chromium.launch(channel ? { channel } : {});
39
- break;
40
- } catch {}
41
- }
42
- if (browser === undefined) fail('No Chromium to launch: npx playwright install chromium, or install Chrome or Edge.');
43
- try {
44
- // `bare`: the replay alone, at the recorded size, so a window that size shows it 1:1.
45
- const view = await browser.newPage({ viewport: kept.viewport });
46
- for (const t of times) {
47
- const url = new URL(page);
48
- url.searchParams.set('t', t.toFixed(2));
49
- url.searchParams.set('bare', '');
50
- const res = await view.goto(url.href);
51
- if (!res?.ok()) fail(`${url.href}: ${res?.status()}. Is the dev server running? Pass --base with its URL.`);
52
- await view.waitForSelector('body[data-ready]', { timeout: 15_000 });
53
- // The replayed page's images and fonts.
54
- await view.waitForLoadState('networkidle').catch(() => {});
55
- await view.waitForTimeout(200);
56
- const path = join(out, `${String(Math.round(t * 1000)).padStart(6, '0')}.png`);
57
- await view.screenshot({ path });
58
- console.log(`${clock(t * 1000).padStart(6)} ${path}`);
59
- }
60
- } finally {
61
- await browser.close();
62
- }
@@ -1,277 +0,0 @@
1
- // What the scripts share: the board's CLI, the project's `.deictic/` folders, and finding a recording or a
2
- // voice clip by a task's ID, a recording's ID, a replay URL or a path. Node 20 or Bun; no dependencies.
3
- import { spawnSync } from 'node:child_process';
4
- import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
- import { tmpdir } from 'node:os';
6
- import { delimiter, dirname, join, resolve } from 'node:path';
7
- import { pathToFileURL } from 'node:url';
8
-
9
- /** `--name value` and `--flag` options, and the arguments around them. */
10
- export function parseArgs(argv, flags = []) {
11
- const options = {};
12
- const rest = [];
13
- for (let i = 0; i < argv.length; i++) {
14
- const a = argv[i];
15
- if (!a.startsWith('--')) rest.push(a);
16
- else if (flags.includes(a.slice(2))) options[a.slice(2)] = true;
17
- else (options[a.slice(2)] ??= []).push(argv[++i]);
18
- }
19
- return { options, rest };
20
- }
21
-
22
- export function fail(message) {
23
- console.error(message);
24
- process.exit(1);
25
- }
26
-
27
- /** `1:02.5`, from milliseconds. */
28
- export function clock(ms) {
29
- const s = Math.max(0, ms) / 1000;
30
- return `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, '0')}`;
31
- }
32
-
33
- /** This directory and each above it. */
34
- function* upFrom(dir = process.cwd()) {
35
- for (let at = resolve(dir); ; at = dirname(at)) {
36
- yield at;
37
- if (dirname(at) === at) return;
38
- }
39
- }
40
-
41
- /** Every `.deictic/` near here: in this directory or above, or in a folder of it (a site/, an app/). */
42
- export function deicticDirs() {
43
- const found = [...upFrom()].map((d) => join(d, '.deictic')).filter((p) => existsSync(p));
44
- const walk = (dir, depth) => {
45
- if (depth === 0) return;
46
- for (const e of readdirSync(dir, { withFileTypes: true })) {
47
- if (!e.isDirectory() || e.name === 'node_modules' || (e.name.startsWith('.') && e.name !== '.deictic')) continue;
48
- const path = join(dir, e.name);
49
- if (e.name === '.deictic') found.push(path);
50
- else walk(path, depth - 1);
51
- }
52
- };
53
- walk(process.cwd(), 3);
54
- return [...new Set(found)];
55
- }
56
-
57
- /**
58
- * The board's URL: `BOARD_URL`, or with none, the board the dev server started for the project, which
59
- * `.deictic/board.json` names. Nothing where there's neither: `vb` then finds the team's board.
60
- */
61
- export function boardUrl() {
62
- if (process.env.BOARD_URL) return process.env.BOARD_URL;
63
- for (const dir of deicticDirs()) {
64
- try {
65
- const { url } = JSON.parse(readFileSync(join(dir, 'board.json'), 'utf8'));
66
- if (typeof url === 'string') return url;
67
- } catch {
68
- // No board of this project's own: the next one's, or the team's.
69
- }
70
- }
71
- return undefined;
72
- }
73
-
74
- /** How often a watch says it's still there, and so how soon the page knows of one that was killed (three missed). */
75
- const BEAT = 20_000;
76
-
77
- /**
78
- * Tells the project's dev server that `name` watches `channel`, which a board can't say: a file under
79
- * `.deictic/watchers`, written again every `BEAT`, that the Task tab reads. In the `.deictic/` whose board this
80
- * is, or in each one near here where the board is the environment's. Answers what takes it back.
81
- */
82
- export function watching(channel, name) {
83
- const url = boardUrl();
84
- const dirs = deicticDirs();
85
- const boardIn = (dir) => {
86
- try {
87
- return JSON.parse(readFileSync(join(dir, 'board.json'), 'utf8')).url;
88
- } catch {
89
- return undefined;
90
- }
91
- };
92
- const own = dirs.filter((dir) => boardIn(dir) === url);
93
- const files = (own.length > 0 ? own : dirs).map((dir) => join(dir, 'watchers', `${process.pid}.json`));
94
- const beat = () => {
95
- for (const file of files) {
96
- try {
97
- mkdirSync(dirname(file), { recursive: true });
98
- writeFileSync(file, `${JSON.stringify({ name, channel, pid: process.pid, at: Date.now() })}\n`);
99
- } catch {
100
- // A folder that can't be written to: the watch goes on, unseen.
101
- }
102
- }
103
- };
104
- beat();
105
- const timer = setInterval(beat, BEAT);
106
- return () => {
107
- clearInterval(timer);
108
- for (const file of files) rmSync(file, { force: true });
109
- };
110
- }
111
-
112
- /** `30m`, `45s`, `1h` or a bare number of seconds, as milliseconds. */
113
- export function duration(text) {
114
- const [, n, unit = 's'] = /^(\d+(?:\.\d+)?)([smh])?$/.exec(text) ?? [];
115
- if (n === undefined) fail(`"${text}" isn't a duration: 30m, 45s, 1h, or seconds as a number.`);
116
- return Number(n) * { s: 1000, m: 60_000, h: 3_600_000 }[unit];
117
- }
118
-
119
- /** The project's own `@vercel/board` CLI, as a script: from here, above, or beside a `.deictic/` near here. */
120
- function vbScript() {
121
- for (const dir of new Set([...upFrom(), ...deicticDirs().map(dirname)])) {
122
- const pkg = join(dir, 'node_modules', '@vercel', 'board', 'package.json');
123
- if (!existsSync(pkg)) continue;
124
- const { bin } = JSON.parse(readFileSync(pkg, 'utf8'));
125
- const entry = typeof bin === 'string' ? bin : bin?.vb;
126
- if (typeof entry === 'string') return join(dirname(pkg), entry);
127
- }
128
- return undefined;
129
- }
130
-
131
- /**
132
- * How to run the board's CLI, with the environment's board or the project's own, as `spawn`'s command,
133
- * arguments and options: the project's `@vercel/board`, run by this runtime, so it needn't be on the PATH and
134
- * no shell reads the arguments; with none installed, `vb` from the PATH.
135
- */
136
- export function vbCommand(args) {
137
- const bins = [...upFrom()].map((d) => join(d, 'node_modules', '.bin'));
138
- const url = boardUrl();
139
- const env = { ...process.env, ...(url === undefined ? {} : { BOARD_URL: url }), PATH: [...bins, process.env.PATH].join(delimiter) };
140
- const script = vbScript();
141
- if (script !== undefined) return [process.execPath, [script, ...args], { env }];
142
- // npm's shims on Windows are .cmd files, which only a shell runs; the arguments here are IDs and names.
143
- if (process.platform === 'win32') return [`vb ${args.map((a) => `"${a}"`).join(' ')}`, [], { env, shell: true }];
144
- return ['vb', args, { env }];
145
- }
146
-
147
- /** Runs the board's CLI and answers what it printed: parsed with `json`, bytes for a download to stdout. */
148
- export function vb(args, { json = false } = {}) {
149
- const [command, argv, options] = vbCommand(json ? [...args, '--json'] : args);
150
- const run = spawnSync(command, argv, {
151
- ...options,
152
- encoding: json || args[0] !== 'download' ? 'utf8' : 'buffer',
153
- maxBuffer: 1 << 28,
154
- });
155
- if (run.error) fail(`vb: ${run.error.message}. Install @vercel/board in the project, or put vb on the PATH.`);
156
- if (run.status !== 0) fail(`vb ${args.join(' ')}: ${String(run.stderr).trim() || `exit ${run.status}`}`);
157
- return json ? JSON.parse(run.stdout) : run.stdout;
158
- }
159
-
160
- /**
161
- * Who the CLI writes as: `{ actor, handle, profile }`. `profile` is the name `BOARD_PROFILE` (or `--as`) gave, and
162
- * `null` without one: then what's written is the person's own, as the board sees it.
163
- */
164
- export const whoami = () => vb(['whoami'], { json: true });
165
-
166
- /** A task's root message, by its ID (`68` or `#68`). */
167
- export const task = (id) => vb(['read', String(id).replace(/^#/, '')], { json: true }).message;
168
-
169
- /** An attachment's bytes. */
170
- export const download = (attachment) => vb(['download', attachment.id, '-']);
171
-
172
- const TASK = /^#?\d+$/;
173
-
174
- /**
175
- * A recording, with where it came from: `{ kept, id, replay?, task? }`. `ref` is a task's ID (its first
176
- * recording, or the `nth`), a replay or recording URL, a recording's ID kept under a `.deictic/`, or a path.
177
- */
178
- export async function loadRecording(ref, nth = 1) {
179
- if (ref === undefined) fail('Name a recording: a task (68), a replay URL, a recording ID or a JSON file.');
180
- if (TASK.test(ref)) {
181
- const root = task(ref);
182
- const files = root.attachments.filter((a) => /^recording-.*\.json$/.test(a.name));
183
- const file = files[nth - 1];
184
- if (file === undefined) fail(`Task #${root.id} has ${files.length} recording(s), not a ${nth}th.`);
185
- const kept = JSON.parse(download(file).toString('utf8'));
186
- const id = file.name.slice('recording-'.length, -'.json'.length);
187
- const replay = root.text.match(new RegExp(`https?://\\S+/replay/${id}`))?.[0];
188
- return { kept, id, replay, task: root };
189
- }
190
- if (/^https?:/.test(ref)) {
191
- const url = new URL(ref);
192
- const id = url.pathname.split('/').at(-1);
193
- const json = new URL(url.pathname.replace(/\/(replay|recording)\/[^/]+$/, `/recording/${id}`), url);
194
- const res = await fetch(json);
195
- if (!res.ok) fail(`${json}: ${res.status} ${await res.text()}`);
196
- return { kept: await res.json(), id, replay: new URL(json.pathname.replace(/\/recording\//, '/replay/'), url).href };
197
- }
198
- if (existsSync(ref)) return { kept: JSON.parse(readFileSync(ref, 'utf8')), id: ref.replace(/^.*[\\/]|\.json$/g, '') };
199
- for (const dir of deicticDirs()) {
200
- const path = join(dir, 'recordings', `${ref}.json`);
201
- if (existsSync(path)) return { kept: JSON.parse(readFileSync(path, 'utf8')), id: ref };
202
- }
203
- fail(`No recording ${ref} in ${deicticDirs().join(', ') || 'any .deictic/ near here'}: name its task or replay URL instead.`);
204
- }
205
-
206
- /** A voice clip's audio as a file: kept under a `.deictic/`, or downloaded from `fromTask` to a temporary folder. */
207
- export function voiceFile(id, fromTask) {
208
- for (const dir of deicticDirs()) {
209
- const voice = join(dir, 'voice');
210
- const name = existsSync(voice) ? readdirSync(voice).find((f) => f.startsWith(`${id}.`)) : undefined;
211
- if (name !== undefined) return join(voice, name);
212
- }
213
- const file = fromTask?.attachments.find((a) => a.name.startsWith(`voice-${id}.`));
214
- if (file === undefined) fail(`No voice clip ${id} here${fromTask ? ` or on task #${fromTask.id}` : ''}.`);
215
- const path = join(mkdtempSync(join(tmpdir(), 'deictic-voice-')), file.name);
216
- // The CLI writes an attachment to a path of our choosing.
217
- vb(['download', file.id, path]);
218
- return path;
219
- }
220
-
221
- /**
222
- * The voice clips `ref` names, each `{ id, file, at, recording? }`: `at` is where it starts in its recording (0
223
- * for a voice note on its own). `ref` is a task (every recording's clips and its voice notes), a recording as
224
- * `loadRecording` takes one, or a clip's ID.
225
- */
226
- export async function voiceClips(ref) {
227
- if (ref === undefined) fail('Name a task, a recording or a voice clip.');
228
- const clips = [];
229
- if (TASK.test(ref)) {
230
- const root = task(ref);
231
- const recordings = root.attachments.filter((a) => /^recording-.*\.json$/.test(a.name));
232
- const inRecordings = new Set();
233
- for (let n = 1; n <= recordings.length; n++) {
234
- const { kept, id } = await loadRecording(ref, n);
235
- for (const c of kept.voice ?? []) {
236
- inRecordings.add(c.id);
237
- clips.push({ id: c.id, file: voiceFile(c.id, root), at: c.at, recording: id });
238
- }
239
- }
240
- for (const a of root.attachments) {
241
- const id = a.name.match(/^voice-(.+)\.\w+$/)?.[1];
242
- if (id !== undefined && !inRecordings.has(id)) clips.push({ id, file: voiceFile(id, root), at: 0 });
243
- }
244
- } else if (!/^https?:/.test(ref) && !existsSync(ref) && isClip(ref)) {
245
- clips.push({ id: ref, file: voiceFile(ref), at: 0 });
246
- } else {
247
- const { kept, id } = await loadRecording(ref);
248
- for (const c of kept.voice ?? []) clips.push({ id: c.id, file: voiceFile(c.id), at: c.at, recording: id });
249
- }
250
- if (clips.length === 0) fail(`No voice on ${ref}.`);
251
- return clips;
252
- }
253
-
254
- const isClip = (id) =>
255
- deicticDirs().some((d) => existsSync(join(d, 'voice')) && readdirSync(join(d, 'voice')).some((f) => f.startsWith(`${id}.`)));
256
-
257
- /** Runs ffmpeg, which reads what MediaRecorder makes; its log is on stderr. */
258
- export function ffmpeg(args, encoding = 'utf8') {
259
- const run = spawnSync('ffmpeg', ['-hide_banner', '-nostats', ...args], { encoding, maxBuffer: 1 << 30 });
260
- if (run.error) fail('Needs ffmpeg on the PATH (https://ffmpeg.org/download.html).');
261
- return run;
262
- }
263
-
264
- /** The project's own copy of a package, where a script needs one it doesn't bundle (Playwright). */
265
- export async function fromProject(...names) {
266
- for (const dir of upFrom()) {
267
- for (const name of names) {
268
- const pkg = join(dir, 'node_modules', name, 'package.json');
269
- if (!existsSync(pkg)) continue;
270
- const { exports, main } = JSON.parse(readFileSync(pkg, 'utf8'));
271
- const entry = exports?.['.']?.import ?? exports?.['.']?.default ?? main ?? 'index.js';
272
- const path = join(dirname(pkg), typeof entry === 'string' ? entry : (entry.default ?? 'index.js'));
273
- return import(pathToFileURL(path).href);
274
- }
275
- }
276
- return fail(`Needs ${names.join(' or ')} in the project: npm install -D ${names[0]}`);
277
- }
@@ -1,266 +0,0 @@
1
- #!/usr/bin/env node
2
- // A recording as a timeline: the page, each click and field typed in (with the element's place in the source),
3
- // scrolls, resizes, each change to the marks (what was drawn, where, and the notes' text), the voice clips,
4
- // the page's console and its requests where the project records them, and the end.
5
- // Usage: recording.mjs <task | replay URL | recording ID | file> [--nth 2] [--json]
6
- // And to ask for a part of it, in any mix:
7
- // --only console,request these kinds of line (`console` is every level; also page, click, input, scroll, resize, marks, voice)
8
- // --problems errors, warnings and requests that failed
9
- // --from 10 --to 15 a stretch, in seconds; --around 12 is the 3 seconds either side
10
- // --grep text lines with this in them, in any case
11
- // --full all of each line: where it was logged from, a request's headers and bodies
12
- import { clock, fail, loadRecording, parseArgs } from './lib.mjs';
13
-
14
- const { options, rest } = parseArgs(process.argv.slice(2), ['json', 'problems', 'full']);
15
- const { kept, id, replay, task } = await loadRecording(rest[0], Number(options.nth?.[0] ?? 1));
16
- const { events } = kept;
17
- if (!Array.isArray(events) || events.length === 0) fail(`Recording ${id} has no events.`);
18
- const t0 = events[0].timestamp;
19
-
20
- // The page's nodes by rrweb's IDs, from the full snapshot and each mutation: enough to name an element.
21
- const nodes = new Map();
22
- const add = (node, parent) => {
23
- nodes.set(node.id, { ...node, parent, childNodes: undefined, kids: (node.childNodes ?? []).map((c) => c.id) });
24
- for (const c of node.childNodes ?? []) add(c, node.id);
25
- };
26
- const textOf = (nid, max = 60) => {
27
- let out = '';
28
- const walk = (n) => {
29
- const node = nodes.get(n);
30
- if (node === undefined || out.length > max) return;
31
- if (node.type === 3) out += node.textContent ?? '';
32
- for (const k of node.kids ?? []) walk(k);
33
- };
34
- walk(nid);
35
- const text = out.replace(/\s+/g, ' ').trim();
36
- return text.length > max ? `${text.slice(0, max)}…` : text;
37
- };
38
- /** `<button> "Save" at src/App.tsx:9:7`: the element, its text, and the nearest place deictic marked. */
39
- const describe = (nid) => {
40
- const node = nodes.get(nid);
41
- if (node === undefined) return `node ${nid}`;
42
- if (node.type === 0) return 'the page';
43
- let at;
44
- for (let n = node; n !== undefined && at === undefined; n = nodes.get(n.parent)) at = n.attributes?.['data-deictic'];
45
- const tag = node.tagName ? `<${node.tagName}>` : 'text';
46
- const text = textOf(nid);
47
- return `${tag}${text ? ` "${text}"` : ''}${at ? ` at ${at}` : ''}`;
48
- };
49
-
50
- // The marks, as data where the recording has it, else read off the SVG.
51
- const boundsOf = (points) => {
52
- const xs = points.map((p) => p.x);
53
- const ys = points.map((p) => p.y);
54
- return `(${Math.round(Math.min(...xs))},${Math.round(Math.min(...ys))})–(${Math.round(Math.max(...xs))},${Math.round(Math.max(...ys))})`;
55
- };
56
- const shapeOf = ({ shape }) => {
57
- switch (shape.kind) {
58
- case 'box':
59
- return `box ${boundsOf([shape, { x: shape.x + shape.width, y: shape.y + shape.height }])}`;
60
- case 'arrow':
61
- return `arrow from (${Math.round(shape.from.x)},${Math.round(shape.from.y)}) to (${Math.round(shape.to.x)},${Math.round(shape.to.y)})`;
62
- case 'pen':
63
- return `pen stroke over ${boundsOf(shape.points)}`;
64
- case 'note':
65
- return `note at (${Math.round(shape.at.x)},${Math.round(shape.at.y)}): ${JSON.stringify(shape.text)}`;
66
- default:
67
- return shape.kind;
68
- }
69
- };
70
- const pairs = (s) => [...s.matchAll(/(-?[\d.]+)[ ,](-?[\d.]+)/g)].map((m) => ({ x: Number(m[1]), y: Number(m[2]) }));
71
- const shapesInSvg = (svg) => {
72
- const out = [];
73
- const unescape = (t) => t.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '"').replaceAll('&amp;', '&');
74
- for (const m of svg.matchAll(/<(rect|path|polyline|text)\b([^>]*)>(?:(.*?)<\/text>)?/g)) {
75
- const [, tag, attrs, inner] = m;
76
- const num = (name) => Number(attrs.match(new RegExp(`\\b${name}="(-?[\\d.]+)"`))?.[1]);
77
- if (tag === 'rect' && attrs.includes('fill="none"'))
78
- out.push({ shape: { kind: 'box', x: num('x'), y: num('y'), width: num('width'), height: num('height') } });
79
- if (tag === 'path') {
80
- const [from, to] = pairs(attrs.match(/d="([^"]*)"/)[1]);
81
- out.push({ shape: { kind: 'arrow', from, to } });
82
- }
83
- if (tag === 'polyline') out.push({ shape: { kind: 'pen', points: pairs(attrs.match(/points="([^"]*)"/)[1]) } });
84
- if (tag === 'text') {
85
- const lines = [...inner.matchAll(/<tspan[^>]*>(.*?)<\/tspan>/g)].map((l) => unescape(l[1]));
86
- const at = pairs(
87
- inner
88
- .match(/x="(-?[\d.]+)" y="(-?[\d.]+)"/)
89
- ?.slice(1)
90
- .join(',') ?? '0,0',
91
- )[0];
92
- out.push({ shape: { kind: 'note', at, text: lines.join('\n') } });
93
- }
94
- }
95
- return out;
96
- };
97
-
98
- const timeline = [];
99
- const at = (e) => e.timestamp - t0;
100
- const push = (t, kind, text, extra = {}) => timeline.push({ t, at: clock(t), kind, text, ...extra });
101
- let marks = [];
102
- let scroll;
103
- let typing;
104
- const flushScroll = () => {
105
- if (scroll) push(scroll.t, 'scroll', `${describe(scroll.id)} to (${scroll.x},${scroll.y})`);
106
- scroll = undefined;
107
- };
108
- const flushTyping = () => {
109
- if (typing) push(typing.t, 'input', `${describe(typing.id)}: ${typing.value}`);
110
- typing = undefined;
111
- };
112
-
113
- for (const e of events) {
114
- const t = at(e);
115
- if (e.type === 4) push(t, 'page', `${e.data.href} at ${e.data.width}×${e.data.height}`);
116
- if (e.type === 2) {
117
- nodes.clear();
118
- add(e.data.node, undefined);
119
- }
120
- if (e.type === 5 && e.data.tag === 'deictic.annotations') {
121
- const now = e.data.payload.annotations ?? shapesInSvg(e.data.payload.svg ?? '');
122
- const key = (a) => a.id ?? JSON.stringify(a.shape);
123
- const before = new Set(marks.map(key));
124
- const after = new Set(now.map(key));
125
- const added = now.filter((a) => !before.has(key(a)));
126
- const removed = marks.filter((a) => !after.has(key(a)));
127
- if (added.length > 0 || removed.length > 0) {
128
- push(t, 'marks', [...added.map((a) => `+ ${shapeOf(a)}`), ...removed.map((a) => `− ${shapeOf(a)}`)].join('; '), {
129
- marks: now.map((a) => a.shape),
130
- });
131
- }
132
- marks = now;
133
- }
134
- // The address changed with no load: a route of the app's.
135
- if (e.type === 5 && e.data.tag === 'deictic.page') push(t, 'page', `${e.data.payload.href} (a route change, no load)`);
136
- // The page's console, and errors nothing caught (rrweb's console plugin): each argument as JSON, a string in
137
- // quotes, and where it was logged from, which goes under a warning or an error.
138
- if (e.type === 6 && e.data.plugin === 'rrweb/console@1') {
139
- const { level, payload, trace } = e.data.payload;
140
- const plain = (arg) => {
141
- try {
142
- const value = JSON.parse(arg);
143
- return typeof value === 'string' ? value : arg;
144
- } catch {
145
- return arg;
146
- }
147
- };
148
- push(t, `console.${level}`, (payload ?? []).map(plain).join(' '), {
149
- trace: trace ?? [],
150
- ...(['error', 'assert', 'warn'].includes(level) ? { problem: true } : {}),
151
- });
152
- }
153
- // The page's requests (rrweb's network plugin), masked as they were kept: each as it ended. One the browser
154
- // reported of itself has no method; headers and bodies, where kept, are in `--json`.
155
- if (e.type === 6 && e.data.plugin === 'rrweb/network@1') {
156
- for (const r of e.data.payload.requests ?? []) {
157
- const took = Number.isFinite(r.duration) ? ` in ${Math.round(r.duration)} ms` : '';
158
- const status = r.status ? r.status : 'no status (failed, blocked, or another origin’s)';
159
- push(t, 'request', `${r.method ?? r.initiatorType ?? ''} ${r.name} → ${status}${took}`.trim(), {
160
- request: r,
161
- ...(r.status >= 400 ? { problem: true } : {}),
162
- ...(e.data.payload.isInitial ? { before: 'made as the page loaded, before this moment' } : {}),
163
- });
164
- }
165
- }
166
- if (e.type === 5 && e.data.tag === 'deictic.end') push(t, 'end', 'recording stopped');
167
- if (e.type !== 3) continue;
168
- const d = e.data;
169
- if (d.source === 0) {
170
- for (const a of d.adds ?? []) add(a.node, a.parentId);
171
- for (const a of d.attributes ?? []) {
172
- const node = nodes.get(a.id);
173
- if (node) node.attributes = { ...node.attributes, ...a.attributes };
174
- }
175
- for (const x of d.texts ?? []) {
176
- const node = nodes.get(x.id);
177
- if (node) node.textContent = x.value;
178
- }
179
- }
180
- if (d.source === 2 && [2, 3, 4].includes(d.type)) {
181
- flushScroll();
182
- flushTyping();
183
- const what = { 2: 'click', 3: 'right-click', 4: 'double-click' }[d.type];
184
- // A click a key made (Enter on a button) has no position.
185
- const where = d.x === 0 && d.y === 0 ? ' by keyboard' : ` at (${Math.round(d.x)},${Math.round(d.y)}) in the viewport`;
186
- push(t, what, `${describe(d.id)}${where}`, { node: d.id });
187
- }
188
- if (d.source === 3) {
189
- if (scroll && scroll.id !== d.id) flushScroll();
190
- scroll = { t: scroll?.t ?? t, id: d.id, x: Math.round(d.x), y: Math.round(d.y) };
191
- }
192
- if (d.source === 4) push(t, 'resize', `viewport ${d.width}×${d.height}`);
193
- if (d.source === 5) {
194
- if (typing && typing.id !== d.id) flushTyping();
195
- typing = {
196
- t: typing?.t ?? t,
197
- id: d.id,
198
- value: d.isChecked !== undefined && d.text === undefined ? String(d.isChecked) : JSON.stringify(d.text),
199
- };
200
- }
201
- }
202
- flushScroll();
203
- flushTyping();
204
- for (const c of kept.voice ?? []) push(c.at, 'voice', `clip ${c.id}, ${clock(c.duration)} long, until ${clock(c.at + c.duration)}`);
205
- timeline.sort((a, b) => a.t - b.t);
206
-
207
- // The part asked for. Seconds, as the replay's `?t=` and `frame.mjs --at` take them.
208
- const seconds = (name) => {
209
- const given = options[name]?.[0];
210
- if (given === undefined) return undefined;
211
- const value = Number(given);
212
- if (!Number.isFinite(value)) fail(`--${name} takes seconds from the recording's start, as 12 or 4.5: not ${given}`);
213
- return value * 1000;
214
- };
215
- const around = seconds('around');
216
- const from = seconds('from') ?? (around === undefined ? undefined : around - 3000);
217
- const to = seconds('to') ?? (around === undefined ? undefined : around + 3000);
218
- const only = (options.only ?? []).flatMap((list) => String(list).split(',')).filter(Boolean);
219
- const grep = options.grep?.[0]?.toLowerCase();
220
- // `console` is every level's lines, `click` a right or a double one too.
221
- const isKind = (kind, asked) => kind === asked || kind.startsWith(`${asked}.`) || kind.endsWith(`-${asked}`);
222
- const shown = timeline.filter(
223
- (e) =>
224
- (only.length === 0 || only.some((asked) => isKind(e.kind, asked))) &&
225
- (!options.problems || e.problem === true) &&
226
- (from === undefined || e.t >= from) &&
227
- (to === undefined || e.t <= to) &&
228
- (grep === undefined || `${e.kind} ${e.text}`.toLowerCase().includes(grep)),
229
- );
230
-
231
- const head = {
232
- id,
233
- page: kept.page,
234
- viewport: kept.viewport,
235
- colorScheme: kept.colorScheme ?? 'light',
236
- startedAt: new Date(kept.startedAt ?? t0).toISOString(),
237
- duration: kept.duration,
238
- replay,
239
- task: task?.id,
240
- };
241
- if (options.json) {
242
- console.log(JSON.stringify({ ...head, lines: timeline.length, timeline: shown }, null, 2));
243
- } else {
244
- console.log(`Recording ${id}${task ? ` on task #${task.id}` : ''}: ${clock(kept.duration)} of ${kept.page}`);
245
- console.log(`viewport ${kept.viewport.width}×${kept.viewport.height}, ${head.colorScheme}, started ${head.startedAt}`);
246
- if (replay) console.log(`replays at ${replay} (add ?t=<seconds> to open it paused there)`);
247
- if (shown.length < timeline.length) console.log(`${shown.length} of its ${timeline.length} lines, as asked`);
248
- console.log();
249
- const under = (line) => console.log(`${' '.repeat(22)}${line}`);
250
- for (const e of shown) {
251
- console.log(`${e.at.padStart(6)} ${e.kind.padEnd(13)} ${e.text}`);
252
- // Where a warning or an error came from, its nearest few places: all of them, and every line's, with `--full`.
253
- if (e.trace && (options.full || e.problem)) for (const line of options.full ? e.trace : e.trace.slice(0, 5)) under(`at ${line}`);
254
- if (!options.full || !e.request) continue;
255
- const r = e.request;
256
- if (e.before) under(e.before);
257
- for (const [title, held] of [
258
- ['request headers', r.requestHeaders],
259
- ['response headers', r.responseHeaders],
260
- ])
261
- for (const [name, value] of Object.entries(held ?? {})) under(`${title} ${name}: ${value}`);
262
- if (r.requestBody) under(`request body ${r.requestBody}`);
263
- if (r.responseBody) under(`response body ${r.responseBody}`);
264
- }
265
- if (shown.length === 0) console.log(timeline.length === 0 ? 'Nothing in it.' : 'No line of it is what was asked for.');
266
- }