deictic 0.0.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +167 -0
- package/dist/annotations/client.d.ts +4 -0
- package/dist/annotations/client.d.ts.map +1 -0
- package/dist/annotations/client.js +497 -0
- package/dist/annotations/client.js.map +1 -0
- package/dist/annotations/index.d.ts +110 -0
- package/dist/annotations/index.d.ts.map +1 -0
- package/dist/annotations/index.js +22 -0
- package/dist/annotations/index.js.map +1 -0
- package/dist/astro.d.ts +29 -0
- package/dist/astro.d.ts.map +1 -0
- package/dist/astro.js +24 -0
- package/dist/astro.js.map +1 -0
- package/dist/bun.d.ts +12 -0
- package/dist/bun.d.ts.map +1 -0
- package/dist/bun.js +67 -0
- package/dist/bun.js.map +1 -0
- package/dist/client/index.d.ts +95 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +1333 -0
- package/dist/client/index.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/loader.d.ts +15 -0
- package/dist/loader.d.ts.map +1 -0
- package/dist/loader.js +17 -0
- package/dist/loader.js.map +1 -0
- package/dist/next.d.ts +17 -0
- package/dist/next.d.ts.map +1 -0
- package/dist/next.js +150 -0
- package/dist/next.js.map +1 -0
- package/dist/recommended/index.d.ts +25 -0
- package/dist/recommended/index.d.ts.map +1 -0
- package/dist/recommended/index.js +19 -0
- package/dist/recommended/index.js.map +1 -0
- package/dist/recordings/client.d.ts +4 -0
- package/dist/recordings/client.d.ts.map +1 -0
- package/dist/recordings/client.js +376 -0
- package/dist/recordings/client.js.map +1 -0
- package/dist/recordings/index.d.ts +2 -0
- package/dist/recordings/index.js +3 -0
- package/dist/screenshots/client.d.ts +23 -0
- package/dist/screenshots/client.d.ts.map +1 -0
- package/dist/screenshots/client.js +76 -0
- package/dist/screenshots/client.js.map +1 -0
- package/dist/screenshots/dom.d.ts +4 -0
- package/dist/screenshots/dom.d.ts.map +1 -0
- package/dist/screenshots/dom.js +92 -0
- package/dist/screenshots/dom.js.map +1 -0
- package/dist/screenshots/index.d.ts +2 -0
- package/dist/screenshots/index.js +98 -0
- package/dist/screenshots/index.js.map +1 -0
- package/dist/screenshots/rrweb.d.ts +9 -0
- package/dist/screenshots/rrweb.d.ts.map +1 -0
- package/dist/screenshots/rrweb.js +60 -0
- package/dist/screenshots/rrweb.js.map +1 -0
- package/dist/shared/endpoints.js +354 -0
- package/dist/shared/endpoints.js.map +1 -0
- package/dist/shared/index.d.ts +226 -0
- package/dist/shared/index.d.ts.map +1 -0
- package/dist/shared/index2.d.ts +98 -0
- package/dist/shared/index2.d.ts.map +1 -0
- package/dist/shared/index3.d.ts +86 -0
- package/dist/shared/index3.d.ts.map +1 -0
- package/dist/shared/index4.d.ts +184 -0
- package/dist/shared/index4.d.ts.map +1 -0
- package/dist/shared/index5.d.ts +70 -0
- package/dist/shared/index5.d.ts.map +1 -0
- package/dist/shared/integration.d.ts +20 -0
- package/dist/shared/integration.d.ts.map +1 -0
- package/dist/shared/integration.js +279 -0
- package/dist/shared/integration.js.map +1 -0
- package/dist/shared/kept.js +23 -0
- package/dist/shared/kept.js.map +1 -0
- package/dist/shared/marks.js +14 -0
- package/dist/shared/marks.js.map +1 -0
- package/dist/shared/playwright.js +105 -0
- package/dist/shared/playwright.js.map +1 -0
- package/dist/shared/recordings.js +246 -0
- package/dist/shared/recordings.js.map +1 -0
- package/dist/shared/shortcut.js +63 -0
- package/dist/shared/shortcut.js.map +1 -0
- package/dist/shared/tasks.js +521 -0
- package/dist/shared/tasks.js.map +1 -0
- package/dist/shared/waveform.js +93 -0
- package/dist/shared/waveform.js.map +1 -0
- package/dist/tailwind/client.d.ts +4 -0
- package/dist/tailwind/client.d.ts.map +1 -0
- package/dist/tailwind/client.js +613 -0
- package/dist/tailwind/client.js.map +1 -0
- package/dist/tailwind/index.d.ts +2 -0
- package/dist/tailwind/index.js +557 -0
- package/dist/tailwind/index.js.map +1 -0
- package/dist/tasks/client.d.ts +6 -0
- package/dist/tasks/client.d.ts.map +1 -0
- package/dist/tasks/client.js +642 -0
- package/dist/tasks/client.js.map +1 -0
- package/dist/tasks/index.d.ts +2 -0
- package/dist/tasks/index.js +1 -0
- package/dist/vite.d.ts +16 -0
- package/dist/vite.d.ts.map +1 -0
- package/dist/vite.js +61 -0
- package/dist/vite.js.map +1 -0
- package/dist/voice/client.d.ts +4 -0
- package/dist/voice/client.d.ts.map +1 -0
- package/dist/voice/client.js +66 -0
- package/dist/voice/client.js.map +1 -0
- package/dist/voice/index.d.ts +47 -0
- package/dist/voice/index.d.ts.map +1 -0
- package/dist/voice/index.js +74 -0
- package/dist/voice/index.js.map +1 -0
- package/dist/webpack.d.ts +50 -0
- package/dist/webpack.d.ts.map +1 -0
- package/dist/webpack.js +78 -0
- package/dist/webpack.js.map +1 -0
- package/package.json +307 -7
- package/skills/deictic/SKILL.md +47 -0
- package/skills/deictic/references/install.md +96 -0
- package/skills/deictic/references/recordings.md +83 -0
- package/skills/deictic/references/tasks.md +79 -0
- package/skills/deictic/references/watch.md +43 -0
- package/skills/deictic/scripts/frame.mjs +62 -0
- package/skills/deictic/scripts/lib.mjs +211 -0
- package/skills/deictic/scripts/recording.mjs +186 -0
- package/skills/deictic/scripts/task.mjs +84 -0
- package/skills/deictic/scripts/transcribe.mjs +93 -0
- package/skills/deictic/scripts/voice.mjs +50 -0
- package/skills/deictic/scripts/watch.mjs +51 -0
- package/src/astro.ts +34 -0
- package/src/bun.ts +79 -0
- package/src/client/index.ts +846 -0
- package/src/client/lightbox.ts +256 -0
- package/src/client/style.ts +243 -0
- package/src/client/tooltip.ts +78 -0
- package/src/client/waveform.ts +98 -0
- package/src/index.ts +247 -0
- package/src/loader.ts +28 -0
- package/src/next.ts +133 -0
- package/src/plugins/annotations/client.ts +301 -0
- package/src/plugins/annotations/draw.ts +169 -0
- package/src/plugins/annotations/index.ts +105 -0
- package/src/plugins/annotations/svg.ts +61 -0
- package/src/plugins/recommended/index.ts +35 -0
- package/src/plugins/recordings/client.ts +316 -0
- package/src/plugins/recordings/index.ts +175 -0
- package/src/plugins/recordings/marks.ts +11 -0
- package/src/plugins/recordings/ours.ts +70 -0
- package/src/plugins/recordings/replay.ts +165 -0
- package/src/plugins/screenshots/client.ts +64 -0
- package/src/plugins/screenshots/dom.ts +79 -0
- package/src/plugins/screenshots/index.ts +194 -0
- package/src/plugins/screenshots/playwright.ts +119 -0
- package/src/plugins/screenshots/rrweb.ts +45 -0
- package/src/plugins/tailwind/catalog.ts +396 -0
- package/src/plugins/tailwind/client.ts +669 -0
- package/src/plugins/tailwind/index.ts +267 -0
- package/src/plugins/tasks/client.ts +622 -0
- package/src/plugins/tasks/index.ts +557 -0
- package/src/plugins/tasks/local.ts +170 -0
- package/src/plugins/voice/client.ts +58 -0
- package/src/plugins/voice/index.ts +114 -0
- package/src/shortcut.ts +83 -0
- package/src/tools/astro.ts +81 -0
- package/src/tools/editor.ts +22 -0
- package/src/tools/endpoints.ts +163 -0
- package/src/tools/history.ts +203 -0
- package/src/tools/integration.ts +108 -0
- package/src/tools/kept.ts +21 -0
- package/src/tools/locate.ts +94 -0
- package/src/tools/plugins.ts +41 -0
- package/src/tools/source.ts +72 -0
- package/src/vite.ts +81 -0
- package/src/webpack.ts +107 -0
- package/index.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dom.js","names":[],"sources":["../../src/plugins/screenshots/dom.ts"],"sourcesContent":["/**\n * The `dom()` renderer's page half: draws the page in the page from its DOM with `modern-screenshot`\n * (imported on the first shot), so it needs no server, but text may lay out a little differently than\n * the page's. Masking changes only the copy that's drawn, never the page.\n */\nimport { boxOf, notOurs, screenshotsClient } from './client.ts';\nimport type { ResolvedMasking } from './index.ts';\n\nconst BLANK = '#d4d4d8';\n\nconst selector = (className: string, extra: string | undefined) => [`.${CSS.escape(className)}`, ...(extra ? [extra] : [])].join(', ');\n\n/**\n * Hides in the copy 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 */\nfunction 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\n/** Draws an SVG over the whole canvas, which is the area it was made for at the canvas's scale. */\nasync function drawOver(canvas: HTMLCanvasElement, svg: string | undefined): Promise<HTMLCanvasElement> {\n if (svg === undefined) return canvas;\n const image = new Image();\n image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;\n await image.decode();\n canvas.getContext('2d')?.drawImage(image, 0, 0, canvas.width, canvas.height);\n return canvas;\n}\n\nexport default screenshotsClient(async (element, { area, masking, overlay }) => {\n const { domToCanvas } = await import('modern-screenshot').catch((e: unknown) => {\n throw new Error('the dom() renderer needs modern-screenshot: add it to your devDependencies', { cause: e });\n });\n // Sharp on a high-density screen, without drawing a long page at more than twice its size.\n const scale = Math.min(devicePixelRatio, 2);\n const options = { filter: notOurs, scale, onCloneNode: (copy: Node) => mask(copy, masking) };\n const box = boxOf(element, area);\n const toPng = (canvas: HTMLCanvasElement) =>\n new Promise<Blob>((done, fail) =>\n canvas.toBlob((blob) => (blob === null ? fail(new Error('screenshots: the page drew nothing')) : done(blob)), 'image/png'),\n );\n if (area === 'element') {\n const { x, y, width, height } = element.getBoundingClientRect();\n const shot = await drawOver(await domToCanvas(element, options), overlay({ x, y, width, height }));\n return { body: await toPng(shot), type: 'image/png', box };\n }\n\n // The whole document, then the part the viewport shows: the document's box is where it scrolled to.\n const page = await domToCanvas(document.documentElement, options);\n const { clientWidth: width, clientHeight: height } = document.documentElement;\n const at = document.documentElement.getBoundingClientRect();\n const canvas = document.createElement('canvas');\n canvas.width = width * scale;\n canvas.height = height * scale;\n const ctx = canvas.getContext('2d');\n if (ctx === null) throw new Error(\"screenshots: this browser won't draw to a canvas\");\n ctx.drawImage(page, -at.left * scale, -at.top * scale, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);\n await drawOver(canvas, overlay({ x: 0, y: 0, width, height }));\n return { body: await toPng(canvas), type: 'image/png', box };\n});\n"],"mappings":"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"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as Masking, c as Screenshots, d as dom, f as rrweb, i as CaptureOptions, l as ScreenshotsOptions, n as BrowserOptions, o as Renderer, p as screenshots, r as Capture, s as ResolvedMasking, t as Box, u as Shot } from "../shared/index2.js";
|
|
2
|
+
export { Box, BrowserOptions, Capture, CaptureOptions, Masking, Renderer, ResolvedMasking, Screenshots, ScreenshotsOptions, Shot, screenshots as default, screenshots, dom, rrweb };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { definePlugin } from "../index.js";
|
|
4
|
+
import { t as keptIn } from "../shared/kept.js";
|
|
5
|
+
// src/plugins/screenshots/index.ts
|
|
6
|
+
/**
|
|
7
|
+
* `deictic/screenshots`: a plugin with no panel, for others to build on. In the page,
|
|
8
|
+
* `use('screenshots').capture(element)` takes what the viewport shows (or the element alone), with
|
|
9
|
+
* nothing of deictic's in it, and says where the element is; on the server, `use('screenshots').read(id)`
|
|
10
|
+
* hands the PNG to another plugin, which the tasks plugin attaches to a task.
|
|
11
|
+
*
|
|
12
|
+
* How a shot is made is its renderer's: `rrweb()` by default, which snapshots the page's DOM and renders it
|
|
13
|
+
* in a browser beside the dev server, so text lays out as the page's does; or `dom()`, which draws the page
|
|
14
|
+
* in the page itself, for a target with no server to render on. A renderer is a page module and, where it
|
|
15
|
+
* renders elsewhere, a `render` here (`Renderer`): another may take pixels from screen sharing or devtools.
|
|
16
|
+
*
|
|
17
|
+
* Shots are kept under `.deictic/screenshots`, the latest `keep` of them, so they outlive a
|
|
18
|
+
* restart of the dev server and stay out of git.
|
|
19
|
+
*/
|
|
20
|
+
/** Draws the page in the page, from its DOM (`modern-screenshot`): no server needed, but text may lay out a little differently. */
|
|
21
|
+
const dom = () => ({ client: "deictic/screenshots/dom" });
|
|
22
|
+
/**
|
|
23
|
+
* Snapshots the page's DOM in the page (`rrweb-snapshot`, masking as rrweb does) and renders it in a
|
|
24
|
+
* browser beside the dev server (`playwright-core`), so text lays out as the page's does.
|
|
25
|
+
*/
|
|
26
|
+
const rrweb = (options = {}) => ({
|
|
27
|
+
client: "deictic/screenshots/rrweb",
|
|
28
|
+
render: async (input) => (await import("../shared/playwright.js")).render(input, options)
|
|
29
|
+
});
|
|
30
|
+
const ID = /^[a-z0-9]+-[a-z0-9]+$/;
|
|
31
|
+
/** What one PNG, or one snapshot to render, may weigh: a viewport at twice its pixels is a few MB. */
|
|
32
|
+
const MAX = 20971520;
|
|
33
|
+
function screenshots(options = {}) {
|
|
34
|
+
const renderer = options.renderer ?? rrweb();
|
|
35
|
+
const keep = options.keep ?? 100;
|
|
36
|
+
let dir = "";
|
|
37
|
+
let taken = 0;
|
|
38
|
+
const pathOf = (id) => join(dir, `${id}.png`);
|
|
39
|
+
const read = (id) => {
|
|
40
|
+
if (!ID.test(id) || !existsSync(pathOf(id))) return void 0;
|
|
41
|
+
return {
|
|
42
|
+
data: new Uint8Array(readFileSync(pathOf(id))),
|
|
43
|
+
name: `${id}.png`,
|
|
44
|
+
type: "image/png"
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
const keepShot = (data) => {
|
|
48
|
+
const id = `${Date.now().toString(36).padStart(9, "0")}${(taken++ % 1296).toString(36).padStart(2, "0")}-${crypto.randomUUID().slice(0, 8)}`;
|
|
49
|
+
mkdirSync(dir, { recursive: true });
|
|
50
|
+
writeFileSync(pathOf(id), data);
|
|
51
|
+
const kept = readdirSync(dir).filter((f) => f.endsWith(".png")).toSorted();
|
|
52
|
+
for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
|
|
53
|
+
return id;
|
|
54
|
+
};
|
|
55
|
+
return definePlugin({
|
|
56
|
+
name: "screenshots",
|
|
57
|
+
client: renderer.client,
|
|
58
|
+
clientOptions: {
|
|
59
|
+
masking: {
|
|
60
|
+
blockClass: options.blockClass ?? "rr-block",
|
|
61
|
+
blockSelector: options.blockSelector,
|
|
62
|
+
maskTextClass: options.maskTextClass ?? "rr-mask",
|
|
63
|
+
maskTextSelector: options.maskTextSelector,
|
|
64
|
+
maskAllInputs: options.maskAllInputs ?? false
|
|
65
|
+
},
|
|
66
|
+
renderer: renderer.clientOptions
|
|
67
|
+
},
|
|
68
|
+
setup: ({ root }) => {
|
|
69
|
+
dir = options.dir === void 0 ? keptIn(root, "screenshots") : resolve(root, options.dir);
|
|
70
|
+
return { read };
|
|
71
|
+
},
|
|
72
|
+
routes: {
|
|
73
|
+
add: async (req) => {
|
|
74
|
+
const type = req.headers.get("content-type") ?? "";
|
|
75
|
+
const body = new Uint8Array(await req.arrayBuffer());
|
|
76
|
+
if (body.byteLength > MAX) return Response.json({ problem: `a shot may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
|
|
77
|
+
if (type === "image/png") return Response.json({ id: keepShot(body) });
|
|
78
|
+
if (renderer.render === void 0 || !type.startsWith("application/json")) return Response.json({ problem: "send the shot as image/png" }, { status: 415 });
|
|
79
|
+
try {
|
|
80
|
+
return Response.json({ id: keepShot(await renderer.render(JSON.parse(new TextDecoder().decode(body)))) });
|
|
81
|
+
} catch (e) {
|
|
82
|
+
return Response.json({ problem: e instanceof Error ? e.message : String(e) }, { status: 500 });
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
shot: (req) => {
|
|
86
|
+
const shot = read(new URL(req.url).pathname.split("/").at(-1) ?? "");
|
|
87
|
+
if (shot === void 0) return new Response("no such shot, or not kept any more", { status: 404 });
|
|
88
|
+
return new Response(shot.data, { headers: {
|
|
89
|
+
"content-type": shot.type,
|
|
90
|
+
"cache-control": "no-store"
|
|
91
|
+
} });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
export { screenshots as default, screenshots, dom, rrweb };
|
|
97
|
+
|
|
98
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/plugins/screenshots/index.ts"],"sourcesContent":["/**\n * `deictic/screenshots`: a plugin with no panel, for others to build on. In the page,\n * `use('screenshots').capture(element)` takes what the viewport shows (or the element alone), with\n * nothing of deictic's in it, and says where the element is; on the server, `use('screenshots').read(id)`\n * hands the PNG to another plugin, which the tasks plugin attaches to a task.\n *\n * How a shot is made is its renderer's: `rrweb()` by default, which snapshots the page's DOM and renders it\n * in a browser beside the dev server, so text lays out as the page's does; or `dom()`, which draws the page\n * in the page itself, for a target with no server to render on. A renderer is a page module and, where it\n * renders elsewhere, a `render` here (`Renderer`): another may take pixels from screen sharing or devtools.\n *\n * Shots are kept under `.deictic/screenshots`, the latest `keep` of them, so they outlive a\n * restart of the dev server and stay out of git.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport { definePlugin } from '#src/index.ts';\nimport { keptIn } from '#src/tools/kept.ts';\n\n/** A rectangle in CSS pixels, from the shot's top left. */\nexport interface Box {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** A shot as the page knows it: its ID, where the dev server serves its PNG, and where the element is in it. */\nexport interface Shot {\n id: string;\n url: string;\n /** The element, in the shot: nothing marks it there, as nothing of deictic's is drawn. */\n box: Box;\n /** The shot's size in CSS pixels; its PNG may have more, on a high-density screen. */\n size: { width: number; height: number };\n}\n\nexport interface CaptureOptions {\n /** `viewport`, what the page shows, by default; or `element`, the element alone. */\n area?: 'viewport' | 'element';\n}\n\n/** The page's half, for other plugins' page halves. */\nexport interface Capture {\n capture(element: Element, options?: CaptureOptions): Promise<Shot>;\n /** Keeps a PNG made of a shot (the same one with marks drawn over it, say) as a shot of its own. */\n upload(png: Blob, of: Pick<Shot, 'box' | 'size'>): Promise<Shot>;\n}\n\n/** The server's half, for other plugins' server halves. */\nexport interface Screenshots {\n /** A shot's PNG, or nothing for one not kept (any more). */\n read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: 'image/png' } | undefined;\n}\n\ndeclare module 'deictic' {\n interface ServerApis {\n screenshots: Screenshots;\n }\n interface ClientApis {\n screenshots: Capture;\n }\n}\n\n/**\n * What a shot hides, as rrweb names it and by its defaults, so one marking in the app hides the same\n * things from a screenshot as from an rrweb recording or snapshot.\n */\nexport interface Masking {\n /** Elements drawn as a blank box their size: `rr-block` by default. */\n blockClass?: string;\n blockSelector?: string;\n /** Elements whose text is drawn as `*`: `rr-mask` by default. */\n maskTextClass?: string;\n maskTextSelector?: string;\n /** Every field's value as `*`, not only passwords': false by default. */\n maskAllInputs?: boolean;\n}\n\n/** Masking with its defaults, as a renderer's page half gets it. */\nexport type ResolvedMasking = Required<Pick<Masking, 'blockClass' | 'maskTextClass' | 'maskAllInputs'>> & Masking;\n\n/**\n * How shots are made. `client` is the page module that captures, default-exporting `screenshotsClient(…)`\n * from `deictic/screenshots/client`. A page half that sends a PNG needs nothing here; one that sends\n * something else, as JSON (a DOM snapshot), needs `render` to make the PNG of it.\n */\nexport interface Renderer {\n client: string;\n /** What the page half gets, besides the masking. */\n clientOptions?: unknown;\n render?(input: unknown): Promise<Uint8Array>;\n}\n\n/** Where `rrweb()` finds a browser: any Chromium renders the snapshot as the page's own would. */\nexport interface BrowserOptions {\n /** A Chromium-based browser's executable. */\n executablePath?: string;\n /** An installed browser by Playwright's name: `chrome`, `msedge`. By default Playwright's own Chromium, then Chrome, then Edge. */\n channel?: string;\n}\n\n/** Draws the page in the page, from its DOM (`modern-screenshot`): no server needed, but text may lay out a little differently. */\nexport const dom = (): Renderer => ({ client: 'deictic/screenshots/dom' });\n\n/**\n * Snapshots the page's DOM in the page (`rrweb-snapshot`, masking as rrweb does) and renders it in a\n * browser beside the dev server (`playwright-core`), so text lays out as the page's does.\n */\nexport const rrweb = (options: BrowserOptions = {}): Renderer => ({\n client: 'deictic/screenshots/rrweb',\n // Loaded on the first shot, so a project rendering in the page needn't install Playwright.\n render: async (input) => (await import('./playwright.ts')).render(input, options),\n});\n\nexport interface ScreenshotsOptions extends Masking {\n /** How shots are made: `rrweb()` by default, or `dom()` where there's no server to render on. */\n renderer?: Renderer;\n /** How many shots to keep, the latest: 100 by default. */\n keep?: number;\n /** Where they're kept, from the project's root: `.deictic/screenshots` by default. */\n dir?: string;\n}\n\nconst ID = /^[a-z0-9]+-[a-z0-9]+$/;\n/** What one PNG, or one snapshot to render, may weigh: a viewport at twice its pixels is a few MB. */\nconst MAX = 20 * 1024 * 1024;\n\nexport function screenshots(options: ScreenshotsOptions = {}) {\n const renderer = options.renderer ?? rrweb();\n const keep = options.keep ?? 100;\n let dir = '';\n let taken = 0;\n const pathOf = (id: string) => join(dir, `${id}.png`);\n const read: Screenshots['read'] = (id) => {\n if (!ID.test(id) || !existsSync(pathOf(id))) return undefined;\n return { data: new Uint8Array(readFileSync(pathOf(id))), name: `${id}.png`, type: 'image/png' };\n };\n const keepShot = (data: Uint8Array) => {\n // Sorts by when it was taken, which is what pruning keeps by: the count orders two in one millisecond.\n const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;\n mkdirSync(dir, { recursive: true });\n writeFileSync(pathOf(id), data);\n const kept = readdirSync(dir)\n .filter((f) => f.endsWith('.png'))\n .toSorted();\n for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));\n return id;\n };\n\n return definePlugin<never, never, never, Screenshots>({\n name: 'screenshots',\n client: renderer.client,\n clientOptions: {\n masking: {\n blockClass: options.blockClass ?? 'rr-block',\n blockSelector: options.blockSelector,\n maskTextClass: options.maskTextClass ?? 'rr-mask',\n maskTextSelector: options.maskTextSelector,\n maskAllInputs: options.maskAllInputs ?? false,\n } satisfies ResolvedMasking,\n renderer: renderer.clientOptions,\n },\n setup: ({ root }) => {\n dir = options.dir === undefined ? keptIn(root, 'screenshots') : resolve(root, options.dir);\n return { read };\n },\n routes: {\n // A PNG the page made, or what the renderer makes one of.\n add: async (req) => {\n const type = req.headers.get('content-type') ?? '';\n const body = new Uint8Array(await req.arrayBuffer());\n if (body.byteLength > MAX) return Response.json({ problem: `a shot may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });\n if (type === 'image/png') return Response.json({ id: keepShot(body) });\n if (renderer.render === undefined || !type.startsWith('application/json'))\n return Response.json({ problem: 'send the shot as image/png' }, { status: 415 });\n try {\n return Response.json({ id: keepShot(await renderer.render(JSON.parse(new TextDecoder().decode(body)))) });\n } catch (e) {\n return Response.json({ problem: e instanceof Error ? e.message : String(e) }, { status: 500 });\n }\n },\n // `shot/<id>`: the PNG, for a panel to show.\n shot: (req) => {\n const shot = read(new URL(req.url).pathname.split('/').at(-1) ?? '');\n if (shot === undefined) return new Response('no such shot, or not kept any more', { status: 404 });\n return new Response(shot.data, { headers: { 'content-type': shot.type, 'cache-control': 'no-store' } });\n },\n },\n });\n}\n\nexport default screenshots;\n"],"mappings":"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"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { r as Capture } from "../shared/index2.js";
|
|
2
|
+
/**
|
|
3
|
+
* The `rrweb()` renderer's page half: a snapshot of the page's DOM with `rrweb-snapshot` (imported on the
|
|
4
|
+
* first shot), masked as rrweb masks, without deictic's overlay, sent with what the server's browser needs
|
|
5
|
+
* to show it as the page does: the viewport, where it's scrolled to, the pixel density, the page's URL.
|
|
6
|
+
*/
|
|
7
|
+
declare const _default: import("deictic").ClientPlugin<never, never, Capture>;
|
|
8
|
+
export { _default as default };
|
|
9
|
+
//# sourceMappingURL=rrweb.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rrweb.d.ts","names":["_$__index_ts0.Capture"],"sources":["../../src/plugins/screenshots/rrweb.ts"],"mappings":";;;;;;cAgBA,4B,2BAAAA"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { boxOf, screenshotsClient } from "./client.js";
|
|
2
|
+
// src/plugins/screenshots/rrweb.ts
|
|
3
|
+
/**
|
|
4
|
+
* The `rrweb()` renderer's page half: a snapshot of the page's DOM with `rrweb-snapshot` (imported on the
|
|
5
|
+
* first shot), masked as rrweb masks, without deictic's overlay, sent with what the server's browser needs
|
|
6
|
+
* to show it as the page does: the viewport, where it's scrolled to, the pixel density, the page's URL.
|
|
7
|
+
*/
|
|
8
|
+
/** The snapshot without deictic's overlay, which rrweb has no option to leave out. */
|
|
9
|
+
function withoutOurs(node) {
|
|
10
|
+
if (!("childNodes" in node)) return node;
|
|
11
|
+
const childNodes = node.childNodes.filter((c) => !("tagName" in c && c.tagName === "deictic-overlay")).map(withoutOurs);
|
|
12
|
+
return {
|
|
13
|
+
...node,
|
|
14
|
+
childNodes
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
var rrweb_default = screenshotsClient(async (element, { area, masking, overlay }) => {
|
|
18
|
+
const { snapshot } = await import("rrweb-snapshot").catch((e) => {
|
|
19
|
+
throw new Error("the rrweb() renderer needs rrweb-snapshot: add it to your devDependencies", { cause: e });
|
|
20
|
+
});
|
|
21
|
+
const taken = snapshot(document, {
|
|
22
|
+
inlineStylesheet: true,
|
|
23
|
+
blockClass: masking.blockClass,
|
|
24
|
+
blockSelector: masking.blockSelector ?? null,
|
|
25
|
+
maskTextClass: masking.maskTextClass,
|
|
26
|
+
maskTextSelector: masking.maskTextSelector ?? null,
|
|
27
|
+
maskAllInputs: masking.maskAllInputs
|
|
28
|
+
});
|
|
29
|
+
if (taken === null) throw new Error("screenshots: rrweb took no snapshot of this page");
|
|
30
|
+
const box = boxOf(element, area);
|
|
31
|
+
const viewport = {
|
|
32
|
+
width: document.documentElement.clientWidth,
|
|
33
|
+
height: document.documentElement.clientHeight
|
|
34
|
+
};
|
|
35
|
+
const marks = overlay({
|
|
36
|
+
x: 0,
|
|
37
|
+
y: 0,
|
|
38
|
+
...viewport
|
|
39
|
+
});
|
|
40
|
+
const body = {
|
|
41
|
+
snapshot: withoutOurs(taken),
|
|
42
|
+
url: location.href,
|
|
43
|
+
viewport,
|
|
44
|
+
...marks === void 0 ? {} : { overlay: marks },
|
|
45
|
+
scroll: {
|
|
46
|
+
x: scrollX,
|
|
47
|
+
y: scrollY
|
|
48
|
+
},
|
|
49
|
+
scale: Math.min(devicePixelRatio, 2),
|
|
50
|
+
...area === "element" ? { clip: element.getBoundingClientRect().toJSON() } : {}
|
|
51
|
+
};
|
|
52
|
+
return {
|
|
53
|
+
body: JSON.stringify(body),
|
|
54
|
+
type: "application/json",
|
|
55
|
+
box
|
|
56
|
+
};
|
|
57
|
+
});
|
|
58
|
+
export { rrweb_default as default };
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=rrweb.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rrweb.js","names":[],"sources":["../../src/plugins/screenshots/rrweb.ts"],"sourcesContent":["/**\n * The `rrweb()` renderer's page half: a snapshot of the page's DOM with `rrweb-snapshot` (imported on the\n * first shot), masked as rrweb masks, without deictic's overlay, sent with what the server's browser needs\n * to show it as the page does: the viewport, where it's scrolled to, the pixel density, the page's URL.\n */\n\nimport { boxOf, screenshotsClient } from './client.ts';\nimport type { Snapshot, SnapshotNode } from './playwright.ts';\n\n/** The snapshot without deictic's overlay, which rrweb has no option to leave out. */\nfunction withoutOurs(node: SnapshotNode): SnapshotNode {\n if (!('childNodes' in node)) return node;\n const childNodes = node.childNodes.filter((c: SnapshotNode) => !('tagName' in c && c.tagName === 'deictic-overlay')).map(withoutOurs);\n return { ...node, childNodes };\n}\n\nexport default screenshotsClient(async (element, { area, masking, overlay }) => {\n const { snapshot } = await import('rrweb-snapshot').catch((e: unknown) => {\n throw new Error('the rrweb() renderer needs rrweb-snapshot: add it to your devDependencies', { cause: e });\n });\n const taken = snapshot(document, {\n inlineStylesheet: true,\n blockClass: masking.blockClass,\n blockSelector: masking.blockSelector ?? null,\n maskTextClass: masking.maskTextClass,\n maskTextSelector: masking.maskTextSelector ?? null,\n maskAllInputs: masking.maskAllInputs,\n });\n if (taken === null) throw new Error('screenshots: rrweb took no snapshot of this page');\n const box = boxOf(element, area);\n const viewport = { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };\n // Over the viewport, which the server renders before cutting out an element's part.\n const marks = overlay({ x: 0, y: 0, ...viewport });\n const body: Snapshot = {\n snapshot: withoutOurs(taken),\n url: location.href,\n viewport,\n ...(marks === undefined ? {} : { overlay: marks }),\n scroll: { x: scrollX, y: scrollY },\n scale: Math.min(devicePixelRatio, 2),\n // A shot of the element alone is the part of the viewport it fills.\n ...(area === 'element' ? { clip: element.getBoundingClientRect().toJSON() as Snapshot['clip'] } : {}),\n };\n return { body: JSON.stringify(body), type: 'application/json', box };\n});\n"],"mappings":";;;;;;;;AAUA,SAAS,YAAY,MAAkC;CACrD,IAAI,EAAE,gBAAgB,OAAO,OAAO;CACpC,MAAM,aAAa,KAAK,WAAW,QAAQ,MAAoB,EAAE,aAAa,KAAK,EAAE,YAAY,kBAAkB,CAAC,CAAC,IAAI,WAAW;CACpI,OAAO;EAAE,GAAG;EAAM;CAAW;AAC/B;AAEA,IAAA,gBAAe,kBAAkB,OAAO,SAAS,EAAE,MAAM,SAAS,cAAc;CAC9E,MAAM,EAAE,aAAa,MAAM,OAAO,iBAAiB,CAAC,OAAO,MAAe;EACxE,MAAM,IAAI,MAAM,6EAA6E,EAAE,OAAO,EAAE,CAAC;CAC3G,CAAC;CACD,MAAM,QAAQ,SAAS,UAAU;EAC/B,kBAAkB;EAClB,YAAY,QAAQ;EACpB,eAAe,QAAQ,iBAAiB;EACxC,eAAe,QAAQ;EACvB,kBAAkB,QAAQ,oBAAoB;EAC9C,eAAe,QAAQ;CACzB,CAAC;CACD,IAAI,UAAU,MAAM,MAAM,IAAI,MAAM,kDAAkD;CACtF,MAAM,MAAM,MAAM,SAAS,IAAI;CAC/B,MAAM,WAAW;EAAE,OAAO,SAAS,gBAAgB;EAAa,QAAQ,SAAS,gBAAgB;CAAa;CAE9G,MAAM,QAAQ,QAAQ;EAAE,GAAG;EAAG,GAAG;EAAG,GAAG;CAAS,CAAC;CACjD,MAAM,OAAiB;EACrB,UAAU,YAAY,KAAK;EAC3B,KAAK,SAAS;EACd;EACA,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,MAAM;EAChD,QAAQ;GAAE,GAAG;GAAS,GAAG;EAAQ;EACjC,OAAO,KAAK,IAAI,kBAAkB,CAAC;EAEnC,GAAI,SAAS,YAAY,EAAE,MAAM,QAAQ,sBAAsB,CAAC,CAAC,OAAO,EAAsB,IAAI,CAAC;CACrG;CACA,OAAO;EAAE,MAAM,KAAK,UAAU,IAAI;EAAG,MAAM;EAAoB;CAAI;AACrE,CAAC"}
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
import { Refusal } from "../index.js";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { t as keptIn } from "./kept.js";
|
|
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
|
+
// src/tools/source.ts
|
|
7
|
+
/**
|
|
8
|
+
* The source a server half reads: a target's file, parsed, and the opening tag the page's attribute
|
|
9
|
+
* points at. Files are only ever read and written under the project's root, outside `node_modules`.
|
|
10
|
+
*/
|
|
11
|
+
/** A file from the project's root, as an absolute path; refused anywhere the page has no business writing. */
|
|
12
|
+
function resolveFile(root, file) {
|
|
13
|
+
const path = resolve(root, file);
|
|
14
|
+
const from = relative(root, path);
|
|
15
|
+
if (from === "" || from.startsWith("..") || isAbsolute(from) || from.split(sep).includes("node_modules")) throw new Refusal(`${file} is not a file of this project's own`);
|
|
16
|
+
return path;
|
|
17
|
+
}
|
|
18
|
+
function readSource(root, file) {
|
|
19
|
+
try {
|
|
20
|
+
return readFileSync(resolveFile(root, file), "utf8");
|
|
21
|
+
} catch (e) {
|
|
22
|
+
if (e instanceof Refusal) throw e;
|
|
23
|
+
throw new Refusal(`can't read ${file}: has it moved since the page loaded?`, { cause: e });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** The target's file and element, as they are on disk now. */
|
|
27
|
+
function sourceAt(root, target) {
|
|
28
|
+
const { file, line, column } = target.loc;
|
|
29
|
+
const code = readSource(root, file);
|
|
30
|
+
const offset = offsetOf(lineStarts(code), line, column);
|
|
31
|
+
const { program, elements } = ASTRO.test(file) ? astro(root, file, code) : jsx(file, code);
|
|
32
|
+
const element = elements.find((el) => el.start === offset && isHost(el));
|
|
33
|
+
if (element === void 0 || element.name.type === "JSXIdentifier" && element.name.name !== target.tag) throw new Refusal(`no <${target.tag}> at ${file}:${line}:${column} any more: the file changed since the page loaded, so reload it`);
|
|
34
|
+
return {
|
|
35
|
+
file,
|
|
36
|
+
code,
|
|
37
|
+
program,
|
|
38
|
+
element,
|
|
39
|
+
read: (other) => readSource(root, other)
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function jsx(file, code) {
|
|
43
|
+
const { program, errors } = parse(file, code);
|
|
44
|
+
if (errors.length > 0) throw new Refusal(`${file} doesn't parse: fix it first (${errors[0].message})`);
|
|
45
|
+
return {
|
|
46
|
+
program,
|
|
47
|
+
elements: openingsIn(program)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function astro(root, file, code) {
|
|
51
|
+
const parsed = parseAstro(root, code);
|
|
52
|
+
if ("problem" in parsed) throw new Refusal(`${file} can't be read: ${parsed.problem}`);
|
|
53
|
+
return parsed;
|
|
54
|
+
}
|
|
55
|
+
/** Each file's text after its edits, which must not overlap. */
|
|
56
|
+
function applyEdits(source, edits) {
|
|
57
|
+
const byFile = Map.groupBy(edits, (e) => e.file ?? source.file);
|
|
58
|
+
const out = /* @__PURE__ */ new Map();
|
|
59
|
+
for (const [file, list] of byFile) {
|
|
60
|
+
const sorted = list.toSorted((a, b) => b.start - a.start);
|
|
61
|
+
let code = file === source.file ? source.code : source.read(file);
|
|
62
|
+
let floor = 1e400;
|
|
63
|
+
for (const edit of sorted) {
|
|
64
|
+
if (edit.end > floor) throw new Error(`deictic: edits to ${file} overlap at ${edit.end}`);
|
|
65
|
+
code = code.slice(0, edit.start) + edit.text + code.slice(edit.end);
|
|
66
|
+
floor = edit.start;
|
|
67
|
+
}
|
|
68
|
+
out.set(file, code);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
// src/tools/history.ts
|
|
73
|
+
/**
|
|
74
|
+
* Every change deictic made, to undo and redo. A change to files holds each file's whole text
|
|
75
|
+
* before and after: source files are small, and the texts make undo exact without a diff to go stale.
|
|
76
|
+
* A change a plugin made itself (`Done`) holds the plugin's name and its record, and undoing it is the
|
|
77
|
+
* plugin's `undo`.
|
|
78
|
+
*
|
|
79
|
+
* Each change has a scope, the plugin and the element it was made on, and the popup undoes and redoes
|
|
80
|
+
* within its own: the latest change of this tab on this element, not the latest of all. So a change
|
|
81
|
+
* is taken back out of order, with later ones to the same file still in it. Then only the lines the
|
|
82
|
+
* change wrote go back to what they were, where they're still in the file as it wrote them, once.
|
|
83
|
+
*
|
|
84
|
+
* Anything else is refused, not merged: a file whose lines were edited since has the editor's own undo
|
|
85
|
+
* for it; and a redo likewise. A plugin's undo refuses on its own terms. Kept under `.deictic`, so it
|
|
86
|
+
* outlives a restart of the dev server and stays out of git.
|
|
87
|
+
*/
|
|
88
|
+
/** Whether a change is in a scope: any is in none. */
|
|
89
|
+
const within = (scope) => (c) => scope === void 0 || c.scope?.plugin === scope.plugin && c.scope.target === scope.target;
|
|
90
|
+
const summary = (c) => ({
|
|
91
|
+
id: c.id,
|
|
92
|
+
at: c.at,
|
|
93
|
+
label: c.label,
|
|
94
|
+
files: "files" in c ? c.files.map((f) => f.file) : []
|
|
95
|
+
});
|
|
96
|
+
var History = class {
|
|
97
|
+
#done = [];
|
|
98
|
+
#undone = [];
|
|
99
|
+
#root;
|
|
100
|
+
#store;
|
|
101
|
+
#plugins;
|
|
102
|
+
constructor(root, { plugins = [], store = keptIn(root, "history.json") } = {}) {
|
|
103
|
+
this.#root = root;
|
|
104
|
+
this.#store = store;
|
|
105
|
+
this.#plugins = new Map(plugins.map((p) => [p.name, p]));
|
|
106
|
+
if (!existsSync(store)) return;
|
|
107
|
+
try {
|
|
108
|
+
({done: this.#done, undone: this.#undone} = JSON.parse(readFileSync(store, "utf8")));
|
|
109
|
+
} catch {}
|
|
110
|
+
}
|
|
111
|
+
/** 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. */
|
|
112
|
+
commit(label, texts, scope) {
|
|
113
|
+
const files = [];
|
|
114
|
+
for (const [file, after] of texts) {
|
|
115
|
+
const path = resolveFile(this.#root, file);
|
|
116
|
+
const before = existsSync(path) ? readFileSync(path, "utf8") : null;
|
|
117
|
+
if (before !== after) files.push({
|
|
118
|
+
file,
|
|
119
|
+
before,
|
|
120
|
+
after
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
if (files.length === 0) throw new Refusal("nothing to change: the source already says that");
|
|
124
|
+
for (const f of files) write(resolveFile(this.#root, f.file), f.after);
|
|
125
|
+
return this.#push({
|
|
126
|
+
label,
|
|
127
|
+
files
|
|
128
|
+
}, scope);
|
|
129
|
+
}
|
|
130
|
+
/** Records a change `plugin` made itself, with what its `undo` needs. */
|
|
131
|
+
record(label, plugin, record, scope) {
|
|
132
|
+
return this.#push({
|
|
133
|
+
label,
|
|
134
|
+
plugin,
|
|
135
|
+
record
|
|
136
|
+
}, scope);
|
|
137
|
+
}
|
|
138
|
+
/** Takes back the latest change, of a scope where one is given. */
|
|
139
|
+
async undo(scope) {
|
|
140
|
+
const change = this.#done.findLast(within(scope));
|
|
141
|
+
if (change === void 0) throw new Refusal(scope === void 0 ? "nothing to undo" : "nothing to undo here");
|
|
142
|
+
if ("files" in change) this.#put(change, "after", "before");
|
|
143
|
+
else change.record = await this.#pluginOf(change, "undo").undo(change.record) ?? change.record;
|
|
144
|
+
this.#done = this.#done.filter((c) => c !== change);
|
|
145
|
+
this.#undone.push(change);
|
|
146
|
+
this.#save();
|
|
147
|
+
return summary(change);
|
|
148
|
+
}
|
|
149
|
+
/** Makes the change last undone again, of a scope where one is given. */
|
|
150
|
+
async redo(scope) {
|
|
151
|
+
const change = this.#undone.findLast(within(scope));
|
|
152
|
+
if (change === void 0) throw new Refusal(scope === void 0 ? "nothing to redo" : "nothing to redo here");
|
|
153
|
+
if ("files" in change) this.#put(change, "before", "after");
|
|
154
|
+
else change.record = await this.#pluginOf(change, "redo").redo(change.record);
|
|
155
|
+
this.#undone = this.#undone.filter((c) => c !== change);
|
|
156
|
+
this.#done.push(change);
|
|
157
|
+
this.#save();
|
|
158
|
+
return summary(change);
|
|
159
|
+
}
|
|
160
|
+
list(scope) {
|
|
161
|
+
return {
|
|
162
|
+
done: this.#done.filter(within(scope)).map(summary),
|
|
163
|
+
undone: this.#undone.filter(within(scope)).map(summary)
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
#push(change, scope) {
|
|
167
|
+
const made = {
|
|
168
|
+
id: Math.max(0, ...[...this.#done, ...this.#undone].map((c) => c.id)) + 1,
|
|
169
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
170
|
+
...change,
|
|
171
|
+
...scope === void 0 ? {} : { scope }
|
|
172
|
+
};
|
|
173
|
+
this.#done = [...this.#done, made].slice(-200);
|
|
174
|
+
this.#undone = this.#undone.filter((c) => !within(scope)(c));
|
|
175
|
+
this.#save();
|
|
176
|
+
return summary(made);
|
|
177
|
+
}
|
|
178
|
+
#pluginOf(change, step) {
|
|
179
|
+
const plugin = this.#plugins.get(change.plugin);
|
|
180
|
+
if (plugin?.[step] === void 0) throw new Refusal(`can't ${step} "${change.label}": the ${change.plugin} plugin that made it isn't loaded, so add it back to \`plugins\``);
|
|
181
|
+
return plugin;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Puts each file's `to` text back, once every one of them still reads as its `from`, or still has the
|
|
185
|
+
* lines that differ as `from` has them: then those lines alone change, and the rest stays as it is now.
|
|
186
|
+
*/
|
|
187
|
+
#put(change, from, to) {
|
|
188
|
+
const paths = change.files.map((f) => resolveFile(this.#root, f.file));
|
|
189
|
+
change.files.map((f, i) => {
|
|
190
|
+
const now = existsSync(paths[i]) ? readFileSync(paths[i], "utf8") : null;
|
|
191
|
+
if (now === f[from]) return f[to];
|
|
192
|
+
const text = now === null || f[from] === null || f[to] === null ? void 0 : swapped(now, f[from], f[to]);
|
|
193
|
+
if (text === void 0) throw new Refusal(`${f.file} changed since "${change.label}" ${from === "after" ? "was made" : "was undone"}: use the editor's undo there`);
|
|
194
|
+
return text;
|
|
195
|
+
}).forEach((text, i) => {
|
|
196
|
+
if (text === null) rmSync(paths[i]);
|
|
197
|
+
else write(paths[i], text);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
#save() {
|
|
201
|
+
write(this.#store, JSON.stringify({
|
|
202
|
+
done: this.#done,
|
|
203
|
+
undone: this.#undone
|
|
204
|
+
}));
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
/**
|
|
208
|
+
* `now` with the lines that differ between `from` and `to` put as `to` has them, where `now` has them as
|
|
209
|
+
* `from` does, in one place only. Nothing where it doesn't (they were edited, or there are two of them), or
|
|
210
|
+
* where `from` has no such lines to find (the change only removed some).
|
|
211
|
+
*/
|
|
212
|
+
function swapped(now, from, to) {
|
|
213
|
+
const [a, b, lines] = [
|
|
214
|
+
from.split("\n"),
|
|
215
|
+
to.split("\n"),
|
|
216
|
+
now.split("\n")
|
|
217
|
+
];
|
|
218
|
+
let head = 0;
|
|
219
|
+
while (head < a.length && head < b.length && a[head] === b[head]) head++;
|
|
220
|
+
let tail = 0;
|
|
221
|
+
while (tail < a.length - head && tail < b.length - head && a.at(-1 - tail) === b.at(-1 - tail)) tail++;
|
|
222
|
+
const theirs = a.slice(head, a.length - tail);
|
|
223
|
+
if (theirs.length === 0) return void 0;
|
|
224
|
+
const found = lines.flatMap((_, i) => theirs.every((line, j) => lines[i + j] === line) ? [i] : []);
|
|
225
|
+
if (found.length !== 1) return void 0;
|
|
226
|
+
return [
|
|
227
|
+
...lines.slice(0, found[0]),
|
|
228
|
+
...b.slice(head, b.length - tail),
|
|
229
|
+
...lines.slice(found[0] + theirs.length)
|
|
230
|
+
].join("\n");
|
|
231
|
+
}
|
|
232
|
+
function write(path, text) {
|
|
233
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
234
|
+
writeFileSync(path, text);
|
|
235
|
+
}
|
|
236
|
+
// src/tools/endpoints.ts
|
|
237
|
+
const scopeOf = (plugin, { file, line, column }) => ({
|
|
238
|
+
plugin,
|
|
239
|
+
target: `${file}:${line}:${column}`
|
|
240
|
+
});
|
|
241
|
+
/** The scope an undo or a redo names, or none for the whole history. */
|
|
242
|
+
const scopeIn = ({ plugin, target }) => plugin === void 0 || target === void 0 ? void 0 : scopeOf(plugin, target.loc);
|
|
243
|
+
/** Answers deictic's requests, and nothing for any other path. */
|
|
244
|
+
function endpoints({ root, plugins, base = "/", open, history = new History(root, { plugins }) }) {
|
|
245
|
+
const byName = new Map(plugins.map((p) => [p.name, p]));
|
|
246
|
+
const prefix = `${base}__deictic/`;
|
|
247
|
+
const ready = setUp(root, plugins);
|
|
248
|
+
const pluginOf = (name) => {
|
|
249
|
+
const plugin = byName.get(name);
|
|
250
|
+
if (plugin === void 0) throw new Refusal(`no plugin "${name}" on the server: is it in the bundler plugin's \`plugins\`?`);
|
|
251
|
+
return plugin;
|
|
252
|
+
};
|
|
253
|
+
const routes = {
|
|
254
|
+
read: async ({ plugin, target }) => ({ model: await readOf(pluginOf(plugin), target) }),
|
|
255
|
+
apply: async ({ plugin: name, target, op }) => {
|
|
256
|
+
const plugin = pluginOf(name);
|
|
257
|
+
if (plugin.apply === void 0) throw new Refusal(`${name} changes nothing from its panel: it has no \`apply\``);
|
|
258
|
+
const source = sourceAt(root, target);
|
|
259
|
+
const before = await readOf(plugin, target);
|
|
260
|
+
const { file, line } = target.loc;
|
|
261
|
+
const label = `${name} ${file}:${line}: ${plugin.describe?.(op, before) ?? "edit"}`;
|
|
262
|
+
const result = await plugin.apply(source, target, op);
|
|
263
|
+
const scope = scopeOf(name, target.loc);
|
|
264
|
+
const change = Array.isArray(result) ? history.commit(label, applyEdits(source, result), scope) : history.record(label, name, result.done, scope);
|
|
265
|
+
return {
|
|
266
|
+
model: await readOf(plugin, target),
|
|
267
|
+
change
|
|
268
|
+
};
|
|
269
|
+
},
|
|
270
|
+
undo: async (body) => ({ change: await history.undo(scopeIn(body)) }),
|
|
271
|
+
redo: async (body) => ({ change: await history.redo(scopeIn(body)) })
|
|
272
|
+
};
|
|
273
|
+
const readOf = (plugin, target) => plugin.read === void 0 ? null : plugin.read(sourceAt(root, target), target);
|
|
274
|
+
let queue = Promise.resolve();
|
|
275
|
+
const serially = (run) => {
|
|
276
|
+
const next = queue.then(run, run);
|
|
277
|
+
queue = next.catch(() => {});
|
|
278
|
+
return next;
|
|
279
|
+
};
|
|
280
|
+
return async (req) => {
|
|
281
|
+
const url = new URL(req.url);
|
|
282
|
+
if (!url.pathname.startsWith(prefix)) return void 0;
|
|
283
|
+
const route = url.pathname.slice(prefix.length);
|
|
284
|
+
const origin = req.headers.get("origin");
|
|
285
|
+
const sameOrigin = origin !== null && new URL(origin).host === url.host;
|
|
286
|
+
try {
|
|
287
|
+
const context = await ready;
|
|
288
|
+
if (route.startsWith("plugins/")) {
|
|
289
|
+
const [name = "", first = ""] = route.slice(8).split("/");
|
|
290
|
+
const handle = byName.get(name)?.routes?.[first];
|
|
291
|
+
if (handle === void 0) return new Response(`no endpoint ${url.pathname}`, { status: 404 });
|
|
292
|
+
if (req.method !== "GET" && req.method !== "HEAD" && !sameOrigin) return Response.json({ problem: `only the page itself may ${req.method} to ${name}` }, { status: 403 });
|
|
293
|
+
return await handle(req, context);
|
|
294
|
+
}
|
|
295
|
+
const loc = {
|
|
296
|
+
file: url.searchParams.get("file") ?? "",
|
|
297
|
+
line: Number(url.searchParams.get("line")),
|
|
298
|
+
column: Number(url.searchParams.get("column"))
|
|
299
|
+
};
|
|
300
|
+
if (route === "history") {
|
|
301
|
+
const plugin = url.searchParams.get("plugin");
|
|
302
|
+
return Response.json(history.list(plugin === null ? void 0 : scopeOf(plugin, loc)));
|
|
303
|
+
}
|
|
304
|
+
if (route === "open") return await open(resolveFile(root, loc.file), loc);
|
|
305
|
+
const handler = routes[route];
|
|
306
|
+
if (handler === void 0) return new Response(`no endpoint ${url.pathname}`, { status: 404 });
|
|
307
|
+
if (req.method !== "POST" || !sameOrigin || req.headers.get("content-type")?.startsWith("application/json") !== true) return Response.json({ problem: "edits come from the page, as JSON" }, { status: 403 });
|
|
308
|
+
const body = await req.json();
|
|
309
|
+
return Response.json(await (route === "read" ? handler(body) : serially(() => handler(body))));
|
|
310
|
+
} catch (e) {
|
|
311
|
+
if (e instanceof Refusal) return Response.json({ problem: e.message }, { status: 422 });
|
|
312
|
+
return Response.json({ problem: e instanceof Error ? e.stack ?? e.message : String(e) }, { status: 500 });
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
/** A redirect within the page's origin, to a launcher the dev server answers itself. */
|
|
317
|
+
const redirect = (path) => new Response(null, {
|
|
318
|
+
status: 307,
|
|
319
|
+
headers: { Location: path }
|
|
320
|
+
});
|
|
321
|
+
/**
|
|
322
|
+
* The endpoints as Node middleware, for Vite's server. The request's host is the one the page was
|
|
323
|
+
* served from: a proxy's `x-forwarded-host` before its own.
|
|
324
|
+
*/
|
|
325
|
+
function nodeMiddleware(handle) {
|
|
326
|
+
return (req, res, next) => {
|
|
327
|
+
if (req.url?.includes("/__deictic/") !== true) return next();
|
|
328
|
+
const forwarded = req.headers["x-forwarded-host"];
|
|
329
|
+
const host = (Array.isArray(forwarded) ? forwarded[0] : forwarded) ?? req.headers.host ?? "localhost";
|
|
330
|
+
const headers = new Headers();
|
|
331
|
+
for (const [name, value] of Object.entries(req.headers)) for (const v of Array.isArray(value) ? value : value === void 0 ? [] : [value]) headers.append(name, v);
|
|
332
|
+
const chunks = [];
|
|
333
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
334
|
+
req.on("end", () => {
|
|
335
|
+
const body = req.method === "GET" || req.method === "HEAD" ? void 0 : Buffer.concat(chunks);
|
|
336
|
+
handle(new Request(`http://${host}${req.url}`, {
|
|
337
|
+
method: req.method,
|
|
338
|
+
headers,
|
|
339
|
+
body
|
|
340
|
+
})).then(async (response) => {
|
|
341
|
+
if (response === void 0) return next();
|
|
342
|
+
res.statusCode = response.status;
|
|
343
|
+
response.headers.forEach((value, name) => res.setHeader(name, value));
|
|
344
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
345
|
+
}).catch((e) => {
|
|
346
|
+
res.statusCode = 500;
|
|
347
|
+
res.end(e instanceof Error ? e.message : String(e));
|
|
348
|
+
});
|
|
349
|
+
});
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
export { nodeMiddleware as n, redirect as r, endpoints as t };
|
|
353
|
+
|
|
354
|
+
//# sourceMappingURL=endpoints.js.map
|