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.
- package/API.md +31 -19
- package/README.md +6 -26
- package/dist/annotations/client.d.ts +1 -1
- package/dist/annotations/client.js +1 -1
- package/dist/annotations/index.d.ts +2 -101
- package/dist/annotations/index.js +1 -22
- package/dist/astro.d.ts +1 -1
- package/dist/astro.js +1 -1
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +37 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.js +1 -10
- package/dist/logs/client.d.ts +1 -1
- package/dist/logs/client.js +1 -1
- package/dist/logs/index.d.ts +2 -18
- package/dist/logs/index.js +1 -21
- package/dist/network/client.d.ts +1 -1
- package/dist/network/client.js +1 -1
- package/dist/network/index.d.ts +1 -1
- package/dist/network/index.js +1 -37
- package/dist/recommended/index.d.ts +7 -7
- package/dist/recommended/index.js +1 -26
- package/dist/recordings/client.d.ts +1 -1
- package/dist/recordings/client.js +1 -1
- package/dist/recordings/index.d.ts +1 -1
- package/dist/screenshots/client.d.ts +1 -1
- package/dist/screenshots/client.js +1 -108
- package/dist/screenshots/dom.d.ts +1 -1
- package/dist/screenshots/dom.js +1 -1
- package/dist/screenshots/index.d.ts +1 -1
- package/dist/screenshots/index.js +1 -98
- package/dist/screenshots/rrweb.d.ts +2 -1
- package/dist/screenshots/rrweb.d.ts.map +1 -1
- package/dist/screenshots/rrweb.js +6 -2
- package/dist/screenshots/rrweb.js.map +1 -1
- package/dist/shared/annotations.js +22 -0
- package/dist/shared/annotations.js.map +1 -0
- package/dist/shared/board.js +190 -0
- package/dist/shared/board.js.map +1 -0
- package/dist/shared/client.js +108 -0
- package/dist/{screenshots → shared}/client.js.map +1 -1
- package/dist/shared/endpoints.js +4 -1
- package/dist/shared/endpoints.js.map +1 -1
- package/dist/shared/find.js +156 -0
- package/dist/shared/find.js.map +1 -0
- package/dist/shared/frame.js +75 -0
- package/dist/shared/frame.js.map +1 -0
- package/dist/shared/index.d.ts +5 -0
- package/dist/shared/index.d.ts.map +1 -1
- package/dist/shared/index2.d.ts +85 -84
- package/dist/shared/index2.d.ts.map +1 -1
- package/dist/shared/index3.d.ts +83 -89
- package/dist/shared/index3.d.ts.map +1 -1
- package/dist/shared/index4.d.ts +98 -50
- package/dist/shared/index4.d.ts.map +1 -1
- package/dist/shared/index5.d.ts +13 -215
- package/dist/shared/index5.d.ts.map +1 -1
- package/dist/shared/index6.d.ts +55 -61
- package/dist/shared/index6.d.ts.map +1 -1
- package/dist/shared/index7.d.ts +224 -0
- package/dist/shared/index7.d.ts.map +1 -0
- package/dist/shared/index8.d.ts +52 -0
- package/dist/shared/index8.d.ts.map +1 -0
- package/dist/shared/index9.d.ts +70 -0
- package/dist/shared/index9.d.ts.map +1 -0
- package/dist/shared/init.js +472 -0
- package/dist/shared/init.js.map +1 -0
- package/dist/shared/local.js +165 -0
- package/dist/shared/local.js.map +1 -0
- package/dist/shared/logs.js +22 -0
- package/dist/shared/logs.js.map +1 -0
- package/dist/shared/network.js +39 -0
- package/dist/shared/network.js.map +1 -0
- package/dist/shared/packages.js +125 -0
- package/dist/shared/packages.js.map +1 -0
- package/dist/shared/playwright.js +36 -9
- package/dist/shared/playwright.js.map +1 -1
- package/dist/shared/recommended.js +26 -0
- package/dist/shared/recommended.js.map +1 -0
- package/dist/shared/recording.js +316 -0
- package/dist/shared/recording.js.map +1 -0
- package/dist/shared/recordings.js +2 -1
- package/dist/shared/recordings.js.map +1 -1
- package/dist/shared/screenshots.js +108 -0
- package/dist/shared/screenshots.js.map +1 -0
- package/dist/shared/src.js +10 -0
- package/dist/shared/src.js.map +1 -0
- package/dist/shared/task.js +108 -0
- package/dist/shared/task.js.map +1 -0
- package/dist/shared/tasks.js +33 -191
- package/dist/shared/tasks.js.map +1 -1
- package/dist/shared/transcribe.js +128 -0
- package/dist/shared/transcribe.js.map +1 -0
- package/dist/shared/vb.js +13 -0
- package/dist/shared/vb.js.map +1 -0
- package/dist/shared/vite.d.ts +16 -0
- package/dist/shared/vite.d.ts.map +1 -0
- package/dist/shared/vite.js +61 -0
- package/dist/shared/vite.js.map +1 -0
- package/dist/shared/voice.js +84 -0
- package/dist/{voice/index.js.map → shared/voice.js.map} +1 -1
- package/dist/shared/voice2.js +90 -0
- package/dist/shared/voice2.js.map +1 -0
- package/dist/shared/watch.js +209 -0
- package/dist/shared/watch.js.map +1 -0
- package/dist/shared/watchers.js +62 -0
- package/dist/shared/watchers.js.map +1 -0
- package/dist/tailwind/client.d.ts +1 -1
- package/dist/tailwind/client.js +1 -1
- package/dist/tailwind/index.d.ts +1 -1
- package/dist/tailwind/index.js +1 -1
- package/dist/tasks/client.d.ts +1 -1
- package/dist/tasks/client.d.ts.map +1 -1
- package/dist/tasks/client.js +45 -8
- package/dist/tasks/client.js.map +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +3 -1
- package/dist/vite.d.ts +2 -15
- package/dist/vite.js +2 -60
- package/dist/voice/client.d.ts +1 -1
- package/dist/voice/client.js +1 -1
- package/dist/voice/index.d.ts +2 -52
- package/dist/voice/index.js +1 -84
- package/package.json +6 -9
- package/skills/deictic/SKILL.md +27 -42
- package/skills/deictic/references/recordings.md +9 -108
- package/skills/deictic/references/tasks.md +21 -107
- package/skills/deictic/references/watch.md +13 -66
- package/src/cli/board.ts +204 -0
- package/src/cli/bun.ts +133 -0
- package/src/cli/edit.ts +56 -0
- package/src/cli/find.ts +147 -0
- package/src/cli/frame.ts +90 -0
- package/src/cli/init.ts +388 -0
- package/src/cli/recording.ts +383 -0
- package/src/cli/task.ts +126 -0
- package/src/cli/transcribe.ts +129 -0
- package/src/cli/vb.ts +11 -0
- package/src/cli/voice.ts +59 -0
- package/src/cli/watch.ts +221 -0
- package/src/cli.ts +37 -0
- package/src/index.ts +5 -0
- package/src/plugins/logs/index.ts +1 -0
- package/src/plugins/network/index.ts +1 -0
- package/src/plugins/recordings/index.ts +1 -0
- package/src/plugins/screenshots/client.ts +3 -2
- package/src/plugins/screenshots/index.ts +10 -3
- package/src/plugins/screenshots/playwright.ts +34 -7
- package/src/plugins/screenshots/rrweb.ts +5 -1
- package/src/plugins/tasks/client.ts +62 -7
- package/src/plugins/tasks/index.ts +41 -20
- package/src/plugins/tasks/local.ts +19 -6
- package/src/plugins/tasks/watchers.ts +41 -6
- package/src/tools/endpoints.ts +3 -0
- package/src/tools/packages.ts +107 -0
- package/dist/annotations/index.d.ts.map +0 -1
- package/dist/annotations/index.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/logs/index.d.ts.map +0 -1
- package/dist/logs/index.js.map +0 -1
- package/dist/network/index.js.map +0 -1
- package/dist/recommended/index.js.map +0 -1
- package/dist/screenshots/index.js.map +0 -1
- package/dist/vite.d.ts.map +0 -1
- package/dist/vite.js.map +0 -1
- package/dist/voice/index.d.ts.map +0 -1
- package/skills/deictic/references/install.md +0 -103
- package/skills/deictic/scripts/frame.mjs +0 -62
- package/skills/deictic/scripts/lib.mjs +0 -277
- package/skills/deictic/scripts/recording.mjs +0 -266
- package/skills/deictic/scripts/task.mjs +0 -113
- package/skills/deictic/scripts/transcribe.mjs +0 -93
- package/skills/deictic/scripts/vb.mjs +0 -12
- package/skills/deictic/scripts/voice.mjs +0 -50
- package/skills/deictic/scripts/watch.mjs +0 -115
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { n as defineClientPlugin } from "./src.js";
|
|
2
|
+
// src/plugins/screenshots/client.ts
|
|
3
|
+
/**
|
|
4
|
+
* The screenshots plugin's page half, around a renderer's capture: the renderer makes the shot (a PNG,
|
|
5
|
+
* or what its server half makes one of), and this sends it to the plugin's `add` route and answers the
|
|
6
|
+
* `Shot`. A renderer's page module default-exports `screenshotsClient(itsCapture)`.
|
|
7
|
+
*/
|
|
8
|
+
/** Leaves out deictic's own UI: the overlay with its hover outline and any open panel. */
|
|
9
|
+
const notOurs = (node) => !(node instanceof Element && node.localName === "deictic-overlay");
|
|
10
|
+
/** The element's box, in CSS pixels from the viewport's top left, or from its own for a shot of it alone. */
|
|
11
|
+
function boxOf(element, area) {
|
|
12
|
+
const { x, y, width, height } = element.getBoundingClientRect();
|
|
13
|
+
return area === "element" ? {
|
|
14
|
+
x: 0,
|
|
15
|
+
y: 0,
|
|
16
|
+
width,
|
|
17
|
+
height
|
|
18
|
+
} : {
|
|
19
|
+
x,
|
|
20
|
+
y,
|
|
21
|
+
width,
|
|
22
|
+
height
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
const BLANK = "#d4d4d8";
|
|
26
|
+
const selector = (className, extra) => [`.${CSS.escape(className)}`, ...extra ? [extra] : []].join(", ");
|
|
27
|
+
/**
|
|
28
|
+
* Hides in a copy of the page's what rrweb would: blocked elements become a blank box their size (the copy keeps each
|
|
29
|
+
* element's size as its styles), masked text keeps its spaces but shows `*`, and so do passwords' values,
|
|
30
|
+
* or every field's.
|
|
31
|
+
*/
|
|
32
|
+
function mask(copy, m) {
|
|
33
|
+
if (!(copy instanceof Element)) return;
|
|
34
|
+
const all = (sel) => [...copy.matches(sel) ? [copy] : [], ...copy.querySelectorAll(sel)];
|
|
35
|
+
const stars = (text) => text.replace(/\S/g, "*");
|
|
36
|
+
for (const el of all(selector(m.blockClass, m.blockSelector))) {
|
|
37
|
+
el.replaceChildren();
|
|
38
|
+
if (el instanceof HTMLElement || el instanceof SVGElement) el.style.background = BLANK;
|
|
39
|
+
}
|
|
40
|
+
for (const el of all(selector(m.maskTextClass, m.maskTextSelector))) {
|
|
41
|
+
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
|
|
42
|
+
for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) text.textContent = stars(text.textContent ?? "");
|
|
43
|
+
}
|
|
44
|
+
for (const field of all("input, textarea")) {
|
|
45
|
+
if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) continue;
|
|
46
|
+
if (!m.maskAllInputs && !(field instanceof HTMLInputElement && field.type === "password")) continue;
|
|
47
|
+
field.value = stars(field.value);
|
|
48
|
+
field.setAttribute("value", field.value);
|
|
49
|
+
if (field instanceof HTMLTextAreaElement) field.textContent = field.value;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function screenshotsClient(capture) {
|
|
53
|
+
return defineClientPlugin({
|
|
54
|
+
name: "screenshots",
|
|
55
|
+
setup: ({ base, request, options, use }) => {
|
|
56
|
+
const { masking, renderer } = options;
|
|
57
|
+
const overlay = (area) => {
|
|
58
|
+
return use("annotations")?.svg(area);
|
|
59
|
+
};
|
|
60
|
+
const add = async (body, type, { box, size }) => {
|
|
61
|
+
const res = await request("add", {
|
|
62
|
+
method: "POST",
|
|
63
|
+
headers: { "content-type": type },
|
|
64
|
+
body
|
|
65
|
+
});
|
|
66
|
+
const { id, url, problem, box: drawn } = await res.json();
|
|
67
|
+
if (id === void 0) throw new Error(`screenshots: ${problem ?? res.statusText}`);
|
|
68
|
+
return {
|
|
69
|
+
id,
|
|
70
|
+
url: url ?? `${base}__deictic/plugins/screenshots/shot/${id}`,
|
|
71
|
+
box: drawn ?? box,
|
|
72
|
+
size
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
capture: async (element, { area = "viewport" } = {}) => {
|
|
77
|
+
const { body, type, box } = await capture(element, {
|
|
78
|
+
area,
|
|
79
|
+
masking,
|
|
80
|
+
renderer,
|
|
81
|
+
overlay
|
|
82
|
+
});
|
|
83
|
+
const { clientWidth, clientHeight } = document.documentElement;
|
|
84
|
+
const size = area === "element" ? {
|
|
85
|
+
width: box.width,
|
|
86
|
+
height: box.height
|
|
87
|
+
} : {
|
|
88
|
+
width: clientWidth,
|
|
89
|
+
height: clientHeight
|
|
90
|
+
};
|
|
91
|
+
return add(body, type, {
|
|
92
|
+
box,
|
|
93
|
+
size
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
upload: (png, of) => add(png, "image/png", of),
|
|
97
|
+
masked: (element) => {
|
|
98
|
+
const copy = element.cloneNode(true);
|
|
99
|
+
mask(copy, masking);
|
|
100
|
+
return copy;
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
export { screenshotsClient as i, mask as n, notOurs as r, boxOf as t };
|
|
107
|
+
|
|
108
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../src/plugins/screenshots/client.ts"],"sourcesContent":["/**\n * The screenshots plugin's page half, around a renderer's capture: the renderer makes the shot (a PNG,\n * or what its server half makes one of), and this sends it to the plugin's `add` route and answers the\n * `Shot`. A renderer's page module default-exports `screenshotsClient(itsCapture)`.\n */\nimport { defineClientPlugin } from '#src/index.ts';\nimport type { Annotations } from '#src/plugins/annotations/index.ts';\n\nimport type { Box, Capture, CaptureOptions, ResolvedMasking, Shot } from './index.ts';\n\n/**\n * What a renderer's page half makes of the element: a body for `add`, its type, and where the element is\n * in the shot. `overlay(area)` is what's drawn over the page in that part of the viewport, in viewport CSS\n * pixels, as an SVG that size, or nothing: the annotations plugin's marks, where it's loaded. The renderer\n * draws it over the shot, as deictic's own layers are left out.\n */\nexport type PageCapture = (\n element: Element,\n options: {\n area: NonNullable<CaptureOptions['area']>;\n masking: ResolvedMasking;\n renderer: unknown;\n overlay: (area: Box) => string | undefined;\n },\n) => Promise<{ body: Blob | string; type: string; box: Box }>;\n\n/** Leaves out deictic's own UI: the overlay with its hover outline and any open panel. */\nexport const notOurs = (node: Node) => !(node instanceof Element && node.localName === 'deictic-overlay');\n\n/** The element's box, in CSS pixels from the viewport's top left, or from its own for a shot of it alone. */\nexport function boxOf(element: Element, area: NonNullable<CaptureOptions['area']>): Box {\n const { x, y, width, height } = element.getBoundingClientRect();\n return area === 'element' ? { x: 0, y: 0, width, height } : { x, y, width, height };\n}\n\nconst BLANK = '#d4d4d8';\n\nconst selector = (className: string, extra: string | undefined) => [`.${CSS.escape(className)}`, ...(extra ? [extra] : [])].join(', ');\n\n/**\n * Hides in a copy of the page's what rrweb would: blocked elements become a blank box their size (the copy keeps each\n * element's size as its styles), masked text keeps its spaces but shows `*`, and so do passwords' values,\n * or every field's.\n */\nexport function mask(copy: Node, m: ResolvedMasking): void {\n if (!(copy instanceof Element)) return;\n const all = (sel: string) => [...(copy.matches(sel) ? [copy] : []), ...copy.querySelectorAll(sel)];\n const stars = (text: string) => text.replace(/\\S/g, '*');\n for (const el of all(selector(m.blockClass, m.blockSelector))) {\n el.replaceChildren();\n if (el instanceof HTMLElement || el instanceof SVGElement) el.style.background = BLANK;\n }\n for (const el of all(selector(m.maskTextClass, m.maskTextSelector))) {\n const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);\n for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) text.textContent = stars(text.textContent ?? '');\n }\n for (const field of all('input, textarea')) {\n if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) continue;\n if (!m.maskAllInputs && !(field instanceof HTMLInputElement && field.type === 'password')) continue;\n field.value = stars(field.value);\n field.setAttribute('value', field.value);\n if (field instanceof HTMLTextAreaElement) field.textContent = field.value;\n }\n}\n\nexport function screenshotsClient(capture: PageCapture) {\n return defineClientPlugin<never, never, Capture>({\n name: 'screenshots',\n setup: ({ base, request, options, use }) => {\n const { masking, renderer } = options as { masking: ResolvedMasking; renderer: unknown };\n // Asked at each shot: the annotations plugin may be set up after this one.\n const overlay = (area: Box) => {\n const marks: Annotations | undefined = use('annotations');\n return marks?.svg(area);\n };\n const add = async (body: Blob | string, type: string, { box, size }: Pick<Shot, 'box' | 'size'>): Promise<Shot> => {\n const res = await request('add', { method: 'POST', headers: { 'content-type': type }, body });\n // `url`: where the shot is, said by what keeps it with no server to serve it from (a `standalone` build).\n const { id, url, problem } = (await res.json()) as { id?: string; url?: string; problem?: string };\n if (id === undefined) throw new Error(`screenshots: ${problem ?? res.statusText}`);\n return { id, url: url ?? `${base}__deictic/plugins/screenshots/shot/${id}`, box, size };\n };\n return {\n capture: async (element, { area = 'viewport' } = {}) => {\n const { body, type, box } = await capture(element, { area, masking, renderer, overlay });\n const { clientWidth, clientHeight } = document.documentElement;\n const size = area === 'element' ? { width: box.width, height: box.height } : { width: clientWidth, height: clientHeight };\n return add(body, type, { box, size });\n },\n upload: (png, of) => add(png, 'image/png', of),\n masked: (element) => {\n const copy = element.cloneNode(true) as Element;\n mask(copy, masking);\n return copy;\n },\n };\n },\n });\n}\n"],"mappings":";;;;;;;;AA2BA,MAAa,WAAW,SAAe,EAAE,gBAAgB,WAAW,KAAK,cAAc;;AAGvF,SAAgB,MAAM,SAAkB,MAAgD;CACtF,MAAM,EAAE,GAAG,GAAG,OAAO,WAAW,QAAQ,sBAAsB;CAC9D,OAAO,SAAS,YAAY;EAAE,GAAG;EAAG,GAAG;EAAG;EAAO;CAAO,IAAI;EAAE;EAAG;EAAG;EAAO;CAAO;AACpF;AAEA,MAAM,QAAQ;AAEd,MAAM,YAAY,WAAmB,UAA8B,CAAC,IAAI,IAAI,OAAO,SAAS,KAAK,GAAI,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAE,CAAC,CAAC,KAAK,IAAI;;;;;;AAOrI,SAAgB,KAAK,MAAY,GAA0B;CACzD,IAAI,EAAE,gBAAgB,UAAU;CAChC,MAAM,OAAO,QAAgB,CAAC,GAAI,KAAK,QAAQ,GAAG,IAAI,CAAC,IAAI,IAAI,CAAC,GAAI,GAAG,KAAK,iBAAiB,GAAG,CAAC;CACjG,MAAM,SAAS,SAAiB,KAAK,QAAQ,OAAO,GAAG;CACvD,KAAK,MAAM,MAAM,IAAI,SAAS,EAAE,YAAY,EAAE,aAAa,CAAC,GAAG;EAC7D,GAAG,gBAAgB;EACnB,IAAI,cAAc,eAAe,cAAc,YAAY,GAAG,MAAM,aAAa;CACnF;CACA,KAAK,MAAM,MAAM,IAAI,SAAS,EAAE,eAAe,EAAE,gBAAgB,CAAC,GAAG;EACnE,MAAM,SAAS,SAAS,iBAAiB,IAAI,WAAW,SAAS;EACjE,KAAK,IAAI,OAAO,OAAO,SAAS,GAAG,SAAS,MAAM,OAAO,OAAO,SAAS,GAAG,KAAK,cAAc,MAAM,KAAK,eAAe,EAAE;CAC7H;CACA,KAAK,MAAM,SAAS,IAAI,iBAAiB,GAAG;EAC1C,IAAI,EAAE,iBAAiB,oBAAoB,iBAAiB,sBAAsB;EAClF,IAAI,CAAC,EAAE,iBAAiB,EAAE,iBAAiB,oBAAoB,MAAM,SAAS,aAAa;EAC3F,MAAM,QAAQ,MAAM,MAAM,KAAK;EAC/B,MAAM,aAAa,SAAS,MAAM,KAAK;EACvC,IAAI,iBAAiB,qBAAqB,MAAM,cAAc,MAAM;CACtE;AACF;AAEA,SAAgB,kBAAkB,SAAsB;CACtD,OAAO,mBAA0C;EAC/C,MAAM;EACN,QAAQ,EAAE,MAAM,SAAS,SAAS,UAAU;GAC1C,MAAM,EAAE,SAAS,aAAa;GAE9B,MAAM,WAAW,SAAc;IAE7B,OADuC,IAAI,aAChC,CAAC,EAAE,IAAI,IAAI;GACxB;GACA,MAAM,MAAM,OAAO,MAAqB,MAAc,EAAE,KAAK,WAAsD;IACjH,MAAM,MAAM,MAAM,QAAQ,OAAO;KAAE,QAAQ;KAAQ,SAAS,EAAE,gBAAgB,KAAK;KAAG;IAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../src/plugins/screenshots/client.ts"],"sourcesContent":["/**\n * The screenshots plugin's page half, around a renderer's capture: the renderer makes the shot (a PNG,\n * or what its server half makes one of), and this sends it to the plugin's `add` route and answers the\n * `Shot`. A renderer's page module default-exports `screenshotsClient(itsCapture)`.\n */\nimport { defineClientPlugin } from '#src/index.ts';\nimport type { Annotations } from '#src/plugins/annotations/index.ts';\n\nimport type { Box, Capture, CaptureOptions, ResolvedMasking, Shot } from './index.ts';\n\n/**\n * What a renderer's page half makes of the element: a body for `add`, its type, and where the element is\n * in the shot. `overlay(area)` is what's drawn over the page in that part of the viewport, in viewport CSS\n * pixels, as an SVG that size, or nothing: the annotations plugin's marks, where it's loaded. The renderer\n * draws it over the shot, as deictic's own layers are left out.\n */\nexport type PageCapture = (\n element: Element,\n options: {\n area: NonNullable<CaptureOptions['area']>;\n masking: ResolvedMasking;\n renderer: unknown;\n overlay: (area: Box) => string | undefined;\n },\n) => Promise<{ body: Blob | string; type: string; box: Box }>;\n\n/** Leaves out deictic's own UI: the overlay with its hover outline and any open panel. */\nexport const notOurs = (node: Node) => !(node instanceof Element && node.localName === 'deictic-overlay');\n\n/** The element's box, in CSS pixels from the viewport's top left, or from its own for a shot of it alone. */\nexport function boxOf(element: Element, area: NonNullable<CaptureOptions['area']>): Box {\n const { x, y, width, height } = element.getBoundingClientRect();\n return area === 'element' ? { x: 0, y: 0, width, height } : { x, y, width, height };\n}\n\nconst BLANK = '#d4d4d8';\n\nconst selector = (className: string, extra: string | undefined) => [`.${CSS.escape(className)}`, ...(extra ? [extra] : [])].join(', ');\n\n/**\n * Hides in a copy of the page's what rrweb would: blocked elements become a blank box their size (the copy keeps each\n * element's size as its styles), masked text keeps its spaces but shows `*`, and so do passwords' values,\n * or every field's.\n */\nexport function mask(copy: Node, m: ResolvedMasking): void {\n if (!(copy instanceof Element)) return;\n const all = (sel: string) => [...(copy.matches(sel) ? [copy] : []), ...copy.querySelectorAll(sel)];\n const stars = (text: string) => text.replace(/\\S/g, '*');\n for (const el of all(selector(m.blockClass, m.blockSelector))) {\n el.replaceChildren();\n if (el instanceof HTMLElement || el instanceof SVGElement) el.style.background = BLANK;\n }\n for (const el of all(selector(m.maskTextClass, m.maskTextSelector))) {\n const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);\n for (let text = walker.nextNode(); text !== null; text = walker.nextNode()) text.textContent = stars(text.textContent ?? '');\n }\n for (const field of all('input, textarea')) {\n if (!(field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement)) continue;\n if (!m.maskAllInputs && !(field instanceof HTMLInputElement && field.type === 'password')) continue;\n field.value = stars(field.value);\n field.setAttribute('value', field.value);\n if (field instanceof HTMLTextAreaElement) field.textContent = field.value;\n }\n}\n\nexport function screenshotsClient(capture: PageCapture) {\n return defineClientPlugin<never, never, Capture>({\n name: 'screenshots',\n setup: ({ base, request, options, use }) => {\n const { masking, renderer } = options as { masking: ResolvedMasking; renderer: unknown };\n // Asked at each shot: the annotations plugin may be set up after this one.\n const overlay = (area: Box) => {\n const marks: Annotations | undefined = use('annotations');\n return marks?.svg(area);\n };\n const add = async (body: Blob | string, type: string, { box, size }: Pick<Shot, 'box' | 'size'>): Promise<Shot> => {\n const res = await request('add', { method: 'POST', headers: { 'content-type': type }, body });\n // `url`: where the shot is, said by what keeps it with no server to serve it from (a `standalone` build).\n // `box`: where the element is in a shot drawn again elsewhere, which is what's true of the PNG.\n const { id, url, problem, box: drawn } = (await res.json()) as { id?: string; url?: string; problem?: string; box?: Box };\n if (id === undefined) throw new Error(`screenshots: ${problem ?? res.statusText}`);\n return { id, url: url ?? `${base}__deictic/plugins/screenshots/shot/${id}`, box: drawn ?? box, size };\n };\n return {\n capture: async (element, { area = 'viewport' } = {}) => {\n const { body, type, box } = await capture(element, { area, masking, renderer, overlay });\n const { clientWidth, clientHeight } = document.documentElement;\n const size = area === 'element' ? { width: box.width, height: box.height } : { width: clientWidth, height: clientHeight };\n return add(body, type, { box, size });\n },\n upload: (png, of) => add(png, 'image/png', of),\n masked: (element) => {\n const copy = element.cloneNode(true) as Element;\n mask(copy, masking);\n return copy;\n },\n };\n },\n });\n}\n"],"mappings":";;;;;;;;AA2BA,MAAa,WAAW,SAAe,EAAE,gBAAgB,WAAW,KAAK,cAAc;;AAGvF,SAAgB,MAAM,SAAkB,MAAgD;CACtF,MAAM,EAAE,GAAG,GAAG,OAAO,WAAW,QAAQ,sBAAsB;CAC9D,OAAO,SAAS,YAAY;EAAE,GAAG;EAAG,GAAG;EAAG;EAAO;CAAO,IAAI;EAAE;EAAG;EAAG;EAAO;CAAO;AACpF;AAEA,MAAM,QAAQ;AAEd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AAW,SAAc;IAE7B,OADuC,IAAI,aAChC,CAAC,EAAE,IAAI,IAAI;GACxB;GACA,MAAM,MAAM,OAAO,MAAqB,MAAc,EAAE,KAAK,WAAsD;IACjH,MAAM,MAAM,MAAM,QAAQ,OAAO;KAAE,QAAQ;KAAQ,SAAS,EAAE,gBAAgB,KAAK;KAAG;IAAK,CAAC;IAG5F,MAAM,EAAE,IAAI,KAAK,SAAS,KAAK,UAAW,MAAM,IAAI,KAAK;IACzD,IAAI,OAAO,KAAA,GAAW,MAAM,IAAI,MAAM,gBAAgB,WAAW,IAAI,YAAY;IACjF,OAAO;KAAE;KAAI,KAAK,OAAO,GAAG,KAAK,qCAAqC;KAAM,KAAK,SAAS;KAAK;IAAK;GACtG;GACA,OAAO;IACL,SAAS,OAAO,SAAS,EAAE,OAAO,eAAe,CAAC,MAAM;KACtD,MAAM,EAAE,MAAM,MAAM,QAAQ,MAAM,QAAQ,SAAS;MAAE;MAAM;MAAS;MAAU;KAAQ,CAAC;KACvF,MAAM,EAAE,aAAa,iBAAiB,SAAS;KAC/C,MAAM,OAAO,SAAS,YAAY;MAAE,OAAO,IAAI;MAAO,QAAQ,IAAI;KAAO,IAAI;MAAE,OAAO;MAAa,QAAQ;KAAa;KACxH,OAAO,IAAI,MAAM,MAAM;MAAE;MAAK;KAAK,CAAC;IACtC;IACA,SAAS,KAAK,OAAO,IAAI,KAAK,aAAa,EAAE;IAC7C,SAAS,YAAY;KACnB,MAAM,OAAO,QAAQ,UAAU,IAAI;KACnC,KAAK,MAAM,OAAO;KAClB,OAAO;IACT;GACF;EACF;CACF,CAAC;AACH"}
|
package/dist/shared/endpoints.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { Refusal } from "
|
|
1
|
+
import { t as Refusal } from "./src.js";
|
|
2
2
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { t as keptIn } from "./kept.js";
|
|
5
5
|
import { c as setUp, f as isHost, g as parse, h as openingsIn, l as ASTRO, m as offsetOf, p as lineStarts, u as parseAstro } from "./integration.js";
|
|
6
|
+
import { n as missingMessage } from "./packages.js";
|
|
6
7
|
// src/tools/source.ts
|
|
7
8
|
/**
|
|
8
9
|
* The source a server half reads: a target's file, parsed, and the opening tag the page's attribute
|
|
@@ -245,6 +246,8 @@ function endpoints({ root, plugins, base = "/", open, history = new History(root
|
|
|
245
246
|
const byName = new Map(plugins.map((p) => [p.name, p]));
|
|
246
247
|
const prefix = `${base}__deictic/`;
|
|
247
248
|
const ready = setUp(root, plugins);
|
|
249
|
+
const gone = missingMessage(root, plugins);
|
|
250
|
+
if (gone !== void 0) console.warn(gone);
|
|
248
251
|
const pluginOf = (name) => {
|
|
249
252
|
const plugin = byName.get(name);
|
|
250
253
|
if (plugin === void 0) throw new Refusal(`no plugin "${name}" on the server: is it in the bundler plugin's \`plugins\`?`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoints.js","names":[],"sources":["../../src/tools/source.ts","../../src/tools/history.ts","../../src/tools/endpoints.ts"],"sourcesContent":["/**\n * The source a server half reads: a target's file, parsed, and the opening tag the page's attribute\n * points at. Files are only ever read and written under the project's root, outside `node_modules`.\n */\nimport { readFileSync } from 'node:fs';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\n\nimport { Refusal, type Source, type Target, type TextEdit } from '#src/index.ts';\n\nimport { ASTRO, parseAstro, type Parsed } from './astro.ts';\nimport { isHost, lineStarts, offsetOf, openingsIn, parse } from './locate.ts';\n\n/** A file from the project's root, as an absolute path; refused anywhere the page has no business writing. */\nexport function resolveFile(root: string, file: string): string {\n const path = resolve(root, file);\n const from = relative(root, path);\n // `relative` gives an absolute path for another drive.\n if (from === '' || from.startsWith('..') || isAbsolute(from) || from.split(sep).includes('node_modules'))\n throw new Refusal(`${file} is not a file of this project's own`);\n return path;\n}\n\nexport function readSource(root: string, file: string): string {\n try {\n return readFileSync(resolveFile(root, file), 'utf8');\n } catch (e) {\n if (e instanceof Refusal) throw e;\n throw new Refusal(`can't read ${file}: has it moved since the page loaded?`, { cause: e });\n }\n}\n\n/** The target's file and element, as they are on disk now. */\nexport function sourceAt(root: string, target: Target): Source {\n const { file, line, column } = target.loc;\n const code = readSource(root, file);\n const offset = offsetOf(lineStarts(code), line, column);\n const { program, elements } = ASTRO.test(file) ? astro(root, file, code) : jsx(file, code);\n const element = elements.find((el) => el.start === offset && isHost(el));\n if (element === undefined || (element.name.type === 'JSXIdentifier' && element.name.name !== target.tag))\n throw new Refusal(`no <${target.tag}> at ${file}:${line}:${column} any more: the file changed since the page loaded, so reload it`);\n return { file, code, program, element, read: (other) => readSource(root, other) };\n}\n\nfunction jsx(file: string, code: string): Parsed {\n const { program, errors } = parse(file, code);\n if (errors.length > 0) throw new Refusal(`${file} doesn't parse: fix it first (${errors[0]!.message})`);\n return { program, elements: openingsIn(program) };\n}\n\nfunction astro(root: string, file: string, code: string): Parsed {\n const parsed = parseAstro(root, code);\n if ('problem' in parsed) throw new Refusal(`${file} can't be read: ${parsed.problem}`);\n return parsed;\n}\n\n/** Each file's text after its edits, which must not overlap. */\nexport function applyEdits(source: Source, edits: TextEdit[]): Map<string, string> {\n const byFile = Map.groupBy(edits, (e) => e.file ?? source.file);\n const out = new Map<string, string>();\n for (const [file, list] of byFile) {\n const sorted = list.toSorted((a, b) => b.start - a.start);\n let code = file === source.file ? source.code : source.read(file);\n let floor = Infinity;\n for (const edit of sorted) {\n if (edit.end > floor) throw new Error(`deictic: edits to ${file} overlap at ${edit.end}`);\n code = code.slice(0, edit.start) + edit.text + code.slice(edit.end);\n floor = edit.start;\n }\n out.set(file, code);\n }\n return out;\n}\n","/**\n * Every change deictic made, to undo and redo. A change to files holds each file's whole text\n * before and after: source files are small, and the texts make undo exact without a diff to go stale.\n * A change a plugin made itself (`Done`) holds the plugin's name and its record, and undoing it is the\n * plugin's `undo`.\n *\n * Each change has a scope, the plugin and the element it was made on, and the popup undoes and redoes\n * within its own: the latest change of this tab on this element, not the latest of all. So a change\n * is taken back out of order, with later ones to the same file still in it. Then only the lines the\n * change wrote go back to what they were, where they're still in the file as it wrote them, once.\n *\n * Anything else is refused, not merged: a file whose lines were edited since has the editor's own undo\n * for it; and a redo likewise. A plugin's undo refuses on its own terms. Kept under `.deictic`, so it\n * outlives a restart of the dev server and stays out of git.\n */\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\nimport { Refusal, type ServerPlugin } from '#src/index.ts';\n\nimport { keptIn } from './kept.ts';\nimport { resolveFile } from './source.ts';\n\nexport interface FileChange {\n file: string;\n /** The text before, or nothing for a file the change made. */\n before: string | null;\n after: string;\n}\n\n/** Whose a change is: the plugin whose tab made it, and the element it was open on, as `file:line:column`. */\nexport interface Scope {\n plugin: string;\n target: string;\n}\n\ninterface Base {\n id: number;\n at: string;\n label: string;\n /** None on a change made without one, which only an undo of the whole history reaches. */\n scope?: Scope;\n}\n\nexport type Change = Base & ({ files: FileChange[] } | { plugin: string; record: unknown });\n\n/** A change as the page lists it. `files` is empty for one a plugin made itself. */\nexport interface Summary {\n id: number;\n at: string;\n label: string;\n files: string[];\n}\n\nexport interface HistoryOptions {\n /** Whose `undo` and `redo` take back the changes they made themselves. */\n plugins?: ServerPlugin[];\n store?: string;\n}\n\nconst LIMIT = 200;\n\n/** Whether a change is in a scope: any is in none. */\nconst within = (scope: Scope | undefined) => (c: Change) =>\n scope === undefined || (c.scope?.plugin === scope.plugin && c.scope.target === scope.target);\n\nconst summary = (c: Change): Summary => ({ id: c.id, at: c.at, label: c.label, files: 'files' in c ? c.files.map((f) => f.file) : [] });\n\nexport class History {\n #done: Change[] = [];\n #undone: Change[] = [];\n readonly #root: string;\n readonly #store: string;\n readonly #plugins: Map<string, ServerPlugin>;\n\n constructor(root: string, { plugins = [], store = keptIn(root, 'history.json') }: HistoryOptions = {}) {\n this.#root = root;\n this.#store = store;\n this.#plugins = new Map(plugins.map((p) => [p.name, p]));\n if (!existsSync(store)) return;\n try {\n ({ done: this.#done, undone: this.#undone } = JSON.parse(readFileSync(store, 'utf8')) as { done: Change[]; undone: Change[] });\n } catch {\n // A history that doesn't read is one we start over, not one to stop the dev server for.\n }\n }\n\n /** Writes each file's new text and records it as one change. A redo after it, in its scope, is gone, as in any editor. */\n commit(label: string, texts: Map<string, string>, scope?: Scope): Summary {\n const files: FileChange[] = [];\n for (const [file, after] of texts) {\n const path = resolveFile(this.#root, file);\n const before = existsSync(path) ? readFileSync(path, 'utf8') : null;\n if (before !== after) files.push({ file, before, after });\n }\n if (files.length === 0) throw new Refusal('nothing to change: the source already says that');\n for (const f of files) write(resolveFile(this.#root, f.file), f.after);\n return this.#push({ label, files }, scope);\n }\n\n /** Records a change `plugin` made itself, with what its `undo` needs. */\n record(label: string, plugin: string, record: unknown, scope?: Scope): Summary {\n return this.#push({ label, plugin, record }, scope);\n }\n\n /** Takes back the latest change, of a scope where one is given. */\n async undo(scope?: Scope): Promise<Summary> {\n const change = this.#done.findLast(within(scope));\n if (change === undefined) throw new Refusal(scope === undefined ? 'nothing to undo' : 'nothing to undo here');\n if ('files' in change) this.#put(change, 'after', 'before');\n else change.record = (await this.#pluginOf(change, 'undo').undo!(change.record)) ?? change.record;\n this.#done = this.#done.filter((c) => c !== change);\n this.#undone.push(change);\n this.#save();\n return summary(change);\n }\n\n /** Makes the change last undone again, of a scope where one is given. */\n async redo(scope?: Scope): Promise<Summary> {\n const change = this.#undone.findLast(within(scope));\n if (change === undefined) throw new Refusal(scope === undefined ? 'nothing to redo' : 'nothing to redo here');\n if ('files' in change) this.#put(change, 'before', 'after');\n else change.record = await this.#pluginOf(change, 'redo').redo!(change.record);\n this.#undone = this.#undone.filter((c) => c !== change);\n this.#done.push(change);\n this.#save();\n return summary(change);\n }\n\n list(scope?: Scope): { done: Summary[]; undone: Summary[] } {\n return { done: this.#done.filter(within(scope)).map(summary), undone: this.#undone.filter(within(scope)).map(summary) };\n }\n\n #push(change: Omit<Base, 'id' | 'at'> & ({ files: FileChange[] } | { plugin: string; record: unknown }), scope?: Scope): Summary {\n const id = Math.max(0, ...[...this.#done, ...this.#undone].map((c) => c.id)) + 1;\n const made = { id, at: new Date().toISOString(), ...change, ...(scope === undefined ? {} : { scope }) };\n this.#done = [...this.#done, made].slice(-LIMIT);\n // What was undone in this scope can't be redone over the new change; another scope's still can.\n this.#undone = this.#undone.filter((c) => !within(scope)(c));\n this.#save();\n return summary(made);\n }\n\n #pluginOf(change: { label: string; plugin: string }, step: 'undo' | 'redo'): ServerPlugin {\n const plugin = this.#plugins.get(change.plugin);\n if (plugin?.[step] === undefined) {\n throw new Refusal(\n `can't ${step} \"${change.label}\": the ${change.plugin} plugin that made it isn't loaded, so add it back to \\`plugins\\``,\n );\n }\n return plugin;\n }\n\n /**\n * Puts each file's `to` text back, once every one of them still reads as its `from`, or still has the\n * lines that differ as `from` has them: then those lines alone change, and the rest stays as it is now.\n */\n #put(change: Base & { files: FileChange[] }, from: 'before' | 'after', to: 'before' | 'after'): void {\n const paths = change.files.map((f) => resolveFile(this.#root, f.file));\n const texts = change.files.map((f, i) => {\n const now = existsSync(paths[i]!) ? readFileSync(paths[i]!, 'utf8') : null;\n if (now === f[from]) return f[to];\n const text = now === null || f[from] === null || f[to] === null ? undefined : swapped(now, f[from], f[to]);\n if (text === undefined) {\n throw new Refusal(\n `${f.file} changed since \"${change.label}\" ${from === 'after' ? 'was made' : 'was undone'}: use the editor's undo there`,\n );\n }\n return text;\n });\n texts.forEach((text, i) => {\n if (text === null) rmSync(paths[i]!);\n else write(paths[i]!, text);\n });\n }\n\n #save(): void {\n write(this.#store, JSON.stringify({ done: this.#done, undone: this.#undone }));\n }\n}\n\n/**\n * `now` with the lines that differ between `from` and `to` put as `to` has them, where `now` has them as\n * `from` does, in one place only. Nothing where it doesn't (they were edited, or there are two of them), or\n * where `from` has no such lines to find (the change only removed some).\n */\nfunction swapped(now: string, from: string, to: string): string | undefined {\n const [a, b, lines] = [from.split('\\n'), to.split('\\n'), now.split('\\n')];\n let head = 0;\n while (head < a.length && head < b.length && a[head] === b[head]) head++;\n let tail = 0;\n while (tail < a.length - head && tail < b.length - head && a.at(-1 - tail) === b.at(-1 - tail)) tail++;\n const theirs = a.slice(head, a.length - tail);\n if (theirs.length === 0) return undefined;\n const found = lines.flatMap((_, i) => (theirs.every((line, j) => lines[i + j] === line) ? [i] : []));\n if (found.length !== 1) return undefined;\n return [...lines.slice(0, found[0]), ...b.slice(head, b.length - tail), ...lines.slice(found[0]! + theirs.length)].join('\\n');\n}\n\nfunction write(path: string, text: string): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, text);\n}\n","/**\n * The dev server's half of deictic, under `/__deictic/`: `read` and `apply` an op through a\n * plugin, `undo`, `redo` and `history`, and `open`, which opens a place in the editor. Written over\n * `Request` and `Response`, so each integration mounts them its own way (Vite as middleware), and\n * served from the page's own origin, so no token travels to the page. `undo`, `redo` and `history` are a\n * plugin's on an element where the request names them (as the popup does: its tab, its element), and\n * the whole history's where it doesn't.\n *\n * Everything but `open` and `history` writes or may, so only the page itself may send it: a POST of\n * JSON from the same origin, which a form or a script on another site can't send without asking first.\n *\n * Each plugin's own `routes` are under `plugins/<name>/`. A `GET` there reaches the plugin as it\n * comes; anything else only from the page's own origin, in whatever type it sends (an image, say).\n * Nothing is answered before every plugin's `setup` has run.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport { type Loc, Refusal, type ServerPlugin, type Target } from '#src/index.ts';\n\nimport { History, type Scope } from './history.ts';\nimport { setUp } from './plugins.ts';\nimport { applyEdits, resolveFile, sourceAt } from './source.ts';\n\nexport interface EndpointOptions {\n root: string;\n plugins: ServerPlugin[];\n /** The path the endpoints sit under, ending in `/`: `/` by default. */\n base?: string;\n /** Opens a place in the editor: a redirect to the dev server's own launcher. */\n open: (path: string, loc: Loc) => Response | Promise<Response>;\n history?: History;\n}\n\ninterface Body {\n plugin: string;\n target: Target;\n op?: unknown;\n}\n\nconst scopeOf = (plugin: string, { file, line, column }: Loc): Scope => ({ plugin, target: `${file}:${line}:${column}` });\n/** The scope an undo or a redo names, or none for the whole history. */\nconst scopeIn = ({ plugin, target }: Partial<Body>) =>\n plugin === undefined || target === undefined ? undefined : scopeOf(plugin, target.loc);\n\n/** Answers deictic's requests, and nothing for any other path. */\nexport function endpoints({ root, plugins, base = '/', open, history = new History(root, { plugins }) }: EndpointOptions) {\n const byName = new Map(plugins.map((p) => [p.name, p]));\n const prefix = `${base}__deictic/`;\n // Started now, awaited by every request: a plugin's API is there before anything asks for it.\n const ready = setUp(root, plugins);\n\n const pluginOf = (name: string) => {\n const plugin = byName.get(name);\n if (plugin === undefined) throw new Refusal(`no plugin \"${name}\" on the server: is it in the bundler plugin's \\`plugins\\`?`);\n return plugin;\n };\n\n const routes: Record<string, (body: Body) => Promise<unknown>> = {\n read: async ({ plugin, target }) => ({ model: await readOf(pluginOf(plugin), target) }),\n apply: async ({ plugin: name, target, op }) => {\n const plugin = pluginOf(name);\n if (plugin.apply === undefined) throw new Refusal(`${name} changes nothing from its panel: it has no \\`apply\\``);\n const source = sourceAt(root, target);\n const before = await readOf(plugin, target);\n const { file, line } = target.loc;\n const label = `${name} ${file}:${line}: ${plugin.describe?.(op, before) ?? 'edit'}`;\n const result = await plugin.apply(source, target, op);\n const scope = scopeOf(name, target.loc);\n const change = Array.isArray(result)\n ? history.commit(label, applyEdits(source, result), scope)\n : history.record(label, name, result.done, scope);\n return { model: await readOf(plugin, target), change };\n },\n undo: async (body) => ({ change: await history.undo(scopeIn(body)) }),\n redo: async (body) => ({ change: await history.redo(scopeIn(body)) }),\n };\n // A plugin without `read` has no model, and no need for its element to be where the page says.\n const readOf = (plugin: ServerPlugin, target: Target) => (plugin.read === undefined ? null : plugin.read(sourceAt(root, target), target));\n // One write at a time: a plugin's change may wait on the network, and an undo sent meanwhile must\n // take back that change, not the one before it.\n let queue: Promise<unknown> = Promise.resolve();\n const serially = <T>(run: () => Promise<T>): Promise<T> => {\n const next = queue.then(run, run);\n queue = next.catch(() => {});\n return next;\n };\n\n return async (req: Request): Promise<Response | undefined> => {\n const url = new URL(req.url);\n if (!url.pathname.startsWith(prefix)) return undefined;\n const route = url.pathname.slice(prefix.length);\n const origin = req.headers.get('origin');\n const sameOrigin = origin !== null && new URL(origin).host === url.host;\n try {\n const context = await ready;\n if (route.startsWith('plugins/')) {\n const [name = '', first = ''] = route.slice('plugins/'.length).split('/');\n const handle = byName.get(name)?.routes?.[first];\n if (handle === undefined) return new Response(`no endpoint ${url.pathname}`, { status: 404 });\n if (req.method !== 'GET' && req.method !== 'HEAD' && !sameOrigin)\n return Response.json({ problem: `only the page itself may ${req.method} to ${name}` }, { status: 403 });\n return await handle(req, context);\n }\n const loc = {\n file: url.searchParams.get('file') ?? '',\n line: Number(url.searchParams.get('line')),\n column: Number(url.searchParams.get('column')),\n };\n if (route === 'history') {\n const plugin = url.searchParams.get('plugin');\n return Response.json(history.list(plugin === null ? undefined : scopeOf(plugin, loc)));\n }\n if (route === 'open') return await open(resolveFile(root, loc.file), loc);\n const handler = routes[route];\n if (handler === undefined) return new Response(`no endpoint ${url.pathname}`, { status: 404 });\n if (req.method !== 'POST' || !sameOrigin || req.headers.get('content-type')?.startsWith('application/json') !== true)\n return Response.json({ problem: 'edits come from the page, as JSON' }, { status: 403 });\n const body = (await req.json()) as Body;\n return Response.json(await (route === 'read' ? handler(body) : serially(() => handler(body))));\n } catch (e) {\n if (e instanceof Refusal) return Response.json({ problem: e.message }, { status: 422 });\n return Response.json({ problem: e instanceof Error ? (e.stack ?? e.message) : String(e) }, { status: 500 });\n }\n };\n}\n\n/** A redirect within the page's origin, to a launcher the dev server answers itself. */\nexport const redirect = (path: string) => new Response(null, { status: 307, headers: { Location: path } });\n\n/**\n * The endpoints as Node middleware, for Vite's server. The request's host is the one the page was\n * served from: a proxy's `x-forwarded-host` before its own.\n */\nexport function nodeMiddleware(\n handle: (req: Request) => Promise<Response | undefined>,\n): (req: IncomingMessage, res: ServerResponse, next: () => void) => void {\n return (req, res, next) => {\n // Before reading the body, which a request for anything else leaves to whoever answers it.\n if (req.url?.includes('/__deictic/') !== true) return next();\n const forwarded = req.headers['x-forwarded-host'];\n const host = (Array.isArray(forwarded) ? forwarded[0] : forwarded) ?? req.headers.host ?? 'localhost';\n const headers = new Headers();\n for (const [name, value] of Object.entries(req.headers))\n for (const v of Array.isArray(value) ? value : value === undefined ? [] : [value]) headers.append(name, v);\n\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(chunk));\n req.on('end', () => {\n const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : Buffer.concat(chunks);\n handle(new Request(`http://${host}${req.url}`, { method: req.method, headers, body }))\n .then(async (response) => {\n if (response === undefined) return next();\n res.statusCode = response.status;\n response.headers.forEach((value, name) => res.setHeader(name, value));\n res.end(Buffer.from(await response.arrayBuffer()));\n })\n .catch((e: unknown) => {\n res.statusCode = 500;\n res.end(e instanceof Error ? e.message : String(e));\n });\n });\n };\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAgB,YAAY,MAAc,MAAsB;CAC9D,MAAM,OAAO,QAAQ,MAAM,IAAI;CAC/B,MAAM,OAAO,SAAS,MAAM,IAAI;CAEhC,IAAI,SAAS,MAAM,KAAK,WAAW,IAAI,KAAK,WAAW,IAAI,KAAK,KAAK,MAAM,GAAG,CAAC,CAAC,SAAS,cAAc,GACrG,MAAM,IAAI,QAAQ,GAAG,KAAK,qCAAqC;CACjE,OAAO;AACT;AAEA,SAAgB,WAAW,MAAc,MAAsB;CAC7D,IAAI;EACF,OAAO,aAAa,YAAY,MAAM,IAAI,GAAG,MAAM;CACrD,SAAS,GAAG;EACV,IAAI,aAAa,SAAS,MAAM;EAChC,MAAM,IAAI,QAAQ,cAAc,KAAK,wCAAwC,EAAE,OAAO,EAAE,CAAC;CAC3F;AACF;;AAGA,SAAgB,SAAS,MAAc,QAAwB;CAC7D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AW,OAAO,KAAK;IACxC,IAAI,aAAa,SAAS;IAC1B,SAAS,QAAQ,SAAS,OAAO,SAAS,IAAI,UAAU,MAAM,KAAK,CAAC;IACpE,IAAI,IAAI,OAAO,KAAK,MAAM,SAAS,YAAY,CAAC,CAAC;GACnD,CAAC,CAAC,CACD,OAAO,MAAe;IACrB,IAAI,aAAa;IACjB,IAAI,IAAI,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;GACpD,CAAC;EACL,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"endpoints.js","names":[],"sources":["../../src/tools/source.ts","../../src/tools/history.ts","../../src/tools/endpoints.ts"],"sourcesContent":["/**\n * The source a server half reads: a target's file, parsed, and the opening tag the page's attribute\n * points at. Files are only ever read and written under the project's root, outside `node_modules`.\n */\nimport { readFileSync } from 'node:fs';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\n\nimport { Refusal, type Source, type Target, type TextEdit } from '#src/index.ts';\n\nimport { ASTRO, parseAstro, type Parsed } from './astro.ts';\nimport { isHost, lineStarts, offsetOf, openingsIn, parse } from './locate.ts';\n\n/** A file from the project's root, as an absolute path; refused anywhere the page has no business writing. */\nexport function resolveFile(root: string, file: string): string {\n const path = resolve(root, file);\n const from = relative(root, path);\n // `relative` gives an absolute path for another drive.\n if (from === '' || from.startsWith('..') || isAbsolute(from) || from.split(sep).includes('node_modules'))\n throw new Refusal(`${file} is not a file of this project's own`);\n return path;\n}\n\nexport function readSource(root: string, file: string): string {\n try {\n return readFileSync(resolveFile(root, file), 'utf8');\n } catch (e) {\n if (e instanceof Refusal) throw e;\n throw new Refusal(`can't read ${file}: has it moved since the page loaded?`, { cause: e });\n }\n}\n\n/** The target's file and element, as they are on disk now. */\nexport function sourceAt(root: string, target: Target): Source {\n const { file, line, column } = target.loc;\n const code = readSource(root, file);\n const offset = offsetOf(lineStarts(code), line, column);\n const { program, elements } = ASTRO.test(file) ? astro(root, file, code) : jsx(file, code);\n const element = elements.find((el) => el.start === offset && isHost(el));\n if (element === undefined || (element.name.type === 'JSXIdentifier' && element.name.name !== target.tag))\n throw new Refusal(`no <${target.tag}> at ${file}:${line}:${column} any more: the file changed since the page loaded, so reload it`);\n return { file, code, program, element, read: (other) => readSource(root, other) };\n}\n\nfunction jsx(file: string, code: string): Parsed {\n const { program, errors } = parse(file, code);\n if (errors.length > 0) throw new Refusal(`${file} doesn't parse: fix it first (${errors[0]!.message})`);\n return { program, elements: openingsIn(program) };\n}\n\nfunction astro(root: string, file: string, code: string): Parsed {\n const parsed = parseAstro(root, code);\n if ('problem' in parsed) throw new Refusal(`${file} can't be read: ${parsed.problem}`);\n return parsed;\n}\n\n/** Each file's text after its edits, which must not overlap. */\nexport function applyEdits(source: Source, edits: TextEdit[]): Map<string, string> {\n const byFile = Map.groupBy(edits, (e) => e.file ?? source.file);\n const out = new Map<string, string>();\n for (const [file, list] of byFile) {\n const sorted = list.toSorted((a, b) => b.start - a.start);\n let code = file === source.file ? source.code : source.read(file);\n let floor = Infinity;\n for (const edit of sorted) {\n if (edit.end > floor) throw new Error(`deictic: edits to ${file} overlap at ${edit.end}`);\n code = code.slice(0, edit.start) + edit.text + code.slice(edit.end);\n floor = edit.start;\n }\n out.set(file, code);\n }\n return out;\n}\n","/**\n * Every change deictic made, to undo and redo. A change to files holds each file's whole text\n * before and after: source files are small, and the texts make undo exact without a diff to go stale.\n * A change a plugin made itself (`Done`) holds the plugin's name and its record, and undoing it is the\n * plugin's `undo`.\n *\n * Each change has a scope, the plugin and the element it was made on, and the popup undoes and redoes\n * within its own: the latest change of this tab on this element, not the latest of all. So a change\n * is taken back out of order, with later ones to the same file still in it. Then only the lines the\n * change wrote go back to what they were, where they're still in the file as it wrote them, once.\n *\n * Anything else is refused, not merged: a file whose lines were edited since has the editor's own undo\n * for it; and a redo likewise. A plugin's undo refuses on its own terms. Kept under `.deictic`, so it\n * outlives a restart of the dev server and stays out of git.\n */\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\nimport { Refusal, type ServerPlugin } from '#src/index.ts';\n\nimport { keptIn } from './kept.ts';\nimport { resolveFile } from './source.ts';\n\nexport interface FileChange {\n file: string;\n /** The text before, or nothing for a file the change made. */\n before: string | null;\n after: string;\n}\n\n/** Whose a change is: the plugin whose tab made it, and the element it was open on, as `file:line:column`. */\nexport interface Scope {\n plugin: string;\n target: string;\n}\n\ninterface Base {\n id: number;\n at: string;\n label: string;\n /** None on a change made without one, which only an undo of the whole history reaches. */\n scope?: Scope;\n}\n\nexport type Change = Base & ({ files: FileChange[] } | { plugin: string; record: unknown });\n\n/** A change as the page lists it. `files` is empty for one a plugin made itself. */\nexport interface Summary {\n id: number;\n at: string;\n label: string;\n files: string[];\n}\n\nexport interface HistoryOptions {\n /** Whose `undo` and `redo` take back the changes they made themselves. */\n plugins?: ServerPlugin[];\n store?: string;\n}\n\nconst LIMIT = 200;\n\n/** Whether a change is in a scope: any is in none. */\nconst within = (scope: Scope | undefined) => (c: Change) =>\n scope === undefined || (c.scope?.plugin === scope.plugin && c.scope.target === scope.target);\n\nconst summary = (c: Change): Summary => ({ id: c.id, at: c.at, label: c.label, files: 'files' in c ? c.files.map((f) => f.file) : [] });\n\nexport class History {\n #done: Change[] = [];\n #undone: Change[] = [];\n readonly #root: string;\n readonly #store: string;\n readonly #plugins: Map<string, ServerPlugin>;\n\n constructor(root: string, { plugins = [], store = keptIn(root, 'history.json') }: HistoryOptions = {}) {\n this.#root = root;\n this.#store = store;\n this.#plugins = new Map(plugins.map((p) => [p.name, p]));\n if (!existsSync(store)) return;\n try {\n ({ done: this.#done, undone: this.#undone } = JSON.parse(readFileSync(store, 'utf8')) as { done: Change[]; undone: Change[] });\n } catch {\n // A history that doesn't read is one we start over, not one to stop the dev server for.\n }\n }\n\n /** Writes each file's new text and records it as one change. A redo after it, in its scope, is gone, as in any editor. */\n commit(label: string, texts: Map<string, string>, scope?: Scope): Summary {\n const files: FileChange[] = [];\n for (const [file, after] of texts) {\n const path = resolveFile(this.#root, file);\n const before = existsSync(path) ? readFileSync(path, 'utf8') : null;\n if (before !== after) files.push({ file, before, after });\n }\n if (files.length === 0) throw new Refusal('nothing to change: the source already says that');\n for (const f of files) write(resolveFile(this.#root, f.file), f.after);\n return this.#push({ label, files }, scope);\n }\n\n /** Records a change `plugin` made itself, with what its `undo` needs. */\n record(label: string, plugin: string, record: unknown, scope?: Scope): Summary {\n return this.#push({ label, plugin, record }, scope);\n }\n\n /** Takes back the latest change, of a scope where one is given. */\n async undo(scope?: Scope): Promise<Summary> {\n const change = this.#done.findLast(within(scope));\n if (change === undefined) throw new Refusal(scope === undefined ? 'nothing to undo' : 'nothing to undo here');\n if ('files' in change) this.#put(change, 'after', 'before');\n else change.record = (await this.#pluginOf(change, 'undo').undo!(change.record)) ?? change.record;\n this.#done = this.#done.filter((c) => c !== change);\n this.#undone.push(change);\n this.#save();\n return summary(change);\n }\n\n /** Makes the change last undone again, of a scope where one is given. */\n async redo(scope?: Scope): Promise<Summary> {\n const change = this.#undone.findLast(within(scope));\n if (change === undefined) throw new Refusal(scope === undefined ? 'nothing to redo' : 'nothing to redo here');\n if ('files' in change) this.#put(change, 'before', 'after');\n else change.record = await this.#pluginOf(change, 'redo').redo!(change.record);\n this.#undone = this.#undone.filter((c) => c !== change);\n this.#done.push(change);\n this.#save();\n return summary(change);\n }\n\n list(scope?: Scope): { done: Summary[]; undone: Summary[] } {\n return { done: this.#done.filter(within(scope)).map(summary), undone: this.#undone.filter(within(scope)).map(summary) };\n }\n\n #push(change: Omit<Base, 'id' | 'at'> & ({ files: FileChange[] } | { plugin: string; record: unknown }), scope?: Scope): Summary {\n const id = Math.max(0, ...[...this.#done, ...this.#undone].map((c) => c.id)) + 1;\n const made = { id, at: new Date().toISOString(), ...change, ...(scope === undefined ? {} : { scope }) };\n this.#done = [...this.#done, made].slice(-LIMIT);\n // What was undone in this scope can't be redone over the new change; another scope's still can.\n this.#undone = this.#undone.filter((c) => !within(scope)(c));\n this.#save();\n return summary(made);\n }\n\n #pluginOf(change: { label: string; plugin: string }, step: 'undo' | 'redo'): ServerPlugin {\n const plugin = this.#plugins.get(change.plugin);\n if (plugin?.[step] === undefined) {\n throw new Refusal(\n `can't ${step} \"${change.label}\": the ${change.plugin} plugin that made it isn't loaded, so add it back to \\`plugins\\``,\n );\n }\n return plugin;\n }\n\n /**\n * Puts each file's `to` text back, once every one of them still reads as its `from`, or still has the\n * lines that differ as `from` has them: then those lines alone change, and the rest stays as it is now.\n */\n #put(change: Base & { files: FileChange[] }, from: 'before' | 'after', to: 'before' | 'after'): void {\n const paths = change.files.map((f) => resolveFile(this.#root, f.file));\n const texts = change.files.map((f, i) => {\n const now = existsSync(paths[i]!) ? readFileSync(paths[i]!, 'utf8') : null;\n if (now === f[from]) return f[to];\n const text = now === null || f[from] === null || f[to] === null ? undefined : swapped(now, f[from], f[to]);\n if (text === undefined) {\n throw new Refusal(\n `${f.file} changed since \"${change.label}\" ${from === 'after' ? 'was made' : 'was undone'}: use the editor's undo there`,\n );\n }\n return text;\n });\n texts.forEach((text, i) => {\n if (text === null) rmSync(paths[i]!);\n else write(paths[i]!, text);\n });\n }\n\n #save(): void {\n write(this.#store, JSON.stringify({ done: this.#done, undone: this.#undone }));\n }\n}\n\n/**\n * `now` with the lines that differ between `from` and `to` put as `to` has them, where `now` has them as\n * `from` does, in one place only. Nothing where it doesn't (they were edited, or there are two of them), or\n * where `from` has no such lines to find (the change only removed some).\n */\nfunction swapped(now: string, from: string, to: string): string | undefined {\n const [a, b, lines] = [from.split('\\n'), to.split('\\n'), now.split('\\n')];\n let head = 0;\n while (head < a.length && head < b.length && a[head] === b[head]) head++;\n let tail = 0;\n while (tail < a.length - head && tail < b.length - head && a.at(-1 - tail) === b.at(-1 - tail)) tail++;\n const theirs = a.slice(head, a.length - tail);\n if (theirs.length === 0) return undefined;\n const found = lines.flatMap((_, i) => (theirs.every((line, j) => lines[i + j] === line) ? [i] : []));\n if (found.length !== 1) return undefined;\n return [...lines.slice(0, found[0]), ...b.slice(head, b.length - tail), ...lines.slice(found[0]! + theirs.length)].join('\\n');\n}\n\nfunction write(path: string, text: string): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, text);\n}\n","/**\n * The dev server's half of deictic, under `/__deictic/`: `read` and `apply` an op through a\n * plugin, `undo`, `redo` and `history`, and `open`, which opens a place in the editor. Written over\n * `Request` and `Response`, so each integration mounts them its own way (Vite as middleware), and\n * served from the page's own origin, so no token travels to the page. `undo`, `redo` and `history` are a\n * plugin's on an element where the request names them (as the popup does: its tab, its element), and\n * the whole history's where it doesn't.\n *\n * Everything but `open` and `history` writes or may, so only the page itself may send it: a POST of\n * JSON from the same origin, which a form or a script on another site can't send without asking first.\n *\n * Each plugin's own `routes` are under `plugins/<name>/`. A `GET` there reaches the plugin as it\n * comes; anything else only from the page's own origin, in whatever type it sends (an image, say).\n * Nothing is answered before every plugin's `setup` has run.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport { type Loc, Refusal, type ServerPlugin, type Target } from '#src/index.ts';\n\nimport { History, type Scope } from './history.ts';\nimport { missingMessage } from './packages.ts';\nimport { setUp } from './plugins.ts';\nimport { applyEdits, resolveFile, sourceAt } from './source.ts';\n\nexport interface EndpointOptions {\n root: string;\n plugins: ServerPlugin[];\n /** The path the endpoints sit under, ending in `/`: `/` by default. */\n base?: string;\n /** Opens a place in the editor: a redirect to the dev server's own launcher. */\n open: (path: string, loc: Loc) => Response | Promise<Response>;\n history?: History;\n}\n\ninterface Body {\n plugin: string;\n target: Target;\n op?: unknown;\n}\n\nconst scopeOf = (plugin: string, { file, line, column }: Loc): Scope => ({ plugin, target: `${file}:${line}:${column}` });\n/** The scope an undo or a redo names, or none for the whole history. */\nconst scopeIn = ({ plugin, target }: Partial<Body>) =>\n plugin === undefined || target === undefined ? undefined : scopeOf(plugin, target.loc);\n\n/** Answers deictic's requests, and nothing for any other path. */\nexport function endpoints({ root, plugins, base = '/', open, history = new History(root, { plugins }) }: EndpointOptions) {\n const byName = new Map(plugins.map((p) => [p.name, p]));\n const prefix = `${base}__deictic/`;\n // Started now, awaited by every request: a plugin's API is there before anything asks for it.\n const ready = setUp(root, plugins);\n const gone = missingMessage(root, plugins);\n if (gone !== undefined) console.warn(gone);\n\n const pluginOf = (name: string) => {\n const plugin = byName.get(name);\n if (plugin === undefined) throw new Refusal(`no plugin \"${name}\" on the server: is it in the bundler plugin's \\`plugins\\`?`);\n return plugin;\n };\n\n const routes: Record<string, (body: Body) => Promise<unknown>> = {\n read: async ({ plugin, target }) => ({ model: await readOf(pluginOf(plugin), target) }),\n apply: async ({ plugin: name, target, op }) => {\n const plugin = pluginOf(name);\n if (plugin.apply === undefined) throw new Refusal(`${name} changes nothing from its panel: it has no \\`apply\\``);\n const source = sourceAt(root, target);\n const before = await readOf(plugin, target);\n const { file, line } = target.loc;\n const label = `${name} ${file}:${line}: ${plugin.describe?.(op, before) ?? 'edit'}`;\n const result = await plugin.apply(source, target, op);\n const scope = scopeOf(name, target.loc);\n const change = Array.isArray(result)\n ? history.commit(label, applyEdits(source, result), scope)\n : history.record(label, name, result.done, scope);\n return { model: await readOf(plugin, target), change };\n },\n undo: async (body) => ({ change: await history.undo(scopeIn(body)) }),\n redo: async (body) => ({ change: await history.redo(scopeIn(body)) }),\n };\n // A plugin without `read` has no model, and no need for its element to be where the page says.\n const readOf = (plugin: ServerPlugin, target: Target) => (plugin.read === undefined ? null : plugin.read(sourceAt(root, target), target));\n // One write at a time: a plugin's change may wait on the network, and an undo sent meanwhile must\n // take back that change, not the one before it.\n let queue: Promise<unknown> = Promise.resolve();\n const serially = <T>(run: () => Promise<T>): Promise<T> => {\n const next = queue.then(run, run);\n queue = next.catch(() => {});\n return next;\n };\n\n return async (req: Request): Promise<Response | undefined> => {\n const url = new URL(req.url);\n if (!url.pathname.startsWith(prefix)) return undefined;\n const route = url.pathname.slice(prefix.length);\n const origin = req.headers.get('origin');\n const sameOrigin = origin !== null && new URL(origin).host === url.host;\n try {\n const context = await ready;\n if (route.startsWith('plugins/')) {\n const [name = '', first = ''] = route.slice('plugins/'.length).split('/');\n const handle = byName.get(name)?.routes?.[first];\n if (handle === undefined) return new Response(`no endpoint ${url.pathname}`, { status: 404 });\n if (req.method !== 'GET' && req.method !== 'HEAD' && !sameOrigin)\n return Response.json({ problem: `only the page itself may ${req.method} to ${name}` }, { status: 403 });\n return await handle(req, context);\n }\n const loc = {\n file: url.searchParams.get('file') ?? '',\n line: Number(url.searchParams.get('line')),\n column: Number(url.searchParams.get('column')),\n };\n if (route === 'history') {\n const plugin = url.searchParams.get('plugin');\n return Response.json(history.list(plugin === null ? undefined : scopeOf(plugin, loc)));\n }\n if (route === 'open') return await open(resolveFile(root, loc.file), loc);\n const handler = routes[route];\n if (handler === undefined) return new Response(`no endpoint ${url.pathname}`, { status: 404 });\n if (req.method !== 'POST' || !sameOrigin || req.headers.get('content-type')?.startsWith('application/json') !== true)\n return Response.json({ problem: 'edits come from the page, as JSON' }, { status: 403 });\n const body = (await req.json()) as Body;\n return Response.json(await (route === 'read' ? handler(body) : serially(() => handler(body))));\n } catch (e) {\n if (e instanceof Refusal) return Response.json({ problem: e.message }, { status: 422 });\n return Response.json({ problem: e instanceof Error ? (e.stack ?? e.message) : String(e) }, { status: 500 });\n }\n };\n}\n\n/** A redirect within the page's origin, to a launcher the dev server answers itself. */\nexport const redirect = (path: string) => new Response(null, { status: 307, headers: { Location: path } });\n\n/**\n * The endpoints as Node middleware, for Vite's server. The request's host is the one the page was\n * served from: a proxy's `x-forwarded-host` before its own.\n */\nexport function nodeMiddleware(\n handle: (req: Request) => Promise<Response | undefined>,\n): (req: IncomingMessage, res: ServerResponse, next: () => void) => void {\n return (req, res, next) => {\n // Before reading the body, which a request for anything else leaves to whoever answers it.\n if (req.url?.includes('/__deictic/') !== true) return next();\n const forwarded = req.headers['x-forwarded-host'];\n const host = (Array.isArray(forwarded) ? forwarded[0] : forwarded) ?? req.headers.host ?? 'localhost';\n const headers = new Headers();\n for (const [name, value] of Object.entries(req.headers))\n for (const v of Array.isArray(value) ? value : value === undefined ? [] : [value]) headers.append(name, v);\n\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(chunk));\n req.on('end', () => {\n const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : Buffer.concat(chunks);\n handle(new Request(`http://${host}${req.url}`, { method: req.method, headers, body }))\n .then(async (response) => {\n if (response === undefined) return next();\n res.statusCode = response.status;\n response.headers.forEach((value, name) => res.setHeader(name, value));\n res.end(Buffer.from(await response.arrayBuffer()));\n })\n .catch((e: unknown) => {\n res.statusCode = 500;\n res.end(e instanceof Error ? e.message : String(e));\n });\n });\n };\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,YAAY,MAAc,MAAsB;CAC9D,MAAM,OAAO,QAAQ,MAAM,IAAI;CAC/B,MAAM,OAAO,SAAS,MAAM,IAAI;CAEhC,IAAI,SAAS,MAAM,KAAK,WAAW,IAAI,KAAK,WAAW,IAAI,KAAK,KAAK,MAAM,GAAG,CAAC,CAAC,SAAS,cAAc,GACrG,MAAM,IAAI,QAAQ,GAAG,KAAK,qCAAqC;CACjE,OAAO;AACT;AAEA,SAAgB,WAAW,MAAc,MAAsB;CAC7D,IAAI;EACF,OAAO,aAAa,YAAY,MAAM,IAAI,GAAG,MAAM;CACrD,SAAS,GAAG;EACV,IAAI,aAAa,SAAS,MAAM;EAChC,MAAM,IAAI,QAAQ,cAAc,KAAK,wCAAwC,EAAE,OAAO,EAAE,CAAC;CAC3F;AACF;;AAGA,SAAgB,SAAS,MAAc,QAAwB;CAC7D,MAAM,EAAE,MAAM,MAAM,WAAW,OAAO;CACtC,MAAM,OAAO,WAAW,MAAM,IAAI;CAClC,MAAM,SAAS,SAAS,WAAW,IAAI,GAAG,MAAM,MAAM;CACtD,MAAM,EAAE,SAAS,aAAa,MAAM,KAAK,IAAI,IAAI,MAAM,MAAM,MAAM,IAAI,IAAI,IAAI,MAAM,IAAI;CACzF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YAAY,CAAC,CAAC;GACnD,CAAC,CAAC,CACD,OAAO,MAAe;IACrB,IAAI,aAAa;IACjB,IAAI,IAAI,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;GACpD,CAAC;EACL,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, readdirSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { f as task, l as fail, o as deicticDirs, s as download } from "./board.js";
|
|
8
|
+
// src/cli/find.ts
|
|
9
|
+
/**
|
|
10
|
+
* Finding what a task carries: a recording or a voice clip, by a task's ID, a recording's ID, a replay URL or a path,
|
|
11
|
+
* kept under a `.deictic/` near here or downloaded from the board. And the tools outside deictic some commands run
|
|
12
|
+
* (ffmpeg, the project's Playwright).
|
|
13
|
+
*/
|
|
14
|
+
const TASK = /^#?\d+$/;
|
|
15
|
+
const parsed = (path) => JSON.parse(readFileSync(path, "utf8"));
|
|
16
|
+
/** An attachment of a task, written to a temporary folder: its path. */
|
|
17
|
+
function fetched(root, name) {
|
|
18
|
+
const file = root.attachments.find((a) => a.name === name);
|
|
19
|
+
if (file === void 0) fail(`Task #${root.id} has no ${name}.`);
|
|
20
|
+
const path = join(mkdtempSync(join(tmpdir(), "deictic-")), file.name);
|
|
21
|
+
download(file, path);
|
|
22
|
+
return path;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A recording, with where it came from. `ref` is a task's ID (its first recording, or the `nth`), a replay or
|
|
26
|
+
* recording URL, a recording's ID kept under a `.deictic/`, or a path.
|
|
27
|
+
*/
|
|
28
|
+
async function loadRecording(ref, nth = 1) {
|
|
29
|
+
if (ref === void 0) fail("Name a recording: a task (68), a replay URL, a recording ID or a JSON file.");
|
|
30
|
+
if (TASK.test(ref)) {
|
|
31
|
+
const root = task(ref);
|
|
32
|
+
const files = root.attachments.filter((a) => /^recording-.*\.json$/.test(a.name));
|
|
33
|
+
const file = files[nth - 1];
|
|
34
|
+
if (file === void 0) fail(`Task #${root.id} has ${files.length} recording(s), not a ${nth}th.`);
|
|
35
|
+
const id = file.name.slice(10, -5);
|
|
36
|
+
const replay = new RegExp(`https?://\\S+/replay/${id}`).exec(root.text)?.[0];
|
|
37
|
+
return {
|
|
38
|
+
kept: parsed(fetched(root, file.name)),
|
|
39
|
+
id,
|
|
40
|
+
replay,
|
|
41
|
+
task: root
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
if (/^https?:/.test(ref)) {
|
|
45
|
+
const url = new URL(ref);
|
|
46
|
+
const id = url.pathname.split("/").at(-1) ?? "";
|
|
47
|
+
const json = new URL(url.pathname.replace(/\/(replay|recording)\/[^/]+$/, `/recording/${id}`), url);
|
|
48
|
+
const res = await fetch(json);
|
|
49
|
+
if (!res.ok) fail(`${json.href}: ${res.status} ${await res.text()}`);
|
|
50
|
+
return {
|
|
51
|
+
kept: await res.json(),
|
|
52
|
+
id,
|
|
53
|
+
replay: new URL(json.pathname.replace(/\/recording\//, "/replay/"), url).href
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
if (existsSync(ref)) return {
|
|
57
|
+
kept: parsed(ref),
|
|
58
|
+
id: ref.replace(/^.*[\\/]|\.json$/g, "")
|
|
59
|
+
};
|
|
60
|
+
for (const dir of deicticDirs()) {
|
|
61
|
+
const path = join(dir, "recordings", `${ref}.json`);
|
|
62
|
+
if (existsSync(path)) return {
|
|
63
|
+
kept: parsed(path),
|
|
64
|
+
id: ref
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
return fail(`No recording ${ref} in ${deicticDirs().join(", ") || "any .deictic/ near here"}: name its task or replay URL instead.`);
|
|
68
|
+
}
|
|
69
|
+
/** A voice clip kept under a `.deictic/` near here, by its ID. */
|
|
70
|
+
function keptClip(id) {
|
|
71
|
+
for (const dir of deicticDirs()) {
|
|
72
|
+
const voice = join(dir, "voice");
|
|
73
|
+
const name = existsSync(voice) ? readdirSync(voice).find((f) => f.startsWith(`${id}.`)) : void 0;
|
|
74
|
+
if (name !== void 0) return join(voice, name);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** A voice clip's audio as a file: kept under a `.deictic/`, or downloaded from `from`. */
|
|
78
|
+
function voiceFile(id, from) {
|
|
79
|
+
const kept = keptClip(id);
|
|
80
|
+
if (kept !== void 0) return kept;
|
|
81
|
+
const file = from?.attachments.find((a) => a.name.startsWith(`voice-${id}.`));
|
|
82
|
+
if (from === void 0 || file === void 0) fail(`No voice clip ${id} here${from ? ` or on task #${from.id}` : ""}.`);
|
|
83
|
+
return fetched(from, file.name);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The voice clips `ref` names: a task (every recording's clips and its voice notes), a recording as `loadRecording`
|
|
87
|
+
* takes one, or a clip's ID.
|
|
88
|
+
*/
|
|
89
|
+
async function voiceClips(ref) {
|
|
90
|
+
if (ref === void 0) fail("Name a task, a recording or a voice clip.");
|
|
91
|
+
const clips = [];
|
|
92
|
+
if (TASK.test(ref)) {
|
|
93
|
+
const root = task(ref);
|
|
94
|
+
const recordings = root.attachments.filter((a) => /^recording-.*\.json$/.test(a.name));
|
|
95
|
+
const inRecordings = /* @__PURE__ */ new Set();
|
|
96
|
+
for (let n = 1; n <= recordings.length; n++) {
|
|
97
|
+
const { kept, id } = await loadRecording(ref, n);
|
|
98
|
+
for (const c of kept.voice ?? []) {
|
|
99
|
+
inRecordings.add(c.id);
|
|
100
|
+
clips.push({
|
|
101
|
+
id: c.id,
|
|
102
|
+
file: voiceFile(c.id, root),
|
|
103
|
+
at: c.at,
|
|
104
|
+
recording: id
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
for (const a of root.attachments) {
|
|
109
|
+
const id = /^voice-(.+)\.\w+$/.exec(a.name)?.[1];
|
|
110
|
+
if (id !== void 0 && !inRecordings.has(id)) clips.push({
|
|
111
|
+
id,
|
|
112
|
+
file: voiceFile(id, root),
|
|
113
|
+
at: 0
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
} else if (!/^https?:/.test(ref) && !existsSync(ref) && keptClip(ref) !== void 0) clips.push({
|
|
117
|
+
id: ref,
|
|
118
|
+
file: voiceFile(ref),
|
|
119
|
+
at: 0
|
|
120
|
+
});
|
|
121
|
+
else {
|
|
122
|
+
const { kept, id } = await loadRecording(ref);
|
|
123
|
+
for (const c of kept.voice ?? []) clips.push({
|
|
124
|
+
id: c.id,
|
|
125
|
+
file: voiceFile(c.id),
|
|
126
|
+
at: c.at,
|
|
127
|
+
recording: id
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
if (clips.length === 0) fail(`No voice on ${ref}.`);
|
|
131
|
+
return clips;
|
|
132
|
+
}
|
|
133
|
+
/** Runs ffmpeg, which reads what MediaRecorder makes, and answers its log (stderr) and what it wrote to stdout. */
|
|
134
|
+
function ffmpeg(args) {
|
|
135
|
+
const run = spawnSync("ffmpeg", [
|
|
136
|
+
"-hide_banner",
|
|
137
|
+
"-nostats",
|
|
138
|
+
...args
|
|
139
|
+
], { maxBuffer: 1 << 30 });
|
|
140
|
+
if (run.error) fail("Needs ffmpeg on the PATH (https://ffmpeg.org/download.html).");
|
|
141
|
+
return {
|
|
142
|
+
stdout: run.stdout,
|
|
143
|
+
log: run.stderr.toString("utf8")
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** The project's own copy of a package deictic doesn't bring (Playwright, either of its names), from here. */
|
|
147
|
+
async function fromProject(...names) {
|
|
148
|
+
const project = createRequire(join(process.cwd(), "package.json"));
|
|
149
|
+
for (const name of names) try {
|
|
150
|
+
return await import(pathToFileURL(project.resolve(name)).href);
|
|
151
|
+
} catch {}
|
|
152
|
+
return fail(`Needs ${names.join(" or ")} in the project: npm install -D ${names[0]}`);
|
|
153
|
+
}
|
|
154
|
+
export { voiceClips as i, fromProject as n, loadRecording as r, ffmpeg as t };
|
|
155
|
+
|
|
156
|
+
//# sourceMappingURL=find.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"find.js","names":[],"sources":["../../src/cli/find.ts"],"sourcesContent":["/**\n * Finding what a task carries: a recording or a voice clip, by a task's ID, a recording's ID, a replay URL or a path,\n * kept under a `.deictic/` near here or downloaded from the board. And the tools outside deictic some commands run\n * (ffmpeg, the project's Playwright).\n */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, mkdtempSync, readdirSync, readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport type { Kept } from '#src/plugins/recordings/index.ts';\n\nimport { deicticDirs, download, fail, type Message, task } from './board.ts';\n\nconst TASK = /^#?\\d+$/;\n\nexport interface Found {\n kept: Kept;\n id: string;\n /** Where it replays, where that's known. */\n replay?: string;\n /** The task it's attached to, where it was found by one. */\n task?: Message;\n}\n\nconst parsed = (path: string) => JSON.parse(readFileSync(path, 'utf8')) as Kept;\n\n/** An attachment of a task, written to a temporary folder: its path. */\nfunction fetched(root: Message, name: string): string {\n const file = root.attachments.find((a) => a.name === name);\n if (file === undefined) fail(`Task #${root.id} has no ${name}.`);\n const path = join(mkdtempSync(join(tmpdir(), 'deictic-')), file.name);\n download(file, path);\n return path;\n}\n\n/**\n * A recording, with where it came from. `ref` is a task's ID (its first recording, or the `nth`), a replay or\n * recording URL, a recording's ID kept under a `.deictic/`, or a path.\n */\nexport async function loadRecording(ref: string | undefined, nth = 1): Promise<Found> {\n if (ref === undefined) fail('Name a recording: a task (68), a replay URL, a recording ID or a JSON file.');\n if (TASK.test(ref)) {\n const root = task(ref);\n const files = root.attachments.filter((a) => /^recording-.*\\.json$/.test(a.name));\n const file = files[nth - 1];\n if (file === undefined) fail(`Task #${root.id} has ${files.length} recording(s), not a ${nth}th.`);\n const id = file.name.slice('recording-'.length, -'.json'.length);\n const replay = new RegExp(`https?://\\\\S+/replay/${id}`).exec(root.text)?.[0];\n return { kept: parsed(fetched(root, file.name)), id, replay, task: root };\n }\n if (/^https?:/.test(ref)) {\n const url = new URL(ref);\n const id = url.pathname.split('/').at(-1) ?? '';\n const json = new URL(url.pathname.replace(/\\/(replay|recording)\\/[^/]+$/, `/recording/${id}`), url);\n const res = await fetch(json);\n if (!res.ok) fail(`${json.href}: ${res.status} ${await res.text()}`);\n return { kept: (await res.json()) as Kept, id, replay: new URL(json.pathname.replace(/\\/recording\\//, '/replay/'), url).href };\n }\n if (existsSync(ref)) return { kept: parsed(ref), id: ref.replace(/^.*[\\\\/]|\\.json$/g, '') };\n for (const dir of deicticDirs()) {\n const path = join(dir, 'recordings', `${ref}.json`);\n if (existsSync(path)) return { kept: parsed(path), id: ref };\n }\n return fail(`No recording ${ref} in ${deicticDirs().join(', ') || 'any .deictic/ near here'}: name its task or replay URL instead.`);\n}\n\n/** A voice clip kept under a `.deictic/` near here, by its ID. */\nfunction keptClip(id: string): string | undefined {\n for (const dir of deicticDirs()) {\n const voice = join(dir, 'voice');\n const name = existsSync(voice) ? readdirSync(voice).find((f) => f.startsWith(`${id}.`)) : undefined;\n if (name !== undefined) return join(voice, name);\n }\n return undefined;\n}\n\n/** A voice clip's audio as a file: kept under a `.deictic/`, or downloaded from `from`. */\nfunction voiceFile(id: string, from?: Message): string {\n const kept = keptClip(id);\n if (kept !== undefined) return kept;\n const file = from?.attachments.find((a) => a.name.startsWith(`voice-${id}.`));\n if (from === undefined || file === undefined) fail(`No voice clip ${id} here${from ? ` or on task #${from.id}` : ''}.`);\n return fetched(from, file.name);\n}\n\nexport interface Clip {\n id: string;\n file: string;\n /** Where it starts in its recording, or 0 for a voice note on its own. */\n at: number;\n recording?: string;\n}\n\n/**\n * The voice clips `ref` names: a task (every recording's clips and its voice notes), a recording as `loadRecording`\n * takes one, or a clip's ID.\n */\nexport async function voiceClips(ref: string | undefined): Promise<Clip[]> {\n if (ref === undefined) fail('Name a task, a recording or a voice clip.');\n const clips: Clip[] = [];\n if (TASK.test(ref)) {\n const root = task(ref);\n const recordings = root.attachments.filter((a) => /^recording-.*\\.json$/.test(a.name));\n const inRecordings = new Set<string>();\n for (let n = 1; n <= recordings.length; n++) {\n const { kept, id } = await loadRecording(ref, n);\n for (const c of kept.voice ?? []) {\n inRecordings.add(c.id);\n clips.push({ id: c.id, file: voiceFile(c.id, root), at: c.at, recording: id });\n }\n }\n for (const a of root.attachments) {\n const id = /^voice-(.+)\\.\\w+$/.exec(a.name)?.[1];\n if (id !== undefined && !inRecordings.has(id)) clips.push({ id, file: voiceFile(id, root), at: 0 });\n }\n } else if (!/^https?:/.test(ref) && !existsSync(ref) && keptClip(ref) !== undefined) {\n clips.push({ id: ref, file: voiceFile(ref), at: 0 });\n } else {\n const { kept, id } = await loadRecording(ref);\n for (const c of kept.voice ?? []) clips.push({ id: c.id, file: voiceFile(c.id), at: c.at, recording: id });\n }\n if (clips.length === 0) fail(`No voice on ${ref}.`);\n return clips;\n}\n\n/** Runs ffmpeg, which reads what MediaRecorder makes, and answers its log (stderr) and what it wrote to stdout. */\nexport function ffmpeg(args: string[]): { stdout: Buffer; log: string } {\n const run = spawnSync('ffmpeg', ['-hide_banner', '-nostats', ...args], { maxBuffer: 1 << 30 });\n if (run.error) fail('Needs ffmpeg on the PATH (https://ffmpeg.org/download.html).');\n return { stdout: run.stdout, log: run.stderr.toString('utf8') };\n}\n\n/** The project's own copy of a package deictic doesn't bring (Playwright, either of its names), from here. */\nexport async function fromProject<T>(...names: string[]): Promise<T> {\n const project = createRequire(join(process.cwd(), 'package.json'));\n for (const name of names) {\n try {\n return (await import(pathToFileURL(project.resolve(name)).href)) as T;\n } catch {\n // Not this one: the next name.\n }\n }\n return fail(`Needs ${names.join(' or ')} in the project: npm install -D ${names[0]}`);\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAA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M,WAAW,GAAG,KAAK,eAAe,IAAI,EAAE;CAClD,OAAO;AACT;;AAGA,SAAgB,OAAO,MAAiD;CACtE,MAAM,MAAM,UAAU,UAAU;EAAC;EAAgB;EAAY,GAAG;CAAI,GAAG,EAAE,WAAW,KAAK,GAAG,CAAC;CAC7F,IAAI,IAAI,OAAO,KAAK,8DAA8D;CAClF,OAAO;EAAE,QAAQ,IAAI;EAAQ,KAAK,IAAI,OAAO,SAAS,MAAM;CAAE;AAChE;;AAGA,eAAsB,YAAe,GAAG,OAA6B;CACnE,MAAM,UAAU,cAAc,KAAK,QAAQ,IAAI,GAAG,cAAc,CAAC;CACjE,KAAK,MAAM,QAAQ,OACjB,IAAI;EACF,OAAQ,MAAM,OAAO,cAAc,QAAQ,QAAQ,IAAI,CAAC,CAAC,CAAC;CAC5D,QAAQ,CAER;CAEF,OAAO,KAAK,SAAS,MAAM,KAAK,MAAM,EAAE,kCAAkC,MAAM,IAAI;AACtF"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { a as clock, l as fail, u as parseArgs } from "./board.js";
|
|
5
|
+
import { n as fromProject, r as loadRecording } from "./find.js";
|
|
6
|
+
// src/cli/frame.ts
|
|
7
|
+
/**
|
|
8
|
+
* `deictic frame`: screenshots of a recording at moments of it, as its replay page shows them (marks and pointer
|
|
9
|
+
* included), at the recorded viewport's size. By default: just after each change to the marks, and the end. Needs
|
|
10
|
+
* the dev server running (it serves the replay) and Playwright in the project.
|
|
11
|
+
*/
|
|
12
|
+
const usage = "frame <task | replay URL | recording ID | file> [--at 4.2 ...] [--every 2] [--out dir] [--base url] PNGs of a recording";
|
|
13
|
+
async function run(args) {
|
|
14
|
+
const { values, positionals } = parseArgs(args, {
|
|
15
|
+
nth: {
|
|
16
|
+
type: "string",
|
|
17
|
+
default: "1"
|
|
18
|
+
},
|
|
19
|
+
at: {
|
|
20
|
+
type: "string",
|
|
21
|
+
multiple: true
|
|
22
|
+
},
|
|
23
|
+
every: { type: "string" },
|
|
24
|
+
out: { type: "string" },
|
|
25
|
+
base: { type: "string" }
|
|
26
|
+
});
|
|
27
|
+
const { kept, id, replay } = await loadRecording(positionals[0], Number(values.nth));
|
|
28
|
+
const page = values.base === void 0 ? replay ?? `${new URL(kept.page).origin}/__deictic/plugins/recordings/replay/${id}` : `${values.base.replace(/\/$/, "")}/__deictic/plugins/recordings/replay/${id}`;
|
|
29
|
+
const events = kept.events;
|
|
30
|
+
const t0 = events[0]?.timestamp ?? 0;
|
|
31
|
+
const end = kept.duration / 1e3;
|
|
32
|
+
let times = (values.at ?? []).map(Number);
|
|
33
|
+
if (values.every !== void 0) for (let t = 0; t <= end; t += Number(values.every)) times.push(t);
|
|
34
|
+
if (times.length === 0) times = [...events.filter((e) => e.type === 5 && e.data.tag === "deictic.annotations" && (e.data.payload?.svg ?? "") !== "").map((e) => (e.timestamp - t0 + 50) / 1e3), end];
|
|
35
|
+
times = [...new Set(times.map((t) => Math.min(Math.max(0, t), end)))].sort((a, b) => a - b);
|
|
36
|
+
if (times.some((t) => !Number.isFinite(t))) fail("--at and --every take seconds: --at 4.2");
|
|
37
|
+
const out = resolve(values.out ?? join(tmpdir(), "deictic-frames", id));
|
|
38
|
+
mkdirSync(out, { recursive: true });
|
|
39
|
+
const playwright = await fromProject("playwright-core", "playwright");
|
|
40
|
+
let browser;
|
|
41
|
+
for (const channel of [
|
|
42
|
+
void 0,
|
|
43
|
+
"chrome",
|
|
44
|
+
"msedge"
|
|
45
|
+
]) try {
|
|
46
|
+
browser = await playwright.chromium.launch(channel === void 0 ? {} : { channel });
|
|
47
|
+
break;
|
|
48
|
+
} catch {}
|
|
49
|
+
if (browser === void 0) fail("No Chromium to launch: npx playwright install chromium, or install Chrome or Edge.");
|
|
50
|
+
try {
|
|
51
|
+
const view = await browser.newPage({ viewport: kept.viewport });
|
|
52
|
+
for (const t of times) {
|
|
53
|
+
const url = new URL(page);
|
|
54
|
+
url.searchParams.set("t", t.toFixed(2));
|
|
55
|
+
url.searchParams.set("bare", "");
|
|
56
|
+
const res = await view.goto(url.href).catch((e) => e instanceof Error ? e.message.split("\n")[0] : String(e));
|
|
57
|
+
if (typeof res === "string" || !res?.ok()) {
|
|
58
|
+
const why = typeof res === "string" ? res : String(res?.status());
|
|
59
|
+
await browser.close();
|
|
60
|
+
fail(`${url.href}: ${why}. Is the dev server running? Start it, or pass --base with its URL.`);
|
|
61
|
+
}
|
|
62
|
+
await view.waitForSelector("body[data-ready]", { timeout: 15e3 });
|
|
63
|
+
await view.waitForLoadState("networkidle").catch(() => {});
|
|
64
|
+
await view.waitForTimeout(200);
|
|
65
|
+
const path = join(out, `${String(Math.round(t * 1e3)).padStart(6, "0")}.png`);
|
|
66
|
+
await view.screenshot({ path });
|
|
67
|
+
console.log(`${clock(t * 1e3).padStart(6)} ${path}`);
|
|
68
|
+
}
|
|
69
|
+
} finally {
|
|
70
|
+
await browser.close();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export { run, usage };
|
|
74
|
+
|
|
75
|
+
//# sourceMappingURL=frame.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"frame.js","names":[],"sources":["../../src/cli/frame.ts"],"sourcesContent":["/**\n * `deictic frame`: screenshots of a recording at moments of it, as its replay page shows them (marks and pointer\n * included), at the recorded viewport's size. By default: just after each change to the marks, and the end. Needs\n * the dev server running (it serves the replay) and Playwright in the project.\n */\nimport { mkdirSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\nimport type { Browser, chromium } from 'playwright-core';\n\nimport { clock, fail, parseArgs } from './board.ts';\nimport { fromProject, loadRecording } from './find.ts';\n\nexport const usage =\n 'frame <task | replay URL | recording ID | file> [--at 4.2 ...] [--every 2] [--out dir] [--base url] PNGs of a recording';\n\ninterface Marks {\n type: number;\n timestamp: number;\n data: { tag?: string; payload?: { svg?: string } };\n}\n\nexport async function run(args: string[]): Promise<void> {\n const { values, positionals } = parseArgs(args, {\n nth: { type: 'string', default: '1' },\n at: { type: 'string', multiple: true },\n every: { type: 'string' },\n out: { type: 'string' },\n base: { type: 'string' },\n });\n const { kept, id, replay } = await loadRecording(positionals[0], Number(values.nth));\n // The replay is served by the dev server that recorded it, under deictic's routes.\n const page =\n values.base === undefined\n ? (replay ?? `${new URL(kept.page).origin}/__deictic/plugins/recordings/replay/${id}`)\n : `${values.base.replace(/\\/$/, '')}/__deictic/plugins/recordings/replay/${id}`;\n\n const events = kept.events as Marks[];\n const t0 = events[0]?.timestamp ?? 0;\n const end = kept.duration / 1000;\n let times = (values.at ?? []).map(Number);\n if (values.every !== undefined) for (let t = 0; t <= end; t += Number(values.every)) times.push(t);\n if (times.length === 0) {\n // Just after each change to the marks, so it's drawn, then the end.\n const marks = events.filter((e) => e.type === 5 && e.data.tag === 'deictic.annotations' && (e.data.payload?.svg ?? '') !== '');\n times = [...marks.map((e) => (e.timestamp - t0 + 50) / 1000), end];\n }\n times = [...new Set(times.map((t) => Math.min(Math.max(0, t), end)))].sort((a, b) => a - b);\n if (times.some((t) => !Number.isFinite(t))) fail('--at and --every take seconds: --at 4.2');\n\n const out = resolve(values.out ?? join(tmpdir(), 'deictic-frames', id));\n mkdirSync(out, { recursive: true });\n\n const playwright = await fromProject<{ chromium: typeof chromium }>('playwright-core', 'playwright');\n let browser: Browser | undefined;\n for (const channel of [undefined, 'chrome', 'msedge']) {\n try {\n browser = await playwright.chromium.launch(channel === undefined ? {} : { channel });\n break;\n } catch {\n // Not this one: the next.\n }\n }\n if (browser === undefined) fail('No Chromium to launch: npx playwright install chromium, or install Chrome or Edge.');\n try {\n // `bare`: the replay alone, at the recorded size, so a window that size shows it 1:1.\n const view = await browser.newPage({ viewport: kept.viewport });\n for (const t of times) {\n const url = new URL(page);\n url.searchParams.set('t', t.toFixed(2));\n url.searchParams.set('bare', '');\n const res = await view.goto(url.href).catch((e: unknown) => (e instanceof Error ? e.message.split('\\n')[0] : String(e)));\n if (typeof res === 'string' || !res?.ok()) {\n const why = typeof res === 'string' ? res : String(res?.status());\n await browser.close();\n fail(`${url.href}: ${why}. Is the dev server running? Start it, or pass --base with its URL.`);\n }\n await view.waitForSelector('body[data-ready]', { timeout: 15_000 });\n // The replayed page's images and fonts.\n await view.waitForLoadState('networkidle').catch(() => {});\n await view.waitForTimeout(200);\n const path = join(out, `${String(Math.round(t * 1000)).padStart(6, '0')}.png`);\n await view.screenshot({ path });\n console.log(`${clock(t * 1000).padStart(6)} ${path}`);\n }\n } finally {\n await browser.close();\n }\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAa,QACX;AAQF,eAAsB,IAAI,MAA+B;CACvD,MAAM,EAAE,QAAQ,gBAAgB,UAAU,MAAM;EAC9C,KAAK;GAAE,MAAM;GAAU,SAAS;EAAI;EACpC,IAAI;GAAE,MAAM;GAAU,UAAU;EAAK;EACrC,OAAO,EAAE,MAAM,SAAS;EACxB,KAAK,EAAE,MAAM,SAAS;EACtB,MAAM,EAAE,MAAM,SAAS;CACzB,CAAC;CACD,MAAM,EAAE,MAAM,IAAI,WAAW,MAAM,cAAc,YAAY,IAAI,OAAO,OAAO,GAAG,CAAC;CAEnF,MAAM,OACJ,OAAO,SAAS,KAAA,IACX,UAAU,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,OAAO,uCAAuC,OAC/E,GAAG,OAAO,KAAK,QAAQ,OAAO,EAAE,EAAE,uCAAuC;CAE/E,MAAM,SAAS,KAAK;CACpB,MAAM,KAAK,OAAO,EAAE,EAAE,aAAa;CACnC,MAAM,MAAM,KAAK,WAAW;CAC5B,IAAI,SAAS,OAAO,MAAM,CAAC,EAAA,CAAG,IAAI,MAAM;CACxC,IAAI,OAAO,UAAU,KAAA,GAAW,KAAK,IAAI,IAAI,GAAG,KAAK,KAAK,KAAK,OAAO,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;CAC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AAO,CAAC,CAAE;GACvH,IAAI,OAAO,QAAQ,YAAY,CAAC,KAAK,GAAG,GAAG;IACzC,MAAM,MAAM,OAAO,QAAQ,WAAW,MAAM,OAAO,KAAK,OAAO,CAAC;IAChE,MAAM,QAAQ,MAAM;IACpB,KAAK,GAAG,IAAI,KAAK,IAAI,IAAI,oEAAoE;GAC/F;GACA,MAAM,KAAK,gBAAgB,oBAAoB,EAAE,SAAS,KAAO,CAAC;GAElE,MAAM,KAAK,iBAAiB,aAAa,CAAC,CAAC,YAAY,CAAC,CAAC;GACzD,MAAM,KAAK,eAAe,GAAG;GAC7B,MAAM,OAAO,KAAK,KAAK,GAAG,OAAO,KAAK,MAAM,IAAI,GAAI,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG,EAAE,KAAK;GAC7E,MAAM,KAAK,WAAW,EAAE,KAAK,CAAC;GAC9B,QAAQ,IAAI,GAAG,MAAM,IAAI,GAAI,CAAC,CAAC,SAAS,CAAC,EAAE,IAAI,MAAM;EACvD;CACF,UAAU;EACR,MAAM,QAAQ,MAAM;CACtB;AACF"}
|
package/dist/shared/index.d.ts
CHANGED
|
@@ -97,6 +97,11 @@ interface ServerPlugin<Model = unknown, Op = unknown, Record = unknown, Api = un
|
|
|
97
97
|
shortcut?: Shortcut;
|
|
98
98
|
/** The plugins it can't do without, by name: the dev server won't start without them. */
|
|
99
99
|
needs?: string[];
|
|
100
|
+
/**
|
|
101
|
+
* The packages it imports that the project installs itself (optional peers), by name: as the dev server starts,
|
|
102
|
+
* it says how to install any that's missing, rather than failing when first used.
|
|
103
|
+
*/
|
|
104
|
+
packages?: string[];
|
|
100
105
|
/** Runs once, as the dev server starts and before it answers anything. Answers the plugin's API to the others. */
|
|
101
106
|
setup?(context: ServerContext): Maybe<Api>;
|
|
102
107
|
/** Routes of its own, by their first segment under `/__deictic/plugins/<name>/`. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/shortcut.ts","../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