deictic 0.0.1 → 0.2.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/LICENSE +21 -0
- package/README.md +167 -0
- package/dist/annotations/client.d.ts +4 -0
- package/dist/annotations/client.d.ts.map +1 -0
- package/dist/annotations/client.js +497 -0
- package/dist/annotations/client.js.map +1 -0
- package/dist/annotations/index.d.ts +110 -0
- package/dist/annotations/index.d.ts.map +1 -0
- package/dist/annotations/index.js +22 -0
- package/dist/annotations/index.js.map +1 -0
- package/dist/astro.d.ts +29 -0
- package/dist/astro.d.ts.map +1 -0
- package/dist/astro.js +24 -0
- package/dist/astro.js.map +1 -0
- package/dist/bun.d.ts +12 -0
- package/dist/bun.d.ts.map +1 -0
- package/dist/bun.js +67 -0
- package/dist/bun.js.map +1 -0
- package/dist/client/index.d.ts +95 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +1333 -0
- package/dist/client/index.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/loader.d.ts +15 -0
- package/dist/loader.d.ts.map +1 -0
- package/dist/loader.js +17 -0
- package/dist/loader.js.map +1 -0
- package/dist/next.d.ts +17 -0
- package/dist/next.d.ts.map +1 -0
- package/dist/next.js +150 -0
- package/dist/next.js.map +1 -0
- package/dist/recommended/index.d.ts +25 -0
- package/dist/recommended/index.d.ts.map +1 -0
- package/dist/recommended/index.js +19 -0
- package/dist/recommended/index.js.map +1 -0
- package/dist/recordings/client.d.ts +4 -0
- package/dist/recordings/client.d.ts.map +1 -0
- package/dist/recordings/client.js +376 -0
- package/dist/recordings/client.js.map +1 -0
- package/dist/recordings/index.d.ts +2 -0
- package/dist/recordings/index.js +3 -0
- package/dist/screenshots/client.d.ts +23 -0
- package/dist/screenshots/client.d.ts.map +1 -0
- package/dist/screenshots/client.js +76 -0
- package/dist/screenshots/client.js.map +1 -0
- package/dist/screenshots/dom.d.ts +4 -0
- package/dist/screenshots/dom.d.ts.map +1 -0
- package/dist/screenshots/dom.js +92 -0
- package/dist/screenshots/dom.js.map +1 -0
- package/dist/screenshots/index.d.ts +2 -0
- package/dist/screenshots/index.js +98 -0
- package/dist/screenshots/index.js.map +1 -0
- package/dist/screenshots/rrweb.d.ts +9 -0
- package/dist/screenshots/rrweb.d.ts.map +1 -0
- package/dist/screenshots/rrweb.js +60 -0
- package/dist/screenshots/rrweb.js.map +1 -0
- package/dist/shared/endpoints.js +354 -0
- package/dist/shared/endpoints.js.map +1 -0
- package/dist/shared/index.d.ts +226 -0
- package/dist/shared/index.d.ts.map +1 -0
- package/dist/shared/index2.d.ts +98 -0
- package/dist/shared/index2.d.ts.map +1 -0
- package/dist/shared/index3.d.ts +86 -0
- package/dist/shared/index3.d.ts.map +1 -0
- package/dist/shared/index4.d.ts +184 -0
- package/dist/shared/index4.d.ts.map +1 -0
- package/dist/shared/index5.d.ts +70 -0
- package/dist/shared/index5.d.ts.map +1 -0
- package/dist/shared/integration.d.ts +20 -0
- package/dist/shared/integration.d.ts.map +1 -0
- package/dist/shared/integration.js +279 -0
- package/dist/shared/integration.js.map +1 -0
- package/dist/shared/kept.js +23 -0
- package/dist/shared/kept.js.map +1 -0
- package/dist/shared/marks.js +14 -0
- package/dist/shared/marks.js.map +1 -0
- package/dist/shared/playwright.js +105 -0
- package/dist/shared/playwright.js.map +1 -0
- package/dist/shared/recordings.js +246 -0
- package/dist/shared/recordings.js.map +1 -0
- package/dist/shared/shortcut.js +63 -0
- package/dist/shared/shortcut.js.map +1 -0
- package/dist/shared/tasks.js +521 -0
- package/dist/shared/tasks.js.map +1 -0
- package/dist/shared/waveform.js +93 -0
- package/dist/shared/waveform.js.map +1 -0
- package/dist/tailwind/client.d.ts +4 -0
- package/dist/tailwind/client.d.ts.map +1 -0
- package/dist/tailwind/client.js +613 -0
- package/dist/tailwind/client.js.map +1 -0
- package/dist/tailwind/index.d.ts +2 -0
- package/dist/tailwind/index.js +557 -0
- package/dist/tailwind/index.js.map +1 -0
- package/dist/tasks/client.d.ts +6 -0
- package/dist/tasks/client.d.ts.map +1 -0
- package/dist/tasks/client.js +642 -0
- package/dist/tasks/client.js.map +1 -0
- package/dist/tasks/index.d.ts +2 -0
- package/dist/tasks/index.js +1 -0
- package/dist/vite.d.ts +16 -0
- package/dist/vite.d.ts.map +1 -0
- package/dist/vite.js +61 -0
- package/dist/vite.js.map +1 -0
- package/dist/voice/client.d.ts +4 -0
- package/dist/voice/client.d.ts.map +1 -0
- package/dist/voice/client.js +66 -0
- package/dist/voice/client.js.map +1 -0
- package/dist/voice/index.d.ts +47 -0
- package/dist/voice/index.d.ts.map +1 -0
- package/dist/voice/index.js +74 -0
- package/dist/voice/index.js.map +1 -0
- package/dist/webpack.d.ts +50 -0
- package/dist/webpack.d.ts.map +1 -0
- package/dist/webpack.js +78 -0
- package/dist/webpack.js.map +1 -0
- package/package.json +307 -7
- package/skills/deictic/SKILL.md +47 -0
- package/skills/deictic/references/install.md +96 -0
- package/skills/deictic/references/recordings.md +83 -0
- package/skills/deictic/references/tasks.md +79 -0
- package/skills/deictic/references/watch.md +43 -0
- package/skills/deictic/scripts/frame.mjs +62 -0
- package/skills/deictic/scripts/lib.mjs +211 -0
- package/skills/deictic/scripts/recording.mjs +186 -0
- package/skills/deictic/scripts/task.mjs +84 -0
- package/skills/deictic/scripts/transcribe.mjs +93 -0
- package/skills/deictic/scripts/voice.mjs +50 -0
- package/skills/deictic/scripts/watch.mjs +51 -0
- package/src/astro.ts +34 -0
- package/src/bun.ts +79 -0
- package/src/client/index.ts +846 -0
- package/src/client/lightbox.ts +256 -0
- package/src/client/style.ts +243 -0
- package/src/client/tooltip.ts +78 -0
- package/src/client/waveform.ts +98 -0
- package/src/index.ts +247 -0
- package/src/loader.ts +28 -0
- package/src/next.ts +133 -0
- package/src/plugins/annotations/client.ts +301 -0
- package/src/plugins/annotations/draw.ts +169 -0
- package/src/plugins/annotations/index.ts +105 -0
- package/src/plugins/annotations/svg.ts +61 -0
- package/src/plugins/recommended/index.ts +35 -0
- package/src/plugins/recordings/client.ts +316 -0
- package/src/plugins/recordings/index.ts +175 -0
- package/src/plugins/recordings/marks.ts +11 -0
- package/src/plugins/recordings/ours.ts +70 -0
- package/src/plugins/recordings/replay.ts +165 -0
- package/src/plugins/screenshots/client.ts +64 -0
- package/src/plugins/screenshots/dom.ts +79 -0
- package/src/plugins/screenshots/index.ts +194 -0
- package/src/plugins/screenshots/playwright.ts +119 -0
- package/src/plugins/screenshots/rrweb.ts +45 -0
- package/src/plugins/tailwind/catalog.ts +396 -0
- package/src/plugins/tailwind/client.ts +669 -0
- package/src/plugins/tailwind/index.ts +267 -0
- package/src/plugins/tasks/client.ts +622 -0
- package/src/plugins/tasks/index.ts +557 -0
- package/src/plugins/tasks/local.ts +170 -0
- package/src/plugins/voice/client.ts +58 -0
- package/src/plugins/voice/index.ts +114 -0
- package/src/shortcut.ts +83 -0
- package/src/tools/astro.ts +81 -0
- package/src/tools/editor.ts +22 -0
- package/src/tools/endpoints.ts +163 -0
- package/src/tools/history.ts +203 -0
- package/src/tools/integration.ts +108 -0
- package/src/tools/kept.ts +21 -0
- package/src/tools/locate.ts +94 -0
- package/src/tools/plugins.ts +41 -0
- package/src/tools/source.ts +72 -0
- package/src/vite.ts +81 -0
- package/src/webpack.ts +107 -0
- package/index.js +0 -1
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// src/plugins/recordings/marks.ts
|
|
2
|
+
/**
|
|
3
|
+
* The custom event's tag the marks go in: the page's annotations, as an SVG in page coordinates (`svg`),
|
|
4
|
+
* and as the annotations themselves (`annotations`, absent from recordings made before it was added).
|
|
5
|
+
*/
|
|
6
|
+
const MARKS = "deictic.annotations";
|
|
7
|
+
/**
|
|
8
|
+
* The custom event a recording ends with: rrweb's timeline lasts as long as its events, so without it a
|
|
9
|
+
* recording of a still page (a voice-over, say) would replay as a moment, and its voice never play.
|
|
10
|
+
*/
|
|
11
|
+
const END = "deictic.end";
|
|
12
|
+
export { MARKS as n, END as t };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=marks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"marks.js","names":[],"sources":["../../src/plugins/recordings/marks.ts"],"sourcesContent":["/**\n * The custom event's tag the marks go in: the page's annotations, as an SVG in page coordinates (`svg`),\n * and as the annotations themselves (`annotations`, absent from recordings made before it was added).\n */\nexport const MARKS = 'deictic.annotations';\n\n/**\n * The custom event a recording ends with: rrweb's timeline lasts as long as its events, so without it a\n * recording of a still page (a voice-over, say) would replay as a moment, and its voice never play.\n */\nexport const END = 'deictic.end';\n"],"mappings":";;;;;AAIA,MAAa,QAAQ;;;;;AAMrB,MAAa,MAAM"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
// src/plugins/screenshots/playwright.ts
|
|
3
|
+
/**
|
|
4
|
+
* The `rrweb()` renderer's server half: rebuilds a page's snapshot in a browser beside the dev server and
|
|
5
|
+
* screenshots it at the page's viewport, scroll and pixel density, so text lays out as the page's does. The
|
|
6
|
+
* browser is launched on the first shot and kept for the next; Playwright closes it with the process.
|
|
7
|
+
*
|
|
8
|
+
* The snapshot is rebuilt into a sandboxed iframe filling a blank page on the page's own origin, which
|
|
9
|
+
* Playwright answers itself, so nothing asks the dev server for it: rrweb has made the snapshot's URLs
|
|
10
|
+
* whole, and its stylesheets' fonts and images load from the dev server as the page's did.
|
|
11
|
+
*/
|
|
12
|
+
const HOST = "<!doctype html><html><body style=\"margin:0\"></body></html>";
|
|
13
|
+
const browsers = /* @__PURE__ */ new Map();
|
|
14
|
+
/** A browser by the options, launched once: the one named, or Playwright's own Chromium, then Chrome, then Edge. */
|
|
15
|
+
function browserOf(options) {
|
|
16
|
+
const key = JSON.stringify(options);
|
|
17
|
+
const known = browsers.get(key);
|
|
18
|
+
if (known !== void 0) return known;
|
|
19
|
+
const launched = launch(options);
|
|
20
|
+
browsers.set(key, launched);
|
|
21
|
+
launched.catch(() => browsers.delete(key));
|
|
22
|
+
return launched;
|
|
23
|
+
}
|
|
24
|
+
async function launch({ executablePath, channel }) {
|
|
25
|
+
const { chromium } = await import("playwright-core").catch((e) => {
|
|
26
|
+
throw new Error("the rrweb() renderer needs playwright-core: add it to your devDependencies", { cause: e });
|
|
27
|
+
});
|
|
28
|
+
if (executablePath !== void 0 || channel !== void 0) return chromium.launch({
|
|
29
|
+
executablePath,
|
|
30
|
+
channel
|
|
31
|
+
});
|
|
32
|
+
const tried = [];
|
|
33
|
+
for (const attempt of [
|
|
34
|
+
{},
|
|
35
|
+
{ channel: "chrome" },
|
|
36
|
+
{ channel: "msedge" }
|
|
37
|
+
]) try {
|
|
38
|
+
return await chromium.launch(attempt);
|
|
39
|
+
} catch (e) {
|
|
40
|
+
tried.push(`${"channel" in attempt ? attempt.channel : "Playwright's Chromium"}: ${(e instanceof Error ? e.message : String(e)).split("\n", 1)[0]}`);
|
|
41
|
+
}
|
|
42
|
+
throw new Error(`the rrweb() renderer found no browser to render in (${tried.join("; ")}): run \`npx playwright install chromium\`, or pass rrweb({ executablePath })`);
|
|
43
|
+
}
|
|
44
|
+
/** The rrweb-snapshot bundle that defines `rrwebSnapshot` in a page: its CommonJS entry is that bundle. */
|
|
45
|
+
const bundle = () => createRequire(import.meta.url).resolve("rrweb-snapshot");
|
|
46
|
+
async function render(input, options) {
|
|
47
|
+
const shot = input;
|
|
48
|
+
if (typeof shot?.url !== "string" || typeof shot.snapshot !== "object" || typeof shot.viewport?.width !== "number") throw new Error("screenshots: that is not a snapshot the rrweb() renderer took");
|
|
49
|
+
const context = await (await browserOf(options)).newContext({
|
|
50
|
+
viewport: shot.viewport,
|
|
51
|
+
deviceScaleFactor: shot.scale
|
|
52
|
+
});
|
|
53
|
+
try {
|
|
54
|
+
const page = await context.newPage();
|
|
55
|
+
const host = new URL("/__deictic/plugins/screenshots/host", shot.url).href;
|
|
56
|
+
await page.route(host, (route) => route.fulfill({
|
|
57
|
+
contentType: "text/html",
|
|
58
|
+
body: HOST
|
|
59
|
+
}));
|
|
60
|
+
await page.goto(host);
|
|
61
|
+
await page.addScriptTag({ path: bundle() });
|
|
62
|
+
await page.evaluate(async ({ snapshot, scroll, overlay }) => {
|
|
63
|
+
const { rebuildIntoSandboxedIframe, createCache, createMirror } = globalThis.rrwebSnapshot;
|
|
64
|
+
const { iframe } = rebuildIntoSandboxedIframe(snapshot, {
|
|
65
|
+
root: document.body,
|
|
66
|
+
cache: createCache(),
|
|
67
|
+
mirror: createMirror(),
|
|
68
|
+
iframeAttributes: { style: "border:0;position:fixed;inset:0;width:100vw;height:100vh" }
|
|
69
|
+
});
|
|
70
|
+
const doc = iframe.contentDocument;
|
|
71
|
+
if (doc === null) throw new Error("screenshots: the snapshot was rebuilt where it cannot be read");
|
|
72
|
+
await doc.fonts.ready;
|
|
73
|
+
await Promise.all([...doc.images].map((img) => img.decode().catch(() => {})));
|
|
74
|
+
iframe.contentWindow?.scrollTo(scroll.x, scroll.y);
|
|
75
|
+
if (overlay === void 0) return;
|
|
76
|
+
const marks = document.createElement("div");
|
|
77
|
+
marks.style.cssText = "position:fixed;inset:0;z-index:1;pointer-events:none";
|
|
78
|
+
marks.innerHTML = overlay;
|
|
79
|
+
document.body.append(marks);
|
|
80
|
+
}, shot);
|
|
81
|
+
const clip = shot.clip === void 0 ? void 0 : clamp(shot.clip, shot.viewport);
|
|
82
|
+
return new Uint8Array(await page.screenshot({
|
|
83
|
+
type: "png",
|
|
84
|
+
...clip === void 0 ? {} : { clip }
|
|
85
|
+
}));
|
|
86
|
+
} finally {
|
|
87
|
+
await context.close();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** A box kept within the viewport: an element partly scrolled out of it shows only the part that's in. */
|
|
91
|
+
function clamp(box, viewport) {
|
|
92
|
+
const x = Math.max(0, box.x);
|
|
93
|
+
const y = Math.max(0, box.y);
|
|
94
|
+
const width = Math.min(viewport.width, box.x + box.width) - x;
|
|
95
|
+
const height = Math.min(viewport.height, box.y + box.height) - y;
|
|
96
|
+
return width > 0 && height > 0 ? {
|
|
97
|
+
x,
|
|
98
|
+
y,
|
|
99
|
+
width,
|
|
100
|
+
height
|
|
101
|
+
} : void 0;
|
|
102
|
+
}
|
|
103
|
+
export { render };
|
|
104
|
+
|
|
105
|
+
//# sourceMappingURL=playwright.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"playwright.js","names":[],"sources":["../../src/plugins/screenshots/playwright.ts"],"sourcesContent":["/**\n * The `rrweb()` renderer's server half: rebuilds a page's snapshot in a browser beside the dev server and\n * screenshots it at the page's viewport, scroll and pixel density, so text lays out as the page's does. The\n * browser is launched on the first shot and kept for the next; Playwright closes it with the process.\n *\n * The snapshot is rebuilt into a sandboxed iframe filling a blank page on the page's own origin, which\n * Playwright answers itself, so nothing asks the dev server for it: rrweb has made the snapshot's URLs\n * whole, and its stylesheets' fonts and images load from the dev server as the page's did.\n */\nimport { createRequire } from 'node:module';\n\nimport type { Browser } from 'playwright-core';\nimport type * as Rrweb from 'rrweb-snapshot';\n\nimport type { Box, BrowserOptions } from './index.ts';\n\n/** What the page sends: its snapshot and what's needed to show it as the page does. */\n/** A node of an rrweb snapshot, as `snapshot()` answers it. */\nexport type SnapshotNode = NonNullable<ReturnType<typeof Rrweb.snapshot>>;\n\nexport interface Snapshot {\n snapshot: SnapshotNode;\n url: string;\n viewport: { width: number; height: number };\n scroll: { x: number; y: number };\n scale: number;\n /** The part of the viewport to keep, for a shot of an element alone. */\n clip?: Box;\n /** An SVG the viewport's size, drawn over the page: the annotations, where there are any. */\n overlay?: string;\n}\n\nconst HOST = '<!doctype html><html><body style=\"margin:0\"></body></html>';\n\nconst browsers = new Map<string, Promise<Browser>>();\n\n/** A browser by the options, launched once: the one named, or Playwright's own Chromium, then Chrome, then Edge. */\nexport function browserOf(options: BrowserOptions): Promise<Browser> {\n const key = JSON.stringify(options);\n const known = browsers.get(key);\n if (known !== undefined) return known;\n const launched = launch(options);\n browsers.set(key, launched);\n // A launch that failed is tried again on the next shot, after the user installs what it said to.\n launched.catch(() => browsers.delete(key));\n return launched;\n}\n\nasync function launch({ executablePath, channel }: BrowserOptions): Promise<Browser> {\n const { chromium } = await import('playwright-core').catch((e: unknown) => {\n throw new Error('the rrweb() renderer needs playwright-core: add it to your devDependencies', { cause: e });\n });\n if (executablePath !== undefined || channel !== undefined) return chromium.launch({ executablePath, channel });\n const tried: string[] = [];\n for (const attempt of [{}, { channel: 'chrome' }, { channel: 'msedge' }]) {\n try {\n return await chromium.launch(attempt);\n } catch (e) {\n tried.push(\n `${'channel' in attempt ? attempt.channel : \"Playwright's Chromium\"}: ${(e instanceof Error ? e.message : String(e)).split('\\n', 1)[0]}`,\n );\n }\n }\n throw new Error(\n `the rrweb() renderer found no browser to render in (${tried.join('; ')}): run \\`npx playwright install chromium\\`, or pass rrweb({ executablePath })`,\n );\n}\n\n/** The rrweb-snapshot bundle that defines `rrwebSnapshot` in a page: its CommonJS entry is that bundle. */\nconst bundle = () => createRequire(import.meta.url).resolve('rrweb-snapshot');\n\nexport async function render(input: unknown, options: BrowserOptions): Promise<Uint8Array> {\n const shot = input as Snapshot;\n if (typeof shot?.url !== 'string' || typeof shot.snapshot !== 'object' || typeof shot.viewport?.width !== 'number')\n throw new Error('screenshots: that is not a snapshot the rrweb() renderer took');\n const browser = await browserOf(options);\n const context = await browser.newContext({ viewport: shot.viewport, deviceScaleFactor: shot.scale });\n try {\n const page = await context.newPage();\n const host = new URL('/__deictic/plugins/screenshots/host', shot.url).href;\n await page.route(host, (route) => route.fulfill({ contentType: 'text/html', body: HOST }));\n await page.goto(host);\n await page.addScriptTag({ path: bundle() });\n await page.evaluate(async ({ snapshot, scroll, overlay }) => {\n const { rebuildIntoSandboxedIframe, createCache, createMirror } = (globalThis as unknown as { rrwebSnapshot: typeof Rrweb })\n .rrwebSnapshot;\n const { iframe } = rebuildIntoSandboxedIframe(snapshot, {\n root: document.body,\n cache: createCache(),\n mirror: createMirror(),\n iframeAttributes: { style: 'border:0;position:fixed;inset:0;width:100vw;height:100vh' },\n });\n const doc = iframe.contentDocument;\n if (doc === null) throw new Error('screenshots: the snapshot was rebuilt where it cannot be read');\n await doc.fonts.ready;\n await Promise.all([...doc.images].map((img) => img.decode().catch(() => {})));\n iframe.contentWindow?.scrollTo(scroll.x, scroll.y);\n if (overlay === undefined) return;\n // Over the page and its scroll: the SVG is the viewport's, already where it scrolled to.\n const marks = document.createElement('div');\n marks.style.cssText = 'position:fixed;inset:0;z-index:1;pointer-events:none';\n marks.innerHTML = overlay;\n document.body.append(marks);\n }, shot);\n const clip = shot.clip === undefined ? undefined : clamp(shot.clip, shot.viewport);\n return new Uint8Array(await page.screenshot({ type: 'png', ...(clip === undefined ? {} : { clip }) }));\n } finally {\n await context.close();\n }\n}\n\n/** A box kept within the viewport: an element partly scrolled out of it shows only the part that's in. */\nfunction clamp(box: Box, viewport: { width: number; height: number }): Box | undefined {\n const x = Math.max(0, box.x);\n const y = Math.max(0, box.y);\n const width = Math.min(viewport.width, box.x + box.width) - x;\n const height = Math.min(viewport.height, box.y + box.height) - y;\n return width > 0 && height > 0 ? { x, y, width, height } : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAgCA,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAA8B;;AAGnD,SAAgB,UAAU,SAA2C;CACnE,MAAM,MAAM,KAAK,UAAU,OAAO;CAClC,MAAM,QAAQ,SAAS,IAAI,GAAG;CAC9B,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,MAAM,WAAW,OAAO,OAAO;CAC/B,SAAS,IAAI,KAAK,QAAQ;CAE1B,SAAS,YAAY,SAAS,OAAO,GAAG,CAAC;CACzC,OAAO;AACT;AAEA,eAAe,OAAO,EAAE,gBAAgB,WAA6C;CACnF,MAAM,EAAE,aAAa,MAAM,OAAO,kBAAkB,CAAC,OAAO,MAAe;EACzE,MAAM,IAAI,MAAM,8EAA8E,EAAE,OAAO,E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
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { definePlugin } from "../index.js";
|
|
5
|
+
import { t as keptIn } from "./kept.js";
|
|
6
|
+
import { n as MARKS } from "./marks.js";
|
|
7
|
+
// src/plugins/recordings/replay.ts
|
|
8
|
+
/**
|
|
9
|
+
* The replay page, `replay/<id>`: rrweb's own player (`rrweb-player`), its timeline, speeds, skipping idle
|
|
10
|
+
* stretches and fullscreen, sized to the window, with what it doesn't do drawn over it:
|
|
11
|
+
*
|
|
12
|
+
* - The page shows in the colour scheme it was recorded in, whatever the viewer's: the replay's iframe
|
|
13
|
+
* answers `prefers-color-scheme` as the viewer's browser does, so the recorded CSS's queries are rewritten
|
|
14
|
+
* before it's replayed, the recorded scheme's to always match and the other's never.
|
|
15
|
+
* - The marks drawn while recording come as custom events, an SVG in page coordinates each; they're drawn
|
|
16
|
+
* over the replay in the player's own scaled wrapper, moved with its scroll, rather than into its document,
|
|
17
|
+
* which the replayer rebuilds. Each is a marker on the timeline.
|
|
18
|
+
* - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser
|
|
19
|
+
* plays sound only after a click.
|
|
20
|
+
*
|
|
21
|
+
* `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a
|
|
22
|
+
* screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says
|
|
23
|
+
* it's in place.
|
|
24
|
+
*
|
|
25
|
+
* The plugin's routes serve it, the player and what it plays. A page with no server behind it (a `standalone` build)
|
|
26
|
+
* publishes it as a file instead, `replayPage(sources)`: which recording is `?id=`, and a script of its own says
|
|
27
|
+
* where one is.
|
|
28
|
+
*/
|
|
29
|
+
/** The replay page's HTML: the routes' as it is, or one for a page published as a file. */
|
|
30
|
+
const replayPage = ({ player = "..", source } = {}) => `<!doctype html>
|
|
31
|
+
<html lang="en">
|
|
32
|
+
<meta charset="utf-8">
|
|
33
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
34
|
+
<title>Recording · deictic</title>
|
|
35
|
+
<link rel="stylesheet" href="${player}/player.css">
|
|
36
|
+
<style>
|
|
37
|
+
:root { color-scheme: dark; --accent: #12b358; }
|
|
38
|
+
body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }
|
|
39
|
+
header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }
|
|
40
|
+
header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
41
|
+
main { flex: 1; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }
|
|
42
|
+
body.bare header { display: none; }
|
|
43
|
+
body.bare main { padding: 0; }
|
|
44
|
+
body.embed header { display: none; }
|
|
45
|
+
body.embed main { padding: 0; }
|
|
46
|
+
body.embed #main .rr-player { box-shadow: none; border-radius: 0; }
|
|
47
|
+
#marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }
|
|
48
|
+
#marks svg { position: absolute; left: 0; top: 0; overflow: visible; }
|
|
49
|
+
.problem { color: #f87171; padding: 16px; }
|
|
50
|
+
/* rrweb-player, in the dark of the rest of deictic. Its rules repeat Svelte's scoping class, so these start
|
|
51
|
+
from #main, which outweighs any number of classes. */
|
|
52
|
+
#main .rr-player { background: #27272a; box-shadow: 0 12px 32px rgb(0 0 0 / 0.5); border-radius: 8px; overflow: hidden; }
|
|
53
|
+
body.bare #main .rr-player { box-shadow: none; border-radius: 0; }
|
|
54
|
+
#main .rr-player .rr-player__frame { background: #fff; }
|
|
55
|
+
#main .rr-player .rr-controller { background: #18181b; border-top: 1px solid #3f3f46; border-radius: 0; }
|
|
56
|
+
#main .rr-player .rr-timeline__time { color: #a1a1aa; font: 12px ui-monospace, monospace; }
|
|
57
|
+
#main .rr-player .rr-progress { background: #3f3f46; border-color: #18181b; }
|
|
58
|
+
#main .rr-player .rr-progress__step { background: color-mix(in srgb, var(--accent) 45%, transparent); }
|
|
59
|
+
#main .rr-player .rr-progress__handler { background: var(--accent); }
|
|
60
|
+
#main .rr-player .rr-controller__btns button { color: #e4e4e7; }
|
|
61
|
+
#main .rr-player .rr-controller__btns button:disabled { color: #52525b; }
|
|
62
|
+
#main .rr-player .rr-controller__btns button svg { fill: currentColor; }
|
|
63
|
+
#main .rr-player .rr-controller__btns button.active { color: #04130b; background: var(--accent); }
|
|
64
|
+
#main .rr-player .rr-controller__btns button:active { background: color-mix(in srgb, var(--accent) 60%, transparent); }
|
|
65
|
+
#main .rr-player .switch .label { color: #e4e4e7; }
|
|
66
|
+
#main .rr-player .switch.disabled .label { color: #52525b; }
|
|
67
|
+
#main .rr-player .switch label:before { background: #52525b; }
|
|
68
|
+
#main .rr-player .switch input:checked + label:before { background: var(--accent); }
|
|
69
|
+
</style>
|
|
70
|
+
<header>
|
|
71
|
+
<strong>Recording</strong>
|
|
72
|
+
<a id="page" target="_blank" rel="noreferrer"></a>
|
|
73
|
+
</header>
|
|
74
|
+
<main id="main"></main>
|
|
75
|
+
<script src="${player}/player.js"><\/script>${source === void 0 ? "" : `
|
|
76
|
+
<script src="${source}"><\/script>`}
|
|
77
|
+
<script>
|
|
78
|
+
const params = new URLSearchParams(location.search);
|
|
79
|
+
const bare = params.has('bare');
|
|
80
|
+
const embed = params.has('embed');
|
|
81
|
+
if (bare) document.body.classList.add('bare');
|
|
82
|
+
if (embed) document.body.classList.add('embed');
|
|
83
|
+
const id = params.get('id') ?? location.pathname.split('/').at(-1);
|
|
84
|
+
// The plugin's routes, unless the page was given a source of its own (\`replayPage\`).
|
|
85
|
+
const from = globalThis.deicticReplay ?? {
|
|
86
|
+
recording: (id) => fetch('../recording/' + id).then((r) => (r.ok ? r.json() : r.text().then((t) => Promise.reject(new Error(t))))),
|
|
87
|
+
clip: (id) => '../../voice/clip/' + id,
|
|
88
|
+
};
|
|
89
|
+
Promise.resolve(from.recording(id)).then(async (kept) => {
|
|
90
|
+
const scheme = kept.colorScheme ?? 'light';
|
|
91
|
+
const events = JSON.parse(
|
|
92
|
+
JSON.stringify(kept.events).replace(/\\(\\s*prefers-color-scheme\\s*:\\s*(light|dark)\\s*\\)/g, (_, s) =>
|
|
93
|
+
s === scheme ? '(min-width: 0px)' : '(max-width: 0px) and (min-width: 1px)',
|
|
94
|
+
),
|
|
95
|
+
);
|
|
96
|
+
page.textContent = kept.page;
|
|
97
|
+
page.href = kept.page;
|
|
98
|
+
|
|
99
|
+
// A recording with the mic starts paused: a browser plays sound only after a click, which Play is.
|
|
100
|
+
const clips = await Promise.all((kept.voice ?? []).map(async (c) => ({ ...c, audio: Object.assign(new Audio(await from.clip(c.id)), { preload: 'auto' }) })));
|
|
101
|
+
const t = Number.parseFloat(params.get('t') ?? '');
|
|
102
|
+
// The player's frame, at most the window's room, the controls (80px) under it; 1:1 when bare.
|
|
103
|
+
const size = () => bare
|
|
104
|
+
? { width: kept.viewport.width, height: kept.viewport.height }
|
|
105
|
+
: embed
|
|
106
|
+
? { width: innerWidth, height: innerHeight - 80 }
|
|
107
|
+
: { width: Math.min(kept.viewport.width, innerWidth - 32), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };
|
|
108
|
+
const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;
|
|
109
|
+
const player = new Player({
|
|
110
|
+
target: main,
|
|
111
|
+
props: {
|
|
112
|
+
events,
|
|
113
|
+
...size(),
|
|
114
|
+
autoPlay: !Number.isFinite(t) && clips.length === 0,
|
|
115
|
+
showController: !bare,
|
|
116
|
+
speedOption: [1, 2, 4, 8],
|
|
117
|
+
tags: { ${JSON.stringify(MARKS)}: '#12b358' },
|
|
118
|
+
inactiveColor: '#3f3f46',
|
|
119
|
+
mouseTail: false,
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });
|
|
123
|
+
const replayer = player.getReplayer();
|
|
124
|
+
const total = player.getMetaData().totalTime;
|
|
125
|
+
|
|
126
|
+
// The marks as they were at this point: the latest custom event's, in the player's scaled wrapper, moved with the replay's scroll.
|
|
127
|
+
const marks = Object.assign(document.createElement('div'), { id: 'marks' });
|
|
128
|
+
replayer.wrapper.append(marks);
|
|
129
|
+
replayer.on('custom-event', (e) => { if (e.data.tag === ${JSON.stringify(MARKS)}) marks.innerHTML = e.data.payload.svg; });
|
|
130
|
+
|
|
131
|
+
let playing = false;
|
|
132
|
+
player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });
|
|
133
|
+
const follow = () => {
|
|
134
|
+
const win = replayer.iframe.contentWindow;
|
|
135
|
+
if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';
|
|
136
|
+
const now = Math.min(replayer.getCurrentTime(), total);
|
|
137
|
+
const speed = replayer.config.speed ?? 1;
|
|
138
|
+
// Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.
|
|
139
|
+
for (const c of clips) {
|
|
140
|
+
const into = now - c.at;
|
|
141
|
+
if (!playing || into < 0 || into >= c.duration) { if (!c.audio.paused) c.audio.pause(); continue; }
|
|
142
|
+
if (c.audio.playbackRate !== speed) c.audio.playbackRate = speed;
|
|
143
|
+
if (Math.abs(c.audio.currentTime * 1000 - into) > 250 * speed) c.audio.currentTime = into / 1000;
|
|
144
|
+
if (c.audio.paused) c.audio.play().catch(() => {});
|
|
145
|
+
}
|
|
146
|
+
requestAnimationFrame(follow);
|
|
147
|
+
};
|
|
148
|
+
follow();
|
|
149
|
+
|
|
150
|
+
if (Number.isFinite(t)) player.goto(Math.min(Math.max(0, t * 1000), total), false);
|
|
151
|
+
document.body.dataset.ready = '';
|
|
152
|
+
}).catch((e) => { document.querySelector('main').innerHTML = '<p class="problem"></p>'; document.querySelector('.problem').textContent = e.message; });
|
|
153
|
+
<\/script>
|
|
154
|
+
</html>
|
|
155
|
+
`;
|
|
156
|
+
// src/plugins/recordings/index.ts
|
|
157
|
+
/**
|
|
158
|
+
* `deictic/recordings`: records the page with rrweb, for other plugins to attach (tasks does). No tab of
|
|
159
|
+
* its own: `use('recordings').record()` shows a toolbar on the page (drag it to any edge) with annotate
|
|
160
|
+
* mode's tools, where that plugin is loaded, a mic where the voice plugin is, and Stop and Discard. What's drawn while recording is in the
|
|
161
|
+
* recording too, as custom events the replay draws.
|
|
162
|
+
*
|
|
163
|
+
* Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's
|
|
164
|
+
* events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.
|
|
165
|
+
*/
|
|
166
|
+
const ID = /^[a-z0-9]+-[a-z0-9]+$/;
|
|
167
|
+
/** What one recording may weigh: minutes of a busy page are a few MB. */
|
|
168
|
+
const MAX = 52428800;
|
|
169
|
+
/** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */
|
|
170
|
+
const player = (file) => {
|
|
171
|
+
try {
|
|
172
|
+
return join(dirname(createRequire(import.meta.url).resolve("rrweb-player")), file);
|
|
173
|
+
} catch {
|
|
174
|
+
return "";
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
function recordings(options = {}) {
|
|
178
|
+
const keep = options.keep ?? 20;
|
|
179
|
+
let dir = "";
|
|
180
|
+
let taken = 0;
|
|
181
|
+
const pathOf = (id) => join(dir, `${id}.json`);
|
|
182
|
+
const read = (id) => {
|
|
183
|
+
if (!ID.test(id) || !existsSync(pathOf(id))) return void 0;
|
|
184
|
+
return {
|
|
185
|
+
data: new Uint8Array(readFileSync(pathOf(id))),
|
|
186
|
+
name: `recording-${id}.json`,
|
|
187
|
+
type: "application/json"
|
|
188
|
+
};
|
|
189
|
+
};
|
|
190
|
+
const keepRecording = (data) => {
|
|
191
|
+
const id = `${Date.now().toString(36).padStart(9, "0")}${(taken++ % 1296).toString(36).padStart(2, "0")}-${crypto.randomUUID().slice(0, 8)}`;
|
|
192
|
+
mkdirSync(dir, { recursive: true });
|
|
193
|
+
writeFileSync(pathOf(id), data);
|
|
194
|
+
const kept = readdirSync(dir).filter((f) => f.endsWith(".json")).toSorted();
|
|
195
|
+
for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
|
|
196
|
+
return id;
|
|
197
|
+
};
|
|
198
|
+
const file = (path, type) => {
|
|
199
|
+
if (!existsSync(path)) return new Response("rrweb-player is missing: add it to your devDependencies", { status: 404 });
|
|
200
|
+
return new Response(readFileSync(path), { headers: { "content-type": type } });
|
|
201
|
+
};
|
|
202
|
+
return definePlugin({
|
|
203
|
+
name: "recordings",
|
|
204
|
+
client: "deictic/recordings/client",
|
|
205
|
+
clientOptions: { masking: {
|
|
206
|
+
blockClass: options.blockClass ?? "rr-block",
|
|
207
|
+
blockSelector: options.blockSelector,
|
|
208
|
+
maskTextClass: options.maskTextClass ?? "rr-mask",
|
|
209
|
+
maskTextSelector: options.maskTextSelector,
|
|
210
|
+
maskAllInputs: options.maskAllInputs ?? false
|
|
211
|
+
} },
|
|
212
|
+
setup: ({ root }) => {
|
|
213
|
+
dir = options.dir === void 0 ? keptIn(root, "recordings") : resolve(root, options.dir);
|
|
214
|
+
return { read };
|
|
215
|
+
},
|
|
216
|
+
routes: {
|
|
217
|
+
add: async (req) => {
|
|
218
|
+
if (!(req.headers.get("content-type") ?? "").startsWith("application/json")) return Response.json({ problem: "send the recording as application/json" }, { status: 415 });
|
|
219
|
+
const body = new Uint8Array(await req.arrayBuffer());
|
|
220
|
+
if (body.byteLength > MAX) return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
|
|
221
|
+
let kept;
|
|
222
|
+
try {
|
|
223
|
+
kept = JSON.parse(new TextDecoder().decode(body));
|
|
224
|
+
} catch {
|
|
225
|
+
return Response.json({ problem: "the recording isn't JSON" }, { status: 400 });
|
|
226
|
+
}
|
|
227
|
+
if (!Array.isArray(kept.events) || kept.events.length === 0) return Response.json({ problem: "the recording has no events: record for a moment longer" }, { status: 400 });
|
|
228
|
+
return Response.json({ id: keepRecording(body) });
|
|
229
|
+
},
|
|
230
|
+
recording: (req) => {
|
|
231
|
+
const found = read(new URL(req.url).pathname.split("/").at(-1) ?? "");
|
|
232
|
+
if (found === void 0) return new Response("no such recording, or not kept any more", { status: 404 });
|
|
233
|
+
return new Response(found.data, { headers: {
|
|
234
|
+
"content-type": found.type,
|
|
235
|
+
"cache-control": "no-store"
|
|
236
|
+
} });
|
|
237
|
+
},
|
|
238
|
+
replay: () => new Response(replayPage(), { headers: { "content-type": "text/html; charset=utf-8" } }),
|
|
239
|
+
"player.js": () => file(player("rrweb-player.umd.min.cjs"), "text/javascript"),
|
|
240
|
+
"player.css": () => file(player("style.css"), "text/css")
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
export { replayPage as n, recordings as t };
|
|
245
|
+
|
|
246
|
+
//# sourceMappingURL=recordings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recordings.js","names":[],"sources":["../../src/plugins/recordings/replay.ts","../../src/plugins/recordings/index.ts"],"sourcesContent":["/**\n * The replay page, `replay/<id>`: rrweb's own player (`rrweb-player`), its timeline, speeds, skipping idle\n * stretches and fullscreen, sized to the window, with what it doesn't do drawn over it:\n *\n * - The page shows in the colour scheme it was recorded in, whatever the viewer's: the replay's iframe\n * answers `prefers-color-scheme` as the viewer's browser does, so the recorded CSS's queries are rewritten\n * before it's replayed, the recorded scheme's to always match and the other's never.\n * - The marks drawn while recording come as custom events, an SVG in page coordinates each; they're drawn\n * over the replay in the player's own scaled wrapper, moved with its scroll, rather than into its document,\n * which the replayer rebuilds. Each is a marker on the timeline.\n * - The voice clips play in step, at the player's speed. A recording with voice starts paused, as a browser\n * plays sound only after a click.\n *\n * `?t=<seconds>` opens it paused there, and `&bare` without the controls at the recorded size, 1:1, for a\n * screenshot; `?embed` is it filling a frame, with no header of its own (the lightbox's); `body[data-ready]` says\n * it's in place.\n *\n * The plugin's routes serve it, the player and what it plays. A page with no server behind it (a `standalone` build)\n * publishes it as a file instead, `replayPage(sources)`: which recording is `?id=`, and a script of its own says\n * where one is.\n */\nimport { MARKS } from './marks.ts';\n\n/** Where the replay page finds what the plugin's routes would serve it, for a page published as a file. */\nexport interface ReplaySources {\n /** The folder `player.js` and `player.css` are in (`rrweb-player`'s `rrweb-player.umd.min.cjs` and `style.css`), from the page: `..`, the routes', by default. */\n player?: string;\n /**\n * A script, from the page, that sets `globalThis.deicticReplay` before the page asks: `recording(id)` answers the\n * recording (a `Kept`) and `clip(id)` a voice clip's URL, either as a promise. The routes by default.\n */\n source?: string;\n}\n\n/** The replay page's HTML: the routes' as it is, or one for a page published as a file. */\nexport const replayPage = ({ player = '..', source }: ReplaySources = {}) => `<!doctype html>\n<html lang=\"en\">\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Recording · deictic</title>\n<link rel=\"stylesheet\" href=\"${player}/player.css\">\n<style>\n :root { color-scheme: dark; --accent: #12b358; }\n body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: #18181b; color: #fafafa; font: 13px/1.4 system-ui, sans-serif; }\n header { display: flex; gap: 10px; align-items: center; padding: 10px 16px; border-bottom: 1px solid #3f3f46; }\n header a { color: #a1a1aa; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n main { flex: 1; display: flex; justify-content: center; align-items: flex-start; padding: 16px; }\n body.bare header { display: none; }\n body.bare main { padding: 0; }\n body.embed header { display: none; }\n body.embed main { padding: 0; }\n body.embed #main .rr-player { box-shadow: none; border-radius: 0; }\n #marks { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 3; }\n #marks svg { position: absolute; left: 0; top: 0; overflow: visible; }\n .problem { color: #f87171; padding: 16px; }\n /* rrweb-player, in the dark of the rest of deictic. Its rules repeat Svelte's scoping class, so these start\n from #main, which outweighs any number of classes. */\n #main .rr-player { background: #27272a; box-shadow: 0 12px 32px rgb(0 0 0 / 0.5); border-radius: 8px; overflow: hidden; }\n body.bare #main .rr-player { box-shadow: none; border-radius: 0; }\n #main .rr-player .rr-player__frame { background: #fff; }\n #main .rr-player .rr-controller { background: #18181b; border-top: 1px solid #3f3f46; border-radius: 0; }\n #main .rr-player .rr-timeline__time { color: #a1a1aa; font: 12px ui-monospace, monospace; }\n #main .rr-player .rr-progress { background: #3f3f46; border-color: #18181b; }\n #main .rr-player .rr-progress__step { background: color-mix(in srgb, var(--accent) 45%, transparent); }\n #main .rr-player .rr-progress__handler { background: var(--accent); }\n #main .rr-player .rr-controller__btns button { color: #e4e4e7; }\n #main .rr-player .rr-controller__btns button:disabled { color: #52525b; }\n #main .rr-player .rr-controller__btns button svg { fill: currentColor; }\n #main .rr-player .rr-controller__btns button.active { color: #04130b; background: var(--accent); }\n #main .rr-player .rr-controller__btns button:active { background: color-mix(in srgb, var(--accent) 60%, transparent); }\n #main .rr-player .switch .label { color: #e4e4e7; }\n #main .rr-player .switch.disabled .label { color: #52525b; }\n #main .rr-player .switch label:before { background: #52525b; }\n #main .rr-player .switch input:checked + label:before { background: var(--accent); }\n</style>\n<header>\n <strong>Recording</strong>\n <a id=\"page\" target=\"_blank\" rel=\"noreferrer\"></a>\n</header>\n<main id=\"main\"></main>\n<script src=\"${player}/player.js\"></script>${\n source === undefined\n ? ''\n : `\n<script src=\"${source}\"></script>`\n}\n<script>\n const params = new URLSearchParams(location.search);\n const bare = params.has('bare');\n const embed = params.has('embed');\n if (bare) document.body.classList.add('bare');\n if (embed) document.body.classList.add('embed');\n const id = params.get('id') ?? location.pathname.split('/').at(-1);\n // The plugin's routes, unless the page was given a source of its own (\\`replayPage\\`).\n const from = globalThis.deicticReplay ?? {\n recording: (id) => fetch('../recording/' + id).then((r) => (r.ok ? r.json() : r.text().then((t) => Promise.reject(new Error(t))))),\n clip: (id) => '../../voice/clip/' + id,\n };\n Promise.resolve(from.recording(id)).then(async (kept) => {\n const scheme = kept.colorScheme ?? 'light';\n const events = JSON.parse(\n JSON.stringify(kept.events).replace(/\\\\(\\\\s*prefers-color-scheme\\\\s*:\\\\s*(light|dark)\\\\s*\\\\)/g, (_, s) =>\n s === scheme ? '(min-width: 0px)' : '(max-width: 0px) and (min-width: 1px)',\n ),\n );\n page.textContent = kept.page;\n page.href = kept.page;\n\n // A recording with the mic starts paused: a browser plays sound only after a click, which Play is.\n const clips = await Promise.all((kept.voice ?? []).map(async (c) => ({ ...c, audio: Object.assign(new Audio(await from.clip(c.id)), { preload: 'auto' }) })));\n const t = Number.parseFloat(params.get('t') ?? '');\n // The player's frame, at most the window's room, the controls (80px) under it; 1:1 when bare.\n const size = () => bare\n ? { width: kept.viewport.width, height: kept.viewport.height }\n : embed\n ? { width: innerWidth, height: innerHeight - 80 }\n : { width: Math.min(kept.viewport.width, innerWidth - 32), height: Math.min(kept.viewport.height, innerHeight - 90 - 80 - 16) };\n const Player = rrwebPlayer.default ?? rrwebPlayer.Player ?? rrwebPlayer;\n const player = new Player({\n target: main,\n props: {\n events,\n ...size(),\n autoPlay: !Number.isFinite(t) && clips.length === 0,\n showController: !bare,\n speedOption: [1, 2, 4, 8],\n tags: { ${JSON.stringify(MARKS)}: '#12b358' },\n inactiveColor: '#3f3f46',\n mouseTail: false,\n },\n });\n addEventListener('resize', () => { player.$set(size()); player.triggerResize(); });\n const replayer = player.getReplayer();\n const total = player.getMetaData().totalTime;\n\n // The marks as they were at this point: the latest custom event's, in the player's scaled wrapper, moved with the replay's scroll.\n const marks = Object.assign(document.createElement('div'), { id: 'marks' });\n replayer.wrapper.append(marks);\n replayer.on('custom-event', (e) => { if (e.data.tag === ${JSON.stringify(MARKS)}) marks.innerHTML = e.data.payload.svg; });\n\n let playing = false;\n player.addEventListener('ui-update-player-state', (e) => { playing = e.payload === 'playing'; });\n const follow = () => {\n const win = replayer.iframe.contentWindow;\n if (win) marks.style.transform = 'translate(' + -win.scrollX + 'px,' + -win.scrollY + 'px)';\n const now = Math.min(replayer.getCurrentTime(), total);\n const speed = replayer.config.speed ?? 1;\n // Each clip plays while the replay is inside it, at its speed, kept within a few frames of the replay's time.\n for (const c of clips) {\n const into = now - c.at;\n if (!playing || into < 0 || into >= c.duration) { if (!c.audio.paused) c.audio.pause(); continue; }\n if (c.audio.playbackRate !== speed) c.audio.playbackRate = speed;\n if (Math.abs(c.audio.currentTime * 1000 - into) > 250 * speed) c.audio.currentTime = into / 1000;\n if (c.audio.paused) c.audio.play().catch(() => {});\n }\n requestAnimationFrame(follow);\n };\n follow();\n\n if (Number.isFinite(t)) player.goto(Math.min(Math.max(0, t * 1000), total), false);\n document.body.dataset.ready = '';\n }).catch((e) => { document.querySelector('main').innerHTML = '<p class=\"problem\"></p>'; document.querySelector('.problem').textContent = e.message; });\n</script>\n</html>\n`;\n","/**\n * `deictic/recordings`: records the page with rrweb, for other plugins to attach (tasks does). No tab of\n * its own: `use('recordings').record()` shows a toolbar on the page (drag it to any edge) with annotate\n * mode's tools, where that plugin is loaded, a mic where the voice plugin is, and Stop and Discard. What's drawn while recording is in the\n * recording too, as custom events the replay draws.\n *\n * Recordings are kept under `.deictic/recordings`, the latest `keep`, as JSON: rrweb's\n * events, with the page, its viewport and how long it ran. `replay/<id>` plays one back in the browser.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { definePlugin } from '#src/index.ts';\nimport type { Masking, ResolvedMasking } from '#src/plugins/screenshots/index.ts';\nimport { keptIn } from '#src/tools/kept.ts';\n\nimport { replayPage } from './replay.ts';\n\nexport { MARKS } from './marks.ts';\nexport { replayPage, type ReplaySources } from './replay.ts';\n\n/** A recording as the page knows it: its ID, where it plays back, and how long it ran, in milliseconds. */\nexport interface Recording {\n id: string;\n url: string;\n duration: number;\n /** What the mic took while it was on, where the voice plugin is loaded. */\n voice?: VoiceClip[];\n}\n\n/** A stretch of the mic in a recording: the voice plugin's clip, and when it starts in the recording, in milliseconds. */\nexport interface VoiceClip {\n id: string;\n at: number;\n duration: number;\n}\n\n/** The page's half, for other plugins' page halves. */\nexport interface Recorder {\n /**\n * Records the page, with the toolbar, until Stop: answers the recording, kept by the dev server, or\n * nothing when it's discarded. Rejects while another is going, or when it couldn't be kept.\n */\n record(): Promise<Recording | undefined>;\n /** Whether one is going. */\n recording(): boolean;\n}\n\n/** The server's half, for other plugins' server halves. */\nexport interface Recordings {\n /** A recording's JSON, or nothing for one not kept (any more). */\n read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'application/json' } | undefined;\n}\n\n/** What the page sends, and what's kept: rrweb's events and what they can't say. */\nexport interface Kept {\n page: string;\n viewport: { width: number; height: number };\n /**\n * The colour scheme the page was in, which rrweb doesn't record: the replay shows it in the same, or a\n * page styled by `prefers-color-scheme` would take the replay's.\n */\n colorScheme?: 'light' | 'dark';\n startedAt: number;\n duration: number;\n events: unknown[];\n /** The mic's clips, played along with the replay. */\n voice?: VoiceClip[];\n}\n\ndeclare module 'deictic' {\n interface ServerApis {\n recordings: Recordings;\n }\n interface ClientApis {\n recordings: Recorder;\n }\n}\n\nexport interface RecordingsOptions extends Masking {\n /** How many recordings to keep, the latest: 20 by default. */\n keep?: number;\n /** Where they're kept, from the project's root: `.deictic/recordings` by default. */\n dir?: string;\n}\n\nconst ID = /^[a-z0-9]+-[a-z0-9]+$/;\n/** What one recording may weigh: minutes of a busy page are a few MB. */\nconst MAX = 50 * 1024 * 1024;\n\n/** rrweb's player (`rrweb-player`), served to the replay page: its build for a script tag, and its styles. */\nconst player = (file: string) => {\n try {\n return join(dirname(createRequire(import.meta.url).resolve('rrweb-player')), file);\n } catch {\n // Not installed: `file` answers what to add.\n return '';\n }\n};\n\nexport function recordings(options: RecordingsOptions = {}) {\n const keep = options.keep ?? 20;\n let dir = '';\n let taken = 0;\n const pathOf = (id: string) => join(dir, `${id}.json`);\n const read: Recordings['read'] = (id) => {\n if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;\n return { data: new Uint8Array(readFileSync(pathOf(id))), name: `recording-${id}.json`, type: 'application/json' };\n };\n const keepRecording = (data: Uint8Array) => {\n // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.\n const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;\n mkdirSync(dir, { recursive: true });\n writeFileSync(pathOf(id), data);\n const kept = readdirSync(dir)\n .filter((f) => f.endsWith('.json'))\n .toSorted();\n for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));\n return id;\n };\n const file = (path: string, type: string) => {\n if (!existsSync(path)) return new Response('rrweb-player is missing: add it to your devDependencies', { status: 404 });\n return new Response(readFileSync(path), { headers: { 'content-type': type } });\n };\n\n return definePlugin<never, never, never, Recordings>({\n name: 'recordings',\n client: 'deictic/recordings/client',\n clientOptions: {\n masking: {\n blockClass: options.blockClass ?? 'rr-block',\n blockSelector: options.blockSelector,\n maskTextClass: options.maskTextClass ?? 'rr-mask',\n maskTextSelector: options.maskTextSelector,\n maskAllInputs: options.maskAllInputs ?? false,\n } satisfies ResolvedMasking,\n },\n setup: ({ root }) => {\n dir = options.dir === undefined ? keptIn(root, 'recordings') : resolve(root, options.dir);\n return { read };\n },\n routes: {\n // What the page recorded, as JSON.\n add: async (req) => {\n if (!(req.headers.get('content-type') ?? '').startsWith('application/json'))\n return Response.json({ problem: 'send the recording as application/json' }, { status: 415 });\n const body = new Uint8Array(await req.arrayBuffer());\n if (body.byteLength > MAX)\n return Response.json({ problem: `a recording may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });\n let kept: Partial<Kept>;\n try {\n kept = JSON.parse(new TextDecoder().decode(body)) as Partial<Kept>;\n } catch {\n return Response.json({ problem: \"the recording isn't JSON\" }, { status: 400 });\n }\n if (!Array.isArray(kept.events) || kept.events.length === 0)\n return Response.json({ problem: 'the recording has no events: record for a moment longer' }, { status: 400 });\n return Response.json({ id: keepRecording(body) });\n },\n // `recording/<id>`: the JSON, for the replay page.\n recording: (req) => {\n const found = read(new URL(req.url).pathname.split('/').at(-1) ?? '');\n if (found === undefined) return new Response('no such recording, or not kept any more', { status: 404 });\n return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });\n },\n // `replay/<id>`: a page that plays it back.\n replay: () => new Response(replayPage(), { headers: { 'content-type': 'text/html; charset=utf-8' } }),\n 'player.js': () => file(player('rrweb-player.umd.min.cjs'), 'text/javascript'),\n 'player.css': () => file(player('style.css'), 'text/css'),\n },\n });\n}\n\nexport default recordings;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAa,cAAc,EAAE,SAAS,MAAM,WAA0B,CAAC,MAAM;;;;;+BAK9C,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAwCvB,OAAO,wBACpB,WAAW,KAAA,IACP,KACA;eACS,OAAO,cACrB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAyCiB,KAAK,UAAU,KAAK,EAAE;;;;;;;;;;;;8DAYsB,KAAK,UAAU,KAAK,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACnDpF,MAAM,KAAK;;AAEX,MAAM,MAAM;;AAGZ,MAAM,UAAU,SAAiB;CAC/B,IAAI;EACF,OAAO,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC,CAAC,QAAQ,cAAc,CAAC,GAAG,IAAI;CACnF,QAAQ;EAEN,OAAO;CACT;AACF;AAEA,SAAgB,WAAW,UAA6B,CAAC,GAAG;CAC1D,MAAM,OAAO,QAAQ,QAAQ;CAC7B,IAAI,MAAM;CACV,IAAI,QAAQ;CACZ,MAAM,UAAU,OAAe,KAAK,KAAK,GAAG,GAAG,MAAM;CACrD,MAAM,QAA4B,OAAO;EACvC,IAAI,CAAC,GAAG,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ACpG,mBAAmB,KAAK,OAAO,0BAA0B,GAAG,iBAAiB;GAC7E,oBAAoB,KAAK,OAAO,WAAW,GAAG,UAAU;EAC1D;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// src/shortcut.ts
|
|
2
|
+
const FLAGS = {
|
|
3
|
+
Alt: "altKey",
|
|
4
|
+
Control: "ctrlKey",
|
|
5
|
+
Meta: "metaKey",
|
|
6
|
+
Shift: "shiftKey"
|
|
7
|
+
};
|
|
8
|
+
const BUTTONS = {
|
|
9
|
+
left: 0,
|
|
10
|
+
middle: 1,
|
|
11
|
+
right: 2
|
|
12
|
+
};
|
|
13
|
+
/** deictic's own shortcut, unless `deictic({ shortcut })` names another or `false`. */
|
|
14
|
+
const MASTER = {
|
|
15
|
+
modifiers: ["Alt"],
|
|
16
|
+
button: "left"
|
|
17
|
+
};
|
|
18
|
+
/** The name deictic's own shortcut goes by in a problem. */
|
|
19
|
+
const OWN = "deictic";
|
|
20
|
+
/** deictic's own shortcut as given, with its default, before it's checked. */
|
|
21
|
+
const ownShortcut = (given) => given === false ? void 0 : given ?? MASTER;
|
|
22
|
+
/** The shortcut with its button's default and its modifiers in one order, or an error saying what to write instead. */
|
|
23
|
+
function checkShortcut(plugin, shortcut) {
|
|
24
|
+
const { modifiers = [], button = "left" } = shortcut;
|
|
25
|
+
const named = Object.keys(FLAGS).join("', '");
|
|
26
|
+
if (!Array.isArray(modifiers) || modifiers.length === 0) throw new Error(`deictic: ${plugin}'s shortcut.modifiers is empty: hold at least one of '${named}', or every click would open the popup`);
|
|
27
|
+
for (const m of modifiers) if (!Object.hasOwn(FLAGS, m)) throw new Error(`deictic: ${plugin}'s shortcut.modifiers has '${m}': name one of '${named}'`);
|
|
28
|
+
if (!Object.hasOwn(BUTTONS, button)) throw new Error(`deictic: ${plugin}'s shortcut.button is '${button}': name one of '${Object.keys(BUTTONS).join("', '")}'`);
|
|
29
|
+
const order = Object.keys(FLAGS);
|
|
30
|
+
return {
|
|
31
|
+
modifiers: [...new Set(modifiers)].toSorted((a, b) => order.indexOf(a) - order.indexOf(b)),
|
|
32
|
+
button
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Each shortcut checked, in order, or nothing where there's none: none may be another's, or only the
|
|
37
|
+
* first would ever open. deictic's own goes first, named `OWN`.
|
|
38
|
+
*/
|
|
39
|
+
function checkShortcuts(plugins) {
|
|
40
|
+
const taken = /* @__PURE__ */ new Map();
|
|
41
|
+
return plugins.map(({ name, shortcut }) => {
|
|
42
|
+
if (shortcut === void 0) return void 0;
|
|
43
|
+
const checked = checkShortcut(name, shortcut);
|
|
44
|
+
const key = nameOf(checked);
|
|
45
|
+
const other = taken.get(key);
|
|
46
|
+
if (other !== void 0) throw new Error(`deictic: ${name} and ${other} both open on ${key}: give one of them another \`shortcut\``);
|
|
47
|
+
taken.set(key, name);
|
|
48
|
+
return checked;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/** How a shortcut reads, for a problem or a label: `Alt+Shift`, `Control+right-click`. */
|
|
52
|
+
const nameOf = ({ modifiers = [], button = "left" }) => [...modifiers, ...button === "left" ? [] : [`${button}-click`]].join("+");
|
|
53
|
+
function gestureOf(shortcut) {
|
|
54
|
+
const on = new Set(shortcut.modifiers);
|
|
55
|
+
const flags = Object.entries(FLAGS);
|
|
56
|
+
return {
|
|
57
|
+
held: (e) => flags.every(([key, flag]) => e[flag] === on.has(key)),
|
|
58
|
+
button: BUTTONS[shortcut.button]
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export { ownShortcut as i, checkShortcuts as n, gestureOf as r, OWN as t };
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=shortcut.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shortcut.js","names":[],"sources":["../../src/shortcut.ts"],"sourcesContent":["/**\n * A gesture: the keys held to outline the element under the pointer, and the button that, with them\n * held, opens the popup there. deictic's own (`MASTER` by default) opens the tab used last; a\n * plugin's, which it takes as its `shortcut` option and has none by default, opens its tab. The\n * bundler's plugin checks them all as it starts, so a wrong one, or two alike, fails the dev server,\n * not the page. Both halves import it: it must\n * stay dependency-free.\n */\n\n/** A modifier key, as `KeyboardEvent.key` names it. */\nexport type Modifier = 'Alt' | 'Control' | 'Meta' | 'Shift';\n\nexport interface Shortcut {\n /** Held, and no other, to outline elements. */\n modifiers?: Modifier[];\n /** Pressed with them to open the panel. `'left'` unset. */\n button?: 'left' | 'middle' | 'right';\n}\n\nconst FLAGS = { Alt: 'altKey', Control: 'ctrlKey', Meta: 'metaKey', Shift: 'shiftKey' } as const;\nconst BUTTONS = { left: 0, middle: 1, right: 2 } as const;\n\n/** deictic's own shortcut, unless `deictic({ shortcut })` names another or `false`. */\nexport const MASTER: Required<Shortcut> = { modifiers: ['Alt'], button: 'left' };\n\n/** The name deictic's own shortcut goes by in a problem. */\nexport const OWN = 'deictic';\n\n/** deictic's own shortcut as given, with its default, before it's checked. */\nexport const ownShortcut = (given: Shortcut | false | undefined) => (given === false ? undefined : (given ?? MASTER));\n\n/** The shortcut with its button's default and its modifiers in one order, or an error saying what to write instead. */\nexport function checkShortcut(plugin: string, shortcut: Shortcut): Required<Shortcut> {\n const { modifiers = [], button = 'left' } = shortcut;\n const named = Object.keys(FLAGS).join(\"', '\");\n if (!Array.isArray(modifiers) || modifiers.length === 0) {\n throw new Error(\n `deictic: ${plugin}'s shortcut.modifiers is empty: hold at least one of '${named}', or every click would open the popup`,\n );\n }\n for (const m of modifiers)\n if (!Object.hasOwn(FLAGS, m)) throw new Error(`deictic: ${plugin}'s shortcut.modifiers has '${m}': name one of '${named}'`);\n\n if (!Object.hasOwn(BUTTONS, button))\n throw new Error(`deictic: ${plugin}'s shortcut.button is '${button}': name one of '${Object.keys(BUTTONS).join(\"', '\")}'`);\n\n const order = Object.keys(FLAGS);\n return { modifiers: [...new Set(modifiers)].toSorted((a, b) => order.indexOf(a) - order.indexOf(b)), button };\n}\n\n/**\n * Each shortcut checked, in order, or nothing where there's none: none may be another's, or only the\n * first would ever open. deictic's own goes first, named `OWN`.\n */\nexport function checkShortcuts(plugins: readonly { name: string; shortcut?: Shortcut }[]): (Required<Shortcut> | undefined)[] {\n const taken = new Map<string, string>();\n return plugins.map(({ name, shortcut }) => {\n if (shortcut === undefined) return undefined;\n const checked = checkShortcut(name, shortcut);\n const key = nameOf(checked);\n const other = taken.get(key);\n if (other !== undefined) throw new Error(`deictic: ${name} and ${other} both open on ${key}: give one of them another \\`shortcut\\``);\n taken.set(key, name);\n return checked;\n });\n}\n\n/** How a shortcut reads, for a problem or a label: `Alt+Shift`, `Control+right-click`. */\nexport const nameOf = ({ modifiers = [], button = 'left' }: Shortcut) =>\n [...modifiers, ...(button === 'left' ? [] : [`${button}-click`])].join('+');\n\nexport interface Gesture {\n /** Whether exactly the shortcut's modifiers are down: AltGr, which is Control and Alt, isn't Alt. */\n held: (e: MouseEvent | KeyboardEvent) => boolean;\n /** The shortcut's button, as `MouseEvent.button` numbers it. */\n button: number;\n}\n\nexport function gestureOf(shortcut: Required<Shortcut>): Gesture {\n const on = new Set<string>(shortcut.modifiers);\n const flags = Object.entries(FLAGS);\n return { held: (e) => flags.every(([key, flag]) => e[flag] === on.has(key)), button: BUTTONS[shortcut.button] };\n}\n"],"mappings":";AAmBA,MAAM,QAAQ;CAAE,KAAK;CAAU,SAAS;CAAW,MAAM;CAAW,OAAO;AAAW;AACtF,MAAM,UAAU;CAAE,MAAM;CAAG,QAAQ;CAAG,OAAO;AAAE;;AAG/C,MAAa,SAA6B;CAAE,WAAW,CAAC,KAAK;CAAG,QAAQ;AAAO;;AAG/E,MAAa,MAAM;;AAGnB,MAAa,eAAe,UAAyC,UAAU,QAAQ,KAAA,IAAa,SAAS;;AAG7G,SAAgB,cAAc,QAAgB,UAAwC;CACpF,MAAM,EAAE,YAAY,CAAC,GAAG,SAAS,WAAW;CAC5C,MAAM,QAAQ,OAAO,KAAK,KAAK,CAAC,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