deictic 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/API.md +21 -2
  2. package/README.md +2 -1
  3. package/dist/bun.js +1 -1
  4. package/dist/client/index.d.ts +1 -1
  5. package/dist/client/index.d.ts.map +1 -1
  6. package/dist/client/index.js +77 -51
  7. package/dist/client/index.js.map +1 -1
  8. package/dist/index.d.ts +2 -2
  9. package/dist/next.js +1 -1
  10. package/dist/recommended/index.d.ts +1 -1
  11. package/dist/recordings/client.js +8 -2
  12. package/dist/recordings/client.js.map +1 -1
  13. package/dist/shared/endpoints.js +26 -6
  14. package/dist/shared/endpoints.js.map +1 -1
  15. package/dist/shared/index.d.ts +35 -3
  16. package/dist/shared/index.d.ts.map +1 -1
  17. package/dist/shared/index7.d.ts +22 -2
  18. package/dist/shared/index7.d.ts.map +1 -1
  19. package/dist/shared/index9.d.ts +1 -1
  20. package/dist/shared/integration.d.ts +1 -1
  21. package/dist/shared/integration.js +59 -5
  22. package/dist/shared/integration.js.map +1 -1
  23. package/dist/shared/package.js +23 -0
  24. package/dist/shared/package.js.map +1 -0
  25. package/dist/shared/packages.js +14 -23
  26. package/dist/shared/packages.js.map +1 -1
  27. package/dist/shared/playwright.js +11 -3
  28. package/dist/shared/playwright.js.map +1 -1
  29. package/dist/shared/src.js.map +1 -1
  30. package/dist/shared/task.js +12 -3
  31. package/dist/shared/task.js.map +1 -1
  32. package/dist/shared/tasks.js +52 -4
  33. package/dist/shared/tasks.js.map +1 -1
  34. package/dist/shared/watch.js +2 -1
  35. package/dist/shared/watch.js.map +1 -1
  36. package/dist/tailwind/index.js +7 -2
  37. package/dist/tailwind/index.js.map +1 -1
  38. package/dist/tasks/client.d.ts.map +1 -1
  39. package/dist/tasks/client.js +50 -9
  40. package/dist/tasks/client.js.map +1 -1
  41. package/dist/tasks/index.d.ts +2 -2
  42. package/dist/webpack.js +1 -1
  43. package/package.json +2 -1
  44. package/src/cli/task.ts +20 -4
  45. package/src/cli/watch.ts +3 -1
  46. package/src/client/index.ts +76 -43
  47. package/src/index.ts +35 -2
  48. package/src/plugins/recordings/client.ts +8 -2
  49. package/src/plugins/screenshots/playwright.ts +8 -3
  50. package/src/plugins/tailwind/index.ts +3 -2
  51. package/src/plugins/tasks/client.ts +13 -3
  52. package/src/plugins/tasks/composer.ts +1 -1
  53. package/src/plugins/tasks/drawer.ts +3 -3
  54. package/src/plugins/tasks/index.ts +81 -3
  55. package/src/plugins/tasks/pins.ts +12 -7
  56. package/src/plugins/tasks/which.ts +34 -0
  57. package/src/tools/endpoints.ts +31 -5
  58. package/src/tools/packages.ts +12 -4
  59. package/src/tools/plugins.ts +18 -4
  60. package/src/tools/problems.ts +60 -0
@@ -1,5 +1,5 @@
1
1
  import { Board } from "@vercel/board";
2
- import { A as Shortcut, S as Target, f as Point } from "./index.js";
2
+ import { C as Target, f as Point, j as Shortcut, p as Problem } from "./index.js";
3
3
  import { t as Box } from "./index3.js";
4
4
  interface LocalOptions {
5
5
  /**
@@ -59,6 +59,12 @@ interface TasksOptions {
59
59
  html?: boolean;
60
60
  /** What opens its tab directly, beside deictic's own shortcut, which opens any: none by default. */
61
61
  shortcut?: Shortcut;
62
+ /**
63
+ * Whether deictic's own problems become tasks, for whoever works the board to fix: a package the project hasn't
64
+ * installed, a plugin that failed, a request that broke. One task per problem while it's open (`deictic.problem`
65
+ * is its key), about the project, not an element. True by default.
66
+ */
67
+ problems?: boolean;
62
68
  }
63
69
  interface Task {
64
70
  id: string;
@@ -77,11 +83,21 @@ interface Task {
77
83
  dropped?: string;
78
84
  /** The spot in the element it's about, where it's about one: CSS pixels from the element's top left. */
79
85
  point?: Point;
86
+ /** Which of the elements from its place it's about, where the page had more than one. */
87
+ which?: Which;
80
88
  /**
81
89
  * Where it was added, where that isn't the element's place: where the element was before it moved.
82
90
  */
83
91
  at?: Place;
84
92
  }
93
+ /**
94
+ * One of several elements from the same place in the source (a list's items): its place among them on the page, from 1,
95
+ * and its text where it has any, which still finds it once the list is in another order.
96
+ */
97
+ interface Which {
98
+ nth: number;
99
+ text?: string;
100
+ }
85
101
  /** A place in the element's file: a line and a column, from 1, and the tag there as the task saw it. */
86
102
  interface Place {
87
103
  line: number;
@@ -101,6 +117,8 @@ interface Listed extends Task {
101
117
  last?: string;
102
118
  /** What the board says of where it stands: why it's blocked, what it came to, why it failed. */
103
119
  said?: string;
120
+ /** A problem of deictic's it tells of, not a person's ask: the project's setup to fix, or a bug of deictic's. */
121
+ problem?: Problem['kind'];
104
122
  }
105
123
  /** A task with a place, as its mark has it: what the page pins to the element there. */
106
124
  type Placed = Listed & {
@@ -186,6 +204,8 @@ interface Op {
186
204
  };
187
205
  /** How many elements on the page come from the same place in the source. */
188
206
  count: number;
207
+ /** Which of them it is, where there's more than one: what the page tells it from the others by. */
208
+ which?: Which;
189
209
  /**
190
210
  * The other elements it's about, after the one it's sent on, in the order they were attached: each one's place,
191
211
  * its tag, and its HTML as it rendered, where that's attached.
@@ -299,5 +319,5 @@ interface Removed extends Added {
299
319
  */
300
320
  type Kept = Added | Edited | Removed;
301
321
  declare function tasks(options?: TasksOptions): import("deictic").ServerPlugin<Model, Op, Kept, unknown>;
302
- export { local as S, TasksOptions as _, Kept as a, LocalBoard as b, Model as c, Placed as d, Removed as f, TaskBoard as g, TaskAdded as h, Edited as i, Op as l, Task as m, Answer as n, Listed as o, Reply as p, Attached as r, Marks as s, Added as t, Place as u, Thread as v, LocalOptions as x, tasks as y };
322
+ export { local as C, LocalOptions as S, TasksOptions as _, Kept as a, tasks as b, Model as c, Placed as d, Removed as f, TaskBoard as g, TaskAdded as h, Edited as i, Op as l, Task as m, Answer as n, Listed as o, Reply as p, Attached as r, Marks as s, Added as t, Place as u, Thread as v, LocalBoard as x, Which as y };
303
323
  //# sourceMappingURL=index7.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index7.d.ts","names":[],"sources":["../../src/plugins/tasks/local.ts","../../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UAGe;EACf;EACA;EACA;EACA,QAAQ;;EAER;;;UAIe;EACf;EACA;EACA;EACA;;;;;;UAOe,gBAAgB;EAC/B;;;;;;KAOU,OAAO,QAAQ,SAAS;iBA0BpB,MAAM,UAAS,iCAAiB,aAAA,OAAA,IAAA"}
@@ -1,4 +1,4 @@
1
- import { A as Shortcut } from "./index.js";
1
+ import { j as Shortcut } from "./index.js";
2
2
  /** A class as the panel shows it. */
3
3
  interface ClassInfo {
4
4
  name: string;
@@ -1,4 +1,4 @@
1
- import { A as Shortcut, v as ServerPlugin } from "./index.js";
1
+ import { j as Shortcut, y as ServerPlugin } from "./index.js";
2
2
  import "magic-string";
3
3
  import "oxc-parser";
4
4
  interface DeicticOptions {
@@ -149,6 +149,47 @@ function locateAstro(code, file, root) {
149
149
  const parsed = parseAstro(root, code);
150
150
  return "problem" in parsed ? void 0 : marked(code, file, parsed.elements);
151
151
  }
152
+ // src/tools/problems.ts
153
+ /** How much of a problem is kept: its words, and its details (a stack is shorter). */
154
+ const WORDS = 2e3;
155
+ const DETAILS = 2e4;
156
+ /** What reports a problem: `ready` is when the plugins that hear of them are set up to. */
157
+ function reporter(plugins, ready) {
158
+ const said = /* @__PURE__ */ new Set();
159
+ return (problem) => {
160
+ if (said.has(problem.key)) return;
161
+ said.add(problem.key);
162
+ console.warn(`deictic${problem.plugin === void 0 ? "" : `/${problem.plugin}`}: ${problem.message}`);
163
+ const hearing = plugins.filter((p) => p.problem !== void 0);
164
+ if (hearing.length === 0) return;
165
+ const tell = async (plugin) => {
166
+ try {
167
+ await plugin.problem?.(problem);
168
+ } catch (e) {
169
+ console.warn(`deictic: ${plugin.name} couldn't take that problem, as ${messageOf(e)}`);
170
+ }
171
+ };
172
+ Promise.resolve().then(ready).then(() => Promise.all(hearing.map(tell)), () => {});
173
+ };
174
+ }
175
+ /** What went wrong, as a problem's words say it: an error's message. */
176
+ const messageOf = (e) => e instanceof Error ? e.message : String(e);
177
+ /** An error's stack, where it has one, for a problem's details. */
178
+ const stackOf = (e) => e instanceof Error && e.stack !== void 0 ? { details: e.stack } : {};
179
+ /** A problem as the page sent it, checked and cut short, or nothing where it isn't one. */
180
+ function problemIn(value) {
181
+ if (typeof value !== "object" || value === null) return void 0;
182
+ const { key, kind, message, details, plugin } = value;
183
+ if (typeof key !== "string" || key === "" || typeof message !== "string" || message === "") return void 0;
184
+ if (kind !== "setup" && kind !== "bug") return void 0;
185
+ return {
186
+ key: key.slice(0, WORDS),
187
+ kind,
188
+ message: message.slice(0, WORDS),
189
+ ...typeof details === "string" && details !== "" ? { details: details.slice(0, DETAILS) } : {},
190
+ ...typeof plugin === "string" && plugin !== "" ? { plugin: plugin.slice(0, 100) } : {}
191
+ };
192
+ }
152
193
  // src/tools/plugins.ts
153
194
  const NAME = /^[a-z][a-z0-9-]*$/;
154
195
  /** Throws what to fix in a set of plugins: names, what they need, and their shortcuts, beside deictic's own. */
@@ -172,16 +213,29 @@ function checkPlugins(plugins, own) {
172
213
  /**
173
214
  * Runs every plugin's `setup`, all at once, and answers the context they share: `use` reads an API
174
215
  * when it's asked for, so setups may `use` each other's only after they've all run, from a route or an
175
- * op, never in `setup` itself.
216
+ * op, never in `setup` itself. One that fails is reported and has no API: the others go on, so one of them
217
+ * can tell of it (tasks, on the board).
176
218
  */
177
- async function setUp(root, plugins) {
219
+ async function setUp(root, plugins, report) {
178
220
  const apis = /* @__PURE__ */ new Map();
179
221
  const context = {
180
222
  root,
181
- use: (name) => apis.get(name)
223
+ use: (name) => apis.get(name),
224
+ report
182
225
  };
183
226
  await Promise.all(plugins.map(async (p) => {
184
- if (p.setup !== void 0) apis.set(p.name, await p.setup(context));
227
+ if (p.setup === void 0) return;
228
+ try {
229
+ apis.set(p.name, await p.setup(context));
230
+ } catch (e) {
231
+ report({
232
+ key: `setup:${p.name}`,
233
+ kind: "bug",
234
+ plugin: p.name,
235
+ message: `${p.name} failed to set up, so it does nothing until the dev server restarts: ${messageOf(e)}`,
236
+ ...stackOf(e)
237
+ });
238
+ }
185
239
  }));
186
240
  return context;
187
241
  }
@@ -274,6 +328,6 @@ function fileIn(path, root) {
274
328
  const file = relative(root, path).replaceAll("\\", "/");
275
329
  return file.startsWith("..") || isAbsolute(file) ? void 0 : file;
276
330
  }
277
- export { markAstro as a, setUp as c, JSX as d, isHost as f, parse as g, openingsIn as h, mark as i, ASTRO as l, offsetOf as m, clientModule as n, prepare as o, lineStarts as p, importOf as r, writeClient as s, beside as t, parseAstro as u };
331
+ export { lineStarts as _, markAstro as a, parse as b, setUp as c, reporter as d, stackOf as f, isHost as g, JSX as h, mark as i, messageOf as l, parseAstro as m, clientModule as n, prepare as o, ASTRO as p, importOf as r, writeClient as s, beside as t, problemIn as u, offsetOf as v, openingsIn as y };
278
332
 
279
333
  //# sourceMappingURL=integration.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"integration.js","names":["OWN","OWN"],"sources":["../../src/tools/locate.ts","../../src/tools/astro.ts","../../src/tools/plugins.ts","../../src/tools/integration.ts"],"sourcesContent":["/**\n * Marks each host element in a JSX module with where its opening tag starts:\n * `<div data-deictic=\"src/App.tsx:12:5\">`. The page reads it back to know what was clicked.\n *\n * At build time and not from React's fibers at runtime: it works for any framework that compiles JSX,\n * for server components (which have no fiber in the browser), and it names the element's own tag\n * rather than the component that rendered it. Only host elements (`div`, `button`) are marked, since a\n * component may not pass the attribute on; a component's call site is reached from its elements.\n *\n * The transform must run on the source as written (`enforce: 'pre'` under Vite), so lines and columns\n * are the file's. It runs alike on the server and in the browser, so a hydrated page matches its HTML.\n */\nimport MagicString from 'magic-string';\nimport { type JSXOpeningElement, parseSync, type Program, Visitor } from 'oxc-parser';\n\nexport const ATTRIBUTE = 'data-deictic';\n/** Modules that may hold JSX: `.jsx` and `.tsx`, and plain `.js`, as many React projects write theirs. */\nexport const JSX = /\\.[cm]?(?:[jt]sx|js)$/;\n\n/** A module parsed, with JSX read in a `.js` file too, which the parser reads there only when told. */\nexport const parse = (file: string, code: string) => parseSync(file, code, /\\.[cm]?js$/.test(file) ? { lang: 'jsx' } : undefined);\n\nexport interface Located {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n}\n\n/** Whether an opening tag is a host element's, `<div>` or `<svg>`, not a component's or a namespaced one. */\nexport const isHost = (el: JSXOpeningElement) => el.name.type === 'JSXIdentifier' && /^[a-z]/.test(el.name.name);\n\n/**\n * `code` with every host element marked, `file` being its path from the project's root, and `append`\n * after it (the client's import, in the browser); nothing when there is nothing to mark, or the module\n * doesn't parse, which the framework's own transform reports better.\n */\nexport function locate(code: string, file: string, append = ''): Located | undefined {\n // No tag, no parse: most `.js` modules have none, and every one of the project's comes through here.\n if (!/<[a-z]/.test(code)) return undefined;\n const { program, errors } = parse(file, code);\n if (errors.length > 0) return undefined;\n return marked(code, file, openingsIn(program), append);\n}\n\n/** Every opening tag in a module, in its order. */\nexport function openingsIn(program: Program): JSXOpeningElement[] {\n const elements: JSXOpeningElement[] = [];\n new Visitor({ JSXOpeningElement: (el) => void elements.push(el) }).visit(program);\n return elements;\n}\n\n/**\n * `code` with a mark in each of `elements` that is a host element's and has none yet, and `append` after\n * it; nothing with none to mark.\n */\nexport function marked(code: string, file: string, elements: JSXOpeningElement[], append = ''): Located | undefined {\n const lines = lineStarts(code);\n const s = new MagicString(code);\n for (const el of elements) {\n if (!isHost(el) || el.attributes.some((a) => a.type === 'JSXAttribute' && nameOf(a.name) === ATTRIBUTE)) continue;\n const { line, column } = position(lines, el.start);\n s.appendLeft(el.name.end, ` ${ATTRIBUTE}=\"${file}:${line}:${column}\"`);\n }\n if (!s.hasChanged()) return undefined;\n if (append !== '') s.append(append);\n // A map's source is read from the module's own folder, so it's the file's name, not its path from the root.\n return { code: s.toString(), map: s.generateMap({ source: file.slice(file.lastIndexOf('/') + 1), hires: 'boundary' }) };\n}\n\nconst nameOf = (name: { type: string; name?: unknown }) => (name.type === 'JSXIdentifier' ? name.name : undefined);\n\n/** Where each line starts, by offset. */\nexport function lineStarts(code: string): number[] {\n const starts = [0];\n for (let i = code.indexOf('\\n'); i !== -1; i = code.indexOf('\\n', i + 1)) starts.push(i + 1);\n return starts;\n}\n\n/** An offset's line and column, from 1. */\nexport function position(lines: number[], offset: number): { line: number; column: number } {\n let lo = 0;\n let hi = lines.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (lines[mid]! <= offset) lo = mid;\n else hi = mid - 1;\n }\n return { line: lo + 1, column: offset - lines[lo]! + 1 };\n}\n\n/** A line and column's offset, or nothing past the file's end. */\nexport function offsetOf(lines: number[], line: number, column: number): number | undefined {\n const start = lines[line - 1];\n return start === undefined ? undefined : start + column - 1;\n}\n","/**\n * `.astro` components. They aren't JSX modules, but Astro 7's own parser reads a template as JSX, into the\n * tree oxc makes (offsets in UTF-16, as ours are), so its host elements are marked as a JSX module's are,\n * before Astro compiles the file. The parser is the project's own Astro's (`@astrojs/compiler-rs`, found\n * through `astro`), so it reads a file exactly as the compiler will; an Astro before 7 has none like it,\n * and its `.astro` files are left unmarked.\n */\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\n\nimport type { JSXOpeningElement, Program } from 'oxc-parser';\n\nimport { type Located, marked } from './locate.ts';\n\nexport const ASTRO = /\\.astro$/;\n\n/** A file parsed: its module (an `.astro` file's frontmatter), and each opening tag in it, in the file's order. */\nexport interface Parsed {\n program: Program;\n elements: JSXOpeningElement[];\n}\n\ninterface Tree {\n ast: { frontmatter: { program: Program }; body: unknown };\n diagnostics: { severity: string; text: string }[];\n}\ntype Parse = (code: string) => Tree;\n\nconst parsers = new Map<string, Parse | undefined>();\n\n/** The parser of the Astro installed for the project at `root`, loaded once; nothing without Astro 7. */\nfunction parserOf(root: string): Parse | undefined {\n if (!parsers.has(root)) parsers.set(root, load(root));\n return parsers.get(root);\n}\n\nfunction load(root: string): Parse | undefined {\n try {\n // Astro's own dependency, which a strict package manager doesn't put where the project could import it.\n const astro = createRequire(createRequire(join(root, 'package.json')).resolve('astro/package.json'));\n // An ES module, required: every Node that runs Astro 7 can, and reading a source stays synchronous.\n const compiler: { parse?: Parse } = astro('@astrojs/compiler-rs');\n return compiler.parse;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Astro gives a `<script>` or `<style>` with an attribute it doesn't know to the page as it is, unbundled and\n * unscoped, and a `<slot>` isn't an element at all: none of them can be pointed at, so none is marked.\n */\nconst OWN = new Set(['script', 'style', 'slot']);\n\nconst isOpening = (node: object): node is JSXOpeningElement => 'type' in node && node.type === 'JSXOpeningElement';\n\n/** An `.astro` file's text parsed, or the `problem` with it: no parser (an older Astro), or text that doesn't parse. */\nexport function parseAstro(root: string, code: string): Parsed | { problem: string } {\n const parse = parserOf(root);\n if (parse === undefined) return { problem: 'reading an .astro file takes Astro 7 or later, so update astro' };\n const { ast, diagnostics } = parse(code);\n const error = diagnostics.find((d) => d.severity === 'error');\n if (error !== undefined) return { problem: `fix it first (${error.text})` };\n const elements: JSXOpeningElement[] = [];\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) return node.forEach(walk);\n if (node === null || typeof node !== 'object') return;\n if (isOpening(node) && !(node.name.type === 'JSXIdentifier' && OWN.has(node.name.name))) elements.push(node);\n Object.values(node).forEach(walk);\n };\n walk(ast.body);\n return { program: ast.frontmatter.program, elements };\n}\n\n/** An `.astro` file's text with every host element marked, as `locate` marks a JSX module; nothing where it can't be read. */\nexport function locateAstro(code: string, file: string, root: string): Located | undefined {\n // No tag, no parse.\n if (!/<[a-z]/.test(code)) return undefined;\n const parsed = parseAstro(root, code);\n return 'problem' in parsed ? undefined : marked(code, file, parsed.elements);\n}\n","/**\n * The plugins an integration was given: checked as it starts, so a wrong set fails the dev server with\n * what to write instead, and set up once before the endpoints answer anything.\n */\nimport type { ServerContext, ServerPlugin } from '#src/index.ts';\nimport { checkShortcuts, OWN, ownShortcut, type Shortcut } from '#src/shortcut.ts';\n\nconst NAME = /^[a-z][a-z0-9-]*$/;\n\n/** Throws what to fix in a set of plugins: names, what they need, and their shortcuts, beside deictic's own. */\nexport function checkPlugins(plugins: readonly ServerPlugin[], own?: Shortcut | false): void {\n const names = new Set<string>();\n for (const { name, client, shortcut } of plugins) {\n if (!NAME.test(name)) throw new Error(`deictic: a plugin is named \"${name}\": name it in lowercase letters, digits and -`);\n if (names.has(name)) throw new Error(`deictic: two plugins are named ${name}: load each once`);\n if (shortcut !== undefined && client === undefined)\n throw new Error(`deictic: ${name} has a shortcut but no \\`client\\` to draw its panel: give it one, or leave out its shortcut`);\n names.add(name);\n }\n for (const { name, needs = [] } of plugins) {\n const missing = needs.find((other) => !names.has(other));\n if (missing !== undefined) throw new Error(`deictic: ${name} needs the ${missing} plugin: add it to \\`plugins\\``);\n }\n checkShortcuts([{ name: OWN, shortcut: ownShortcut(own) }, ...plugins]);\n}\n\n/**\n * Runs every plugin's `setup`, all at once, and answers the context they share: `use` reads an API\n * when it's asked for, so setups may `use` each other's only after they've all run, from a route or an\n * op, never in `setup` itself.\n */\nexport async function setUp(root: string, plugins: readonly ServerPlugin[]): Promise<ServerContext> {\n const apis = new Map<string, unknown>();\n const context: ServerContext = { root, use: (name) => apis.get(name) as never };\n await Promise.all(\n plugins.map(async (p) => {\n if (p.setup !== undefined) apis.set(p.name, await p.setup(context));\n }),\n );\n return context;\n}\n","/**\n * What every bundler's integration shares: the options, the client module that starts the overlay, and\n * the transform that marks a JSX module. Each integration adds what its bundler does its own way: how a\n * module is transformed (a hook, a loader, `onLoad`), how the page loads the client (a virtual module\n * under Vite, a file in `.deictic/` elsewhere, as webpack, Turbopack and Bun have none), where the\n * endpoints are served, and what opens the editor.\n */\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, isAbsolute, relative } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { ServerPlugin } from '#src/index.ts';\nimport { checkShortcuts, OWN, ownShortcut, type Shortcut } from '#src/shortcut.ts';\n\nimport { ASTRO, locateAstro } from './astro.ts';\nimport { keptIn } from './kept.ts';\nimport { JSX, locate, type Located } from './locate.ts';\nimport { checkPlugins } from './plugins.ts';\n\nexport interface DeicticOptions {\n /** The plugins to load, server halves: `tailwind()`, `tasks()`, your own. None by default. */\n plugins?: ServerPlugin[];\n /**\n * What opens the popup on any plugin, at the tab used last: Alt and the left button by default, or\n * `false` for none, leaving only plugins' own shortcuts.\n */\n shortcut?: Shortcut | false;\n}\n\n/** The options with their defaults, checked now, so a wrong set stops the dev server as it starts, not the page. */\nexport function prepare(options: DeicticOptions): { plugins: ServerPlugin[]; shortcut: Shortcut | false | undefined } {\n const plugins = options.plugins ?? [];\n checkPlugins(plugins, options.shortcut);\n return { plugins, shortcut: options.shortcut };\n}\n\n/**\n * The client module: the overlay, started with deictic's own shortcut and each plugin that has a half\n * in the page, with its shortcut, checked; and with `server`, a module of the page's that answers its requests\n * where no dev server does.\n */\nexport const clientModule = (plugins: ServerPlugin[], base: string, own?: Shortcut | false, server?: string) => {\n const [shortcut, ...shortcuts] = checkShortcuts([{ name: OWN, shortcut: ownShortcut(own) }, ...plugins]);\n const paged = plugins.flatMap((p, i) =>\n p.client === undefined ? [] : [{ client: p.client, rest: { shortcut: shortcuts[i], options: p.clientOptions } }],\n );\n return [\n `import { start } from 'deictic/client';`,\n ...paged.map((p, i) => `import p${i} from ${JSON.stringify(p.client)};`),\n ...(server === undefined ? [] : [`import server from ${JSON.stringify(server)};`]),\n // Its shortcut and options as JSON, where it has them: `JSON.stringify` leaves out what's undefined.\n `start({ base: ${JSON.stringify(base)}, shortcut: ${JSON.stringify(shortcut) ?? 'undefined'}, plugins: [${paged.map((p, i) => `{ plugin: p${i}, ...${JSON.stringify(p.rest)} }`).join(', ')}]${server === undefined ? '' : ', server'} });`,\n ].join('\\n');\n};\n\n/**\n * Writes the client module to `.deictic/client.js` for a bundler without virtual modules, and answers\n * its path. Its imports are bare (`deictic/client`, each plugin's), found from the project as its own\n * are. Written only when it changed, so a watching bundler doesn't rebuild for nothing.\n */\nexport function writeClient(root: string, plugins: ServerPlugin[], base: string, own?: Shortcut | false): string {\n const code = `// Written by deictic as the dev server starts: it starts the overlay in the page.\\n${clientModule(plugins, base, own)}\\n`;\n // Its own package: an ES module that runs for its effect. An app whose package.json says\n // `\"sideEffects\": false` would otherwise have webpack drop the import, which is only for its effect.\n const manifest = `${JSON.stringify({ private: true, type: 'module', sideEffects: true }, null, 2)}\\n`;\n writeIfChanged(keptIn(root, 'package.json'), manifest);\n return writeIfChanged(keptIn(root, 'client.js'), code);\n}\n\nfunction writeIfChanged(path: string, text: string): string {\n if (!existsSync(path) || readFileSync(path, 'utf8') !== text) writeFileSync(path, text);\n return path;\n}\n\n/** A module beside `url`, by its name: `.ts` from the source, `.js` from `dist`, as `url` is. */\nexport const beside = (url: string, name: string) =>\n fileURLToPath(new URL(`./${name}${url.endsWith('.ts') ? '.ts' : '.js'}`, url)).replaceAll('\\\\', '/');\n\n/**\n * The import of the written client module in the module at `from`, by a relative path with forward\n * slashes: Turbopack can't import a Windows path, and every bundler takes a relative one.\n */\nexport function importOf(path: string, from: string): string {\n const to = relative(dirname(from), path).replaceAll('\\\\', '/');\n return `\\nimport ${JSON.stringify(to.startsWith('.') ? to : `./${to}`)};\\n`;\n}\n\n/**\n * A module marked, by its absolute path: its host elements, and `append` after it (the client's import,\n * in the browser). Nothing for a file that isn't JSX, is a dependency's, or is outside the project.\n */\nexport function mark(code: string, path: string, root: string, append = ''): Located | undefined {\n const file = JSX.test(path) ? fileIn(path, root) : undefined;\n return file === undefined ? undefined : locate(code, file, append);\n}\n\n/** An `.astro` component marked, by its absolute path, as `mark` does a module. It's no module of the browser's, so nothing is appended. */\nexport function markAstro(code: string, path: string, root: string): Located | undefined {\n const file = ASTRO.test(path) ? fileIn(path, root) : undefined;\n return file === undefined ? undefined : locateAstro(code, file, root);\n}\n\n/** A project file's path from the root, as a mark has it; nothing for a dependency's or one outside the project. */\nfunction fileIn(path: string, root: string): string | undefined {\n if (/[\\\\/]node_modules[\\\\/]/.test(path) || !isAbsolute(path)) return undefined;\n const file = relative(root, path).replaceAll('\\\\', '/');\n return file.startsWith('..') || is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IAAI,CAAC,CAAC,WAAW,MAAM,GAAG;CAC7D,OAAO,YAAY,KAAK,UAAU,GAAG,WAAW,GAAG,IAAI,KAAK,KAAK,IAAI,EAAE;AACzE;;;;;AAMA,SAAgB,KAAK,MAAc,MAAc,MAAc,SAAS,IAAyB;CAC/F,MAAM,OAAO,IAAI,KAAK,IAAI,IAAI,OAAO,MAAM,IAAI,IAAI,KAAA;CACnD,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,OAAO,MAAM,MAAM,MAAM;AACnE;;AAGA,SAAgB,UAAU,MAAc,MAAc,MAAmC;CACvF,MAAM,OAAO,MAAM,KAAK,IAAI,IAAI,OAAO,MAAM,IAAI,IAAI,KAAA;CACrD,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,YAAY,MAAM,MAAM,IAAI;AACtE;;AAGA,SAAS,OAAO,MAAc,MAAkC;CAC9D,IAAI,yBAAyB,KAAK,IAAI,KAAK,CAAC,WAAW,IAAI,GAAG,OAAO,KAAA;CACrE,MAAM,OAAO,SAAS,MAAM,IAAI,CAAC,CAAC,WAAW,MAAM,GAAG;CACtD,OAAO,KAAK,WAAW,IAAI,KAAK,WAAW,IAAI,IAAI,KAAA,IAAY;AACjE"}
1
+ {"version":3,"file":"integration.js","names":["OWN","OWN"],"sources":["../../src/tools/locate.ts","../../src/tools/astro.ts","../../src/tools/problems.ts","../../src/tools/plugins.ts","../../src/tools/integration.ts"],"sourcesContent":["/**\n * Marks each host element in a JSX module with where its opening tag starts:\n * `<div data-deictic=\"src/App.tsx:12:5\">`. The page reads it back to know what was clicked.\n *\n * At build time and not from React's fibers at runtime: it works for any framework that compiles JSX,\n * for server components (which have no fiber in the browser), and it names the element's own tag\n * rather than the component that rendered it. Only host elements (`div`, `button`) are marked, since a\n * component may not pass the attribute on; a component's call site is reached from its elements.\n *\n * The transform must run on the source as written (`enforce: 'pre'` under Vite), so lines and columns\n * are the file's. It runs alike on the server and in the browser, so a hydrated page matches its HTML.\n */\nimport MagicString from 'magic-string';\nimport { type JSXOpeningElement, parseSync, type Program, Visitor } from 'oxc-parser';\n\nexport const ATTRIBUTE = 'data-deictic';\n/** Modules that may hold JSX: `.jsx` and `.tsx`, and plain `.js`, as many React projects write theirs. */\nexport const JSX = /\\.[cm]?(?:[jt]sx|js)$/;\n\n/** A module parsed, with JSX read in a `.js` file too, which the parser reads there only when told. */\nexport const parse = (file: string, code: string) => parseSync(file, code, /\\.[cm]?js$/.test(file) ? { lang: 'jsx' } : undefined);\n\nexport interface Located {\n code: string;\n map: ReturnType<MagicString['generateMap']>;\n}\n\n/** Whether an opening tag is a host element's, `<div>` or `<svg>`, not a component's or a namespaced one. */\nexport const isHost = (el: JSXOpeningElement) => el.name.type === 'JSXIdentifier' && /^[a-z]/.test(el.name.name);\n\n/**\n * `code` with every host element marked, `file` being its path from the project's root, and `append`\n * after it (the client's import, in the browser); nothing when there is nothing to mark, or the module\n * doesn't parse, which the framework's own transform reports better.\n */\nexport function locate(code: string, file: string, append = ''): Located | undefined {\n // No tag, no parse: most `.js` modules have none, and every one of the project's comes through here.\n if (!/<[a-z]/.test(code)) return undefined;\n const { program, errors } = parse(file, code);\n if (errors.length > 0) return undefined;\n return marked(code, file, openingsIn(program), append);\n}\n\n/** Every opening tag in a module, in its order. */\nexport function openingsIn(program: Program): JSXOpeningElement[] {\n const elements: JSXOpeningElement[] = [];\n new Visitor({ JSXOpeningElement: (el) => void elements.push(el) }).visit(program);\n return elements;\n}\n\n/**\n * `code` with a mark in each of `elements` that is a host element's and has none yet, and `append` after\n * it; nothing with none to mark.\n */\nexport function marked(code: string, file: string, elements: JSXOpeningElement[], append = ''): Located | undefined {\n const lines = lineStarts(code);\n const s = new MagicString(code);\n for (const el of elements) {\n if (!isHost(el) || el.attributes.some((a) => a.type === 'JSXAttribute' && nameOf(a.name) === ATTRIBUTE)) continue;\n const { line, column } = position(lines, el.start);\n s.appendLeft(el.name.end, ` ${ATTRIBUTE}=\"${file}:${line}:${column}\"`);\n }\n if (!s.hasChanged()) return undefined;\n if (append !== '') s.append(append);\n // A map's source is read from the module's own folder, so it's the file's name, not its path from the root.\n return { code: s.toString(), map: s.generateMap({ source: file.slice(file.lastIndexOf('/') + 1), hires: 'boundary' }) };\n}\n\nconst nameOf = (name: { type: string; name?: unknown }) => (name.type === 'JSXIdentifier' ? name.name : undefined);\n\n/** Where each line starts, by offset. */\nexport function lineStarts(code: string): number[] {\n const starts = [0];\n for (let i = code.indexOf('\\n'); i !== -1; i = code.indexOf('\\n', i + 1)) starts.push(i + 1);\n return starts;\n}\n\n/** An offset's line and column, from 1. */\nexport function position(lines: number[], offset: number): { line: number; column: number } {\n let lo = 0;\n let hi = lines.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (lines[mid]! <= offset) lo = mid;\n else hi = mid - 1;\n }\n return { line: lo + 1, column: offset - lines[lo]! + 1 };\n}\n\n/** A line and column's offset, or nothing past the file's end. */\nexport function offsetOf(lines: number[], line: number, column: number): number | undefined {\n const start = lines[line - 1];\n return start === undefined ? undefined : start + column - 1;\n}\n","/**\n * `.astro` components. They aren't JSX modules, but Astro 7's own parser reads a template as JSX, into the\n * tree oxc makes (offsets in UTF-16, as ours are), so its host elements are marked as a JSX module's are,\n * before Astro compiles the file. The parser is the project's own Astro's (`@astrojs/compiler-rs`, found\n * through `astro`), so it reads a file exactly as the compiler will; an Astro before 7 has none like it,\n * and its `.astro` files are left unmarked.\n */\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\n\nimport type { JSXOpeningElement, Program } from 'oxc-parser';\n\nimport { type Located, marked } from './locate.ts';\n\nexport const ASTRO = /\\.astro$/;\n\n/** A file parsed: its module (an `.astro` file's frontmatter), and each opening tag in it, in the file's order. */\nexport interface Parsed {\n program: Program;\n elements: JSXOpeningElement[];\n}\n\ninterface Tree {\n ast: { frontmatter: { program: Program }; body: unknown };\n diagnostics: { severity: string; text: string }[];\n}\ntype Parse = (code: string) => Tree;\n\nconst parsers = new Map<string, Parse | undefined>();\n\n/** The parser of the Astro installed for the project at `root`, loaded once; nothing without Astro 7. */\nfunction parserOf(root: string): Parse | undefined {\n if (!parsers.has(root)) parsers.set(root, load(root));\n return parsers.get(root);\n}\n\nfunction load(root: string): Parse | undefined {\n try {\n // Astro's own dependency, which a strict package manager doesn't put where the project could import it.\n const astro = createRequire(createRequire(join(root, 'package.json')).resolve('astro/package.json'));\n // An ES module, required: every Node that runs Astro 7 can, and reading a source stays synchronous.\n const compiler: { parse?: Parse } = astro('@astrojs/compiler-rs');\n return compiler.parse;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Astro gives a `<script>` or `<style>` with an attribute it doesn't know to the page as it is, unbundled and\n * unscoped, and a `<slot>` isn't an element at all: none of them can be pointed at, so none is marked.\n */\nconst OWN = new Set(['script', 'style', 'slot']);\n\nconst isOpening = (node: object): node is JSXOpeningElement => 'type' in node && node.type === 'JSXOpeningElement';\n\n/** An `.astro` file's text parsed, or the `problem` with it: no parser (an older Astro), or text that doesn't parse. */\nexport function parseAstro(root: string, code: string): Parsed | { problem: string } {\n const parse = parserOf(root);\n if (parse === undefined) return { problem: 'reading an .astro file takes Astro 7 or later, so update astro' };\n const { ast, diagnostics } = parse(code);\n const error = diagnostics.find((d) => d.severity === 'error');\n if (error !== undefined) return { problem: `fix it first (${error.text})` };\n const elements: JSXOpeningElement[] = [];\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) return node.forEach(walk);\n if (node === null || typeof node !== 'object') return;\n if (isOpening(node) && !(node.name.type === 'JSXIdentifier' && OWN.has(node.name.name))) elements.push(node);\n Object.values(node).forEach(walk);\n };\n walk(ast.body);\n return { program: ast.frontmatter.program, elements };\n}\n\n/** An `.astro` file's text with every host element marked, as `locate` marks a JSX module; nothing where it can't be read. */\nexport function locateAstro(code: string, file: string, root: string): Located | undefined {\n // No tag, no parse.\n if (!/<[a-z]/.test(code)) return undefined;\n const parsed = parseAstro(root, code);\n return 'problem' in parsed ? undefined : marked(code, file, parsed.elements);\n}\n","/**\n * deictic's problems on the server, and those the page sends (`/__deictic/problem`): each said once in the dev server's\n * output, and handed to every plugin with a `problem` once they're all set up, which the tasks plugin posts to the\n * board. Once per key while the dev server runs: a request that fails on every try is still one problem.\n */\nimport type { Problem, ServerPlugin } from '#src/index.ts';\n\n/** How much of a problem is kept: its words, and its details (a stack is shorter). */\nconst WORDS = 2000;\nconst DETAILS = 20_000;\n\nexport type Report = (problem: Problem) => void;\n\n/** What reports a problem: `ready` is when the plugins that hear of them are set up to. */\nexport function reporter(plugins: readonly ServerPlugin[], ready: () => Promise<unknown>): Report {\n const said = new Set<string>();\n return (problem) => {\n if (said.has(problem.key)) return;\n said.add(problem.key);\n console.warn(`deictic${problem.plugin === undefined ? '' : `/${problem.plugin}`}: ${problem.message}`);\n const hearing = plugins.filter((p) => p.problem !== undefined);\n if (hearing.length === 0) return;\n // Its own failure is said, not reported: a board that can't be reached would report itself for ever.\n const tell = async (plugin: ServerPlugin) => {\n try {\n await plugin.problem?.(problem);\n } catch (e) {\n console.warn(`deictic: ${plugin.name} couldn't take that problem, as ${messageOf(e)}`);\n }\n };\n // Later, never now: a setup that fails at once reports before what it's part of is ready to be waited for.\n void Promise.resolve()\n .then(ready)\n .then(\n () => Promise.all(hearing.map(tell)),\n () => {},\n );\n };\n}\n\n/** What went wrong, as a problem's words say it: an error's message. */\nexport const messageOf = (e: unknown) => (e instanceof Error ? e.message : String(e));\n\n/** An error's stack, where it has one, for a problem's details. */\nexport const stackOf = (e: unknown) => (e instanceof Error && e.stack !== undefined ? { details: e.stack } : {});\n\n/** A problem as the page sent it, checked and cut short, or nothing where it isn't one. */\nexport function problemIn(value: unknown): Problem | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const { key, kind, message, details, plugin } = value as Record<string, unknown>;\n if (typeof key !== 'string' || key === '' || typeof message !== 'string' || message === '') return undefined;\n if (kind !== 'setup' && kind !== 'bug') return undefined;\n return {\n key: key.slice(0, WORDS),\n kind,\n message: message.slice(0, WORDS),\n ...(typeof details === 'string' && details !== '' ? { details: details.slice(0, DETAILS) } : {}),\n ...(typeof plugin === 'string' && plugin !== '' ? { plugin: plugin.slice(0, 100) } : {}),\n };\n}\n","/**\n * The plugins an integration was given: checked as it starts, so a wrong set fails the dev server with\n * what to write instead, and set up once before the endpoints answer anything.\n */\nimport type { ServerContext, ServerPlugin } from '#src/index.ts';\nimport { checkShortcuts, OWN, ownShortcut, type Shortcut } from '#src/shortcut.ts';\n\nimport { messageOf, type Report, stackOf } from './problems.ts';\n\nconst NAME = /^[a-z][a-z0-9-]*$/;\n\n/** Throws what to fix in a set of plugins: names, what they need, and their shortcuts, beside deictic's own. */\nexport function checkPlugins(plugins: readonly ServerPlugin[], own?: Shortcut | false): void {\n const names = new Set<string>();\n for (const { name, client, shortcut } of plugins) {\n if (!NAME.test(name)) throw new Error(`deictic: a plugin is named \"${name}\": name it in lowercase letters, digits and -`);\n if (names.has(name)) throw new Error(`deictic: two plugins are named ${name}: load each once`);\n if (shortcut !== undefined && client === undefined)\n throw new Error(`deictic: ${name} has a shortcut but no \\`client\\` to draw its panel: give it one, or leave out its shortcut`);\n names.add(name);\n }\n for (const { name, needs = [] } of plugins) {\n const missing = needs.find((other) => !names.has(other));\n if (missing !== undefined) throw new Error(`deictic: ${name} needs the ${missing} plugin: add it to \\`plugins\\``);\n }\n checkShortcuts([{ name: OWN, shortcut: ownShortcut(own) }, ...plugins]);\n}\n\n/**\n * Runs every plugin's `setup`, all at once, and answers the context they share: `use` reads an API\n * when it's asked for, so setups may `use` each other's only after they've all run, from a route or an\n * op, never in `setup` itself. One that fails is reported and has no API: the others go on, so one of them\n * can tell of it (tasks, on the board).\n */\nexport async function setUp(root: string, plugins: readonly ServerPlugin[], report: Report): Promise<ServerContext> {\n const apis = new Map<string, unknown>();\n const context: ServerContext = { root, use: (name) => apis.get(name) as never, report };\n await Promise.all(\n plugins.map(async (p) => {\n if (p.setup === undefined) return;\n try {\n apis.set(p.name, await p.setup(context));\n } catch (e) {\n report({\n key: `setup:${p.name}`,\n kind: 'bug',\n plugin: p.name,\n message: `${p.name} failed to set up, so it does nothing until the dev server restarts: ${messageOf(e)}`,\n ...stackOf(e),\n });\n }\n }),\n );\n return context;\n}\n","/**\n * What every bundler's integration shares: the options, the client module that starts the overlay, and\n * the transform that marks a JSX module. Each integration adds what its bundler does its own way: how a\n * module is transformed (a hook, a loader, `onLoad`), how the page loads the client (a virtual module\n * under Vite, a file in `.deictic/` elsewhere, as webpack, Turbopack and Bun have none), where the\n * endpoints are served, and what opens the editor.\n */\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, isAbsolute, relative } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { ServerPlugin } from '#src/index.ts';\nimport { checkShortcuts, OWN, ownShortcut, type Shortcut } from '#src/shortcut.ts';\n\nimport { ASTRO, locateAstro } from './astro.ts';\nimport { keptIn } from './kept.ts';\nimport { JSX, locate, type Located } from './locate.ts';\nimport { checkPlugins } from './plugins.ts';\n\nexport interface DeicticOptions {\n /** The plugins to load, server halves: `tailwind()`, `tasks()`, your own. None by default. */\n plugins?: ServerPlugin[];\n /**\n * What opens the popup on any plugin, at the tab used last: Alt and the left button by default, or\n * `false` for none, leaving only plugins' own shortcuts.\n */\n shortcut?: Shortcut | false;\n}\n\n/** The options with their defaults, checked now, so a wrong set stops the dev server as it starts, not the page. */\nexport function prepare(options: DeicticOptions): { plugins: ServerPlugin[]; shortcut: Shortcut | false | undefined } {\n const plugins = options.plugins ?? [];\n checkPlugins(plugins, options.shortcut);\n return { plugins, shortcut: options.shortcut };\n}\n\n/**\n * The client module: the overlay, started with deictic's own shortcut and each plugin that has a half\n * in the page, with its shortcut, checked; and with `server`, a module of the page's that answers its requests\n * where no dev server does.\n */\nexport const clientModule = (plugins: ServerPlugin[], base: string, own?: Shortcut | false, server?: string) => {\n const [shortcut, ...shortcuts] = checkShortcuts([{ name: OWN, shortcut: ownShortcut(own) }, ...plugins]);\n const paged = plugins.flatMap((p, i) =>\n p.client === undefined ? [] : [{ client: p.client, rest: { shortcut: shortcuts[i], options: p.clientOptions } }],\n );\n return [\n `import { start } from 'deictic/client';`,\n ...paged.map((p, i) => `import p${i} from ${JSON.stringify(p.client)};`),\n ...(server === undefined ? [] : [`import server from ${JSON.stringify(server)};`]),\n // Its shortcut and options as JSON, where it has them: `JSON.stringify` leaves out what's undefined.\n `start({ base: ${JSON.stringify(base)}, shortcut: ${JSON.stringify(shortcut) ?? 'undefined'}, plugins: [${paged.map((p, i) => `{ plugin: p${i}, ...${JSON.stringify(p.rest)} }`).join(', ')}]${server === undefined ? '' : ', server'} });`,\n ].join('\\n');\n};\n\n/**\n * Writes the client module to `.deictic/client.js` for a bundler without virtual modules, and answers\n * its path. Its imports are bare (`deictic/client`, each plugin's), found from the project as its own\n * are. Written only when it changed, so a watching bundler doesn't rebuild for nothing.\n */\nexport function writeClient(root: string, plugins: ServerPlugin[], base: string, own?: Shortcut | false): string {\n const code = `// Written by deictic as the dev server starts: it starts the overlay in the page.\\n${clientModule(plugins, base, own)}\\n`;\n // Its own package: an ES module that runs for its effect. An app whose package.json says\n // `\"sideEffects\": false` would otherwise have webpack drop the import, which is only for its effect.\n const manifest = `${JSON.stringify({ private: true, type: 'module', sideEffects: true }, null, 2)}\\n`;\n writeIfChanged(keptIn(root, 'package.json'), manifest);\n return writeIfChanged(keptIn(root, 'client.js'), code);\n}\n\nfunction writeIfChanged(path: string, text: string): string {\n if (!existsSync(path) || readFileSync(path, 'utf8') !== text) writeFileSync(path, text);\n return path;\n}\n\n/** A module beside `url`, by its name: `.ts` from the source, `.js` from `dist`, as `url` is. */\nexport const beside = (url: string, name: string) =>\n fileURLToPath(new URL(`./${name}${url.endsWith('.ts') ? '.ts' : '.js'}`, url)).replaceAll('\\\\', '/');\n\n/**\n * The import of the written client module in the module at `from`, by a relative path with forward\n * slashes: Turbopack can't import a Windows path, and every bundler takes a relative one.\n */\nexport function importOf(path: string, from: string): string {\n const to = relative(dirname(from), path).replaceAll('\\\\', '/');\n return `\\nimport ${JSON.stringify(to.startsWith('.') ? to : `./${to}`)};\\n`;\n}\n\n/**\n * A module marked, by its absolute path: its host elements, and `append` after it (the client's import,\n * in the browser). Nothing for a file that isn't JSX, is a dependency's, or is outside the project.\n */\nexport function mark(code: string, path: string, root: string, append = ''): Located | undefined {\n const file = JSX.test(path) ? fileIn(path, root) : undefined;\n return file === undefined ? undefined : locate(code, file, append);\n}\n\n/** An `.astro` component marked, by its absolute path, as `mark` does a module. It's no module of the browser's, so nothing is appended. */\nexport function markAstro(code: string, path: string, root: string): Located | undefined {\n const file = ASTRO.test(path) ? fileIn(path, root) : undefined;\n return file === undefined ? undefined : locateAstro(code, file, root);\n}\n\n/** A project file's path from the root, as a mark has it; nothing for a dependency's or one outside the project. */\nfunction fileIn(path: string, root: string): string | undefined {\n if (/[\\\\/]node_modules[\\\\/]/.test(path) || !isAbsolute(path)) return undefined;\n const file = relative(root, path).replaceAll('\\\\', '/');\n return file.startsWith('..') || isAbsolute(file) ? undefined : file;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAeA,MAAa,YAAY;;AAEzB,MAAa,MAAM;;AAGnB,MAAa,SAAS,MAAc,SAAiB,UAAU,MAAM,MAAM,aAAa,KAAK,IAAI,IAAI,EAAE,MAAM,MAAM,IAAI,KAAA,CAAS;;AAQhI,MAAa,UAAU,OAA0B,GAAG,KAAK,SAAS,mBAAmB,SAAS,KAAK,GAAG,KAAK,IAAI;;;;;;AAO/G,SAAgB,OAAO,MAAc,MAAc,SAAS,IAAyB;CAEnF,IAAI,CAAC,SAAS,KAAK,IAAI,GAAG,OAAO,KAAA;CACjC,MAAM,EAAE,SAAS,WAAW,MAAM,MAAM,IAAI;CAC5C,IAAI,OAAO,SAAS,GAAG,OAAO,KAAA;CAC9B,OAAO,OAAO,MAAM,MAAM,WAAW,OAAO,GAAG,MAAM;AACvD;;AAGA,SAAgB,WAAW,SAAuC;CAChE,MAAM,WAAgC,CAAC;CACvC,IAAI,QA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AI,IAAI,KAAA;CACnD,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,OAAO,MAAM,MAAM,MAAM;AACnE;;AAGA,SAAgB,UAAU,MAAc,MAAc,MAAmC;CACvF,MAAM,OAAO,MAAM,KAAK,IAAI,IAAI,OAAO,MAAM,IAAI,IAAI,KAAA;CACrD,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,YAAY,MAAM,MAAM,IAAI;AACtE;;AAGA,SAAS,OAAO,MAAc,MAAkC;CAC9D,IAAI,yBAAyB,KAAK,IAAI,KAAK,CAAC,WAAW,IAAI,GAAG,OAAO,KAAA;CACrE,MAAM,OAAO,SAAS,MAAM,IAAI,CAAC,CAAC,WAAW,MAAM,GAAG;CACtD,OAAO,KAAK,WAAW,IAAI,KAAK,WAAW,IAAI,IAAI,KAAA,IAAY;AACjE"}
@@ -0,0 +1,23 @@
1
+ // package.json
2
+ var name = "deictic";
3
+ var version = "0.8.0";
4
+ var bugs = { "url": "https://github.com/gkurt/deictic/issues" };
5
+ var peerDependencies = {
6
+ "@rrweb/rrweb-plugin-console-record": "^2.2.2",
7
+ "@rrweb/rrweb-plugin-network-record": "^2.2.2",
8
+ "@rspack/core": ">=1",
9
+ "@vercel/board": ">=0.53.0",
10
+ "astro": ">=5",
11
+ "launch-editor": "^2.9.0",
12
+ "modern-screenshot": "^4.7.0",
13
+ "next": ">=16",
14
+ "playwright-core": "^1.50.0",
15
+ "rrweb": "^2.2.2",
16
+ "rrweb-player": "^2.2.2",
17
+ "rrweb-snapshot": "^2.2.2",
18
+ "vite": ">=6",
19
+ "webpack": ">=5"
20
+ };
21
+ export { version as i, name as n, peerDependencies as r, bugs as t };
22
+
23
+ //# sourceMappingURL=package.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":[""],"mappings":""}
@@ -1,25 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname, join } from "node:path";
4
- // package.json
5
- var name = "deictic";
6
- var version = "0.7.0";
7
- var peerDependencies = {
8
- "@rrweb/rrweb-plugin-console-record": "^2.2.2",
9
- "@rrweb/rrweb-plugin-network-record": "^2.2.2",
10
- "@rspack/core": ">=1",
11
- "@vercel/board": ">=0.53.0",
12
- "astro": ">=5",
13
- "launch-editor": "^2.9.0",
14
- "modern-screenshot": "^4.7.0",
15
- "next": ">=16",
16
- "playwright-core": "^1.50.0",
17
- "rrweb": "^2.2.2",
18
- "rrweb-player": "^2.2.2",
19
- "rrweb-snapshot": "^2.2.2",
20
- "vite": ">=6",
21
- "webpack": ">=5"
22
- };
4
+ import { i as version, n as name, r as peerDependencies } from "./package.js";
23
5
  // src/tools/packages.ts
24
6
  /**
25
7
  * The packages plugins import that the project installs itself (`ServerPlugin.packages`: deictic's optional peers,
@@ -119,14 +101,23 @@ function missing(root, plugins) {
119
101
  }];
120
102
  });
121
103
  }
122
- /** What to say as the dev server starts when plugins' packages are missing: which, and the command that installs them. */
123
- function missingMessage(root, plugins) {
104
+ /**
105
+ * What to report as the dev server starts when plugins' packages are missing: which, and the command that installs
106
+ * them. Its key names them, so a problem fixed and then another missing is a new one.
107
+ */
108
+ function missingProblem(root, plugins) {
124
109
  const gone = missing(root, plugins);
125
110
  if (gone.length === 0) return void 0;
126
111
  const names = [...new Set(gone.flatMap((g) => g.packages))];
127
112
  const which = gone.map((g) => g.plugin);
128
- return `deictic: install what ${which.length === 1 ? which[0] : `${which.slice(0, -1).join(", ")} and ${which.at(-1)}`} ${which.length === 1 ? "needs" : "need"}: ${installCommand(packageManager(root), names, root)}`;
113
+ const who = which.length === 1 ? which[0] : `${which.slice(0, -1).join(", ")} and ${which.at(-1)}`;
114
+ const need = which.length === 1 ? "needs" : "need";
115
+ return {
116
+ key: `packages:${[...names].sort().join(",")}`,
117
+ kind: "setup",
118
+ message: `install what ${who} ${need}, then restart the dev server: ${installCommand(packageManager(root), names, root)}`
119
+ };
129
120
  }
130
- export { readJson as a, packageManager as i, installCommand as n, runnerOf as o, missingMessage as r, execOf as t };
121
+ export { readJson as a, packageManager as i, installCommand as n, runnerOf as o, missingProblem as r, execOf as t };
131
122
 
132
123
  //# sourceMappingURL=packages.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"packages.js","names":["name","manifest.name","manifest.version","manifest.peerDependencies"],"sources":["../../package.json","../../src/tools/packages.ts"],"sourcesContent":["","/**\n * The packages plugins import that the project installs itself (`ServerPlugin.packages`: deictic's optional peers,\n * or a plugin's own), and how to install them with the project's package manager. A missing one is said as the dev\n * server starts, with the command that installs it, not on the first shot or recording, where it would fail.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\n\nimport manifest from '#package.json' with { type: 'json' };\nimport type { ServerPlugin } from '#src/index.ts';\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';\n\n/** Each package manager's lockfiles, in the order they're looked for in a folder. */\nconst LOCKS: [string, PackageManager][] = [\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['package-lock.json', 'npm'],\n];\nconst MANAGERS: PackageManager[] = ['npm', 'pnpm', 'yarn', 'bun'];\n\n/**\n * The project's package manager: its `packageManager` field, or the lockfile nearest the root (a workspace's is\n * above it), or the one running this (`npm_config_user_agent`), or npm. The lockfile wins over what runs this,\n * as `npx deictic init` runs under npm in a project of any manager's.\n */\nexport function packageManager(root: string, agent = process.env.npm_config_user_agent): PackageManager {\n for (let dir = root; ; dir = dirname(dir)) {\n const field = fieldOf(dir);\n if (field !== undefined) return field;\n const lock = LOCKS.find(([file]) => existsSync(join(dir, file)));\n if (lock !== undefined) return lock[1];\n if (dirname(dir) === dir) break;\n }\n const running = agent?.split('/')[0];\n return MANAGERS.find((m) => m === running) ?? 'npm';\n}\n\n/** A package.json's `packageManager` (`pnpm@9.1.0`), by its manager's name. */\nfunction fieldOf(dir: string): PackageManager | undefined {\n const field = readJson(join(dir, 'package.json'))?.packageManager;\n const name = typeof field === 'string' ? field.split('@')[0] : undefined;\n return MANAGERS.find((m) => m === name);\n}\n\nexport function readJson(path: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A package as the install command names it: with deictic's range for it where it's one of deictic's peers (rrweb's\n * packages must agree), or deictic's own version for deictic. Quoted, as `>` and `^` are a shell's.\n */\nexport function specOf(name: string): string {\n const range = name === manifest.name ? `^${manifest.version}` : (manifest.peerDependencies as Record<string, string>)[name];\n return range === undefined ? name : `\"${name}@${range}\"`;\n}\n\n/** The command that adds `names` to the project's dev dependencies. A pnpm workspace's root takes them only with `-w`. */\nexport function installCommand(manager: PackageManager, names: readonly string[], root: string): string {\n const add = {\n npm: 'npm install -D',\n pnpm: existsSync(join(root, 'pnpm-workspace.yaml')) ? 'pnpm add -D -w' : 'pnpm add -D',\n yarn: 'yarn add -D',\n bun: 'bun add -d',\n }[manager];\n return [add, ...names.map(specOf)].join(' ');\n}\n\n/** What runs a package's CLI without installing it, for the manager: `npx`, `bunx`. */\nexport const runnerOf = (manager: PackageManager) => ({ npm: 'npx', pnpm: 'pnpm dlx', yarn: 'npx', bun: 'bunx' })[manager];\n\n/** What runs a CLI the project installed, for the manager: `npx`, `bunx`, each the project's own version. */\nexport const execOf = (manager: PackageManager) => ({ npm: 'npx', pnpm: 'pnpm exec', yarn: 'yarn', bun: 'bunx' })[manager];\n\n/** Whether the project can import `name`: it's found from the root, as the bundler and deictic's own imports find it. */\nexport function installed(root: string, name: string): boolean {\n try {\n createRequire(join(root, 'package.json')).resolve(`${name}/package.json`);\n return true;\n } catch (e) {\n // There, but its `exports` don't name its package.json: only \"not found\" means it's missing.\n return (e as { code?: string }).code !== 'MODULE_NOT_FOUND';\n }\n}\n\n/** Each plugin with the packages it imports that the project hasn't installed, where it has any. */\nexport function missing(root: string, plugins: readonly ServerPlugin[]): { plugin: string; packages: string[] }[] {\n return plugins.flatMap(({ name, packages = [] }) => {\n const gone = packages.filter((p) => !installed(root, p));\n return gone.length === 0 ? [] : [{ plugin: name, packages: gone }];\n });\n}\n\n/** What to say as the dev server starts when plugins' packages are missing: which, and the command that installs them. */\nexport function missingMessage(root: string, plugins: readonly ServerPlugin[]): string | undefined {\n const gone = missing(root, plugins);\n if (gone.length === 0) return undefined;\n const names = [...new Set(gone.flatMap((g) => g.packages))];\n const which = gone.map((g) => g.plugin);\n const who = which.length === 1 ? which[0] : `${which.slice(0, -1).join(', ')} and ${which.at(-1)}`;\n return `deictic: install what ${who} ${which.length === 1 ? 'needs' : 'need'}: ${installCommand(packageManager(root), names, root)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACeA,MAAM,QAAoC;CACxC,CAAC,YAAY,KAAK;CAClB,CAAC,aAAa,KAAK;CACnB,CAAC,kBAAkB,MAAM;CACzB,CAAC,aAAa,MAAM;CACpB,CAAC,qBAAqB,KAAK;AAC7B;AACA,MAAM,WAA6B;CAAC;CAAO;CAAQ;CAAQ;AAAK;;;;;;AAOhE,SAAgB,eAAe,MAAc,QAAQ,QAAQ,IAAI,uBAAuC;CACtG,KAAK,IAAI,MAAM,OAAQ,MAAM,QAAQ,GAAG,GAAG;EACzC,MAAM,QAAQ,QAAQ,GAAG;EACzB,IAAI,UAAU,KAAA,GAAW,OAAO;EAChC,MAAM,OAAO,MAAM,MAAM,CAAC,UAAU,WAAW,KAAK,KAAK,IAAI,CAAC,CAAC;EAC/D,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK;EACpC,IAAI,QAAQ,GAAG,MAAM,KAAK;CAC5B;CACA,MAAM,UAAU,OAAO,MAAM,GAAG,CAAC,CAAC;CAClC,OAAO,SAAS,MAAM,MAAM,MAAM,OAAO,KAAK;AAChD;;AAGA,SAAS,QAAQ,KAAyC;CACxD,MAAM,QAAQ,SAAS,KAAK,KAA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I,CAAC;GAAE,QAAQ;GAAM,UAAU;EAAK,CAAC;CACnE,CAAC;AACH;;AAGA,SAAgB,eAAe,MAAc,SAAsD;CACjG,MAAM,OAAO,QAAQ,MAAM,OAAO;CAClC,IAAI,KAAK,WAAW,GAAG,OAAO,KAAA;CAC9B,MAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,KAAK,SAAS,MAAM,EAAE,QAAQ,CAAC,CAAC;CAC1D,MAAM,QAAQ,KAAK,KAAK,MAAM,EAAE,MAAM;CAEtC,OAAO,yBADK,MAAM,WAAW,IAAI,MAAM,KAAK,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,OAAO,MAAM,GAAG,EAAE,IAC3D,GAAG,MAAM,WAAW,IAAI,UAAU,OAAO,IAAI,eAAe,eAAe,IAAI,GAAG,OAAO,IAAI;AACnI"}
1
+ {"version":3,"file":"packages.js","names":["name","manifest.name","manifest.version","manifest.peerDependencies"],"sources":["../../src/tools/packages.ts"],"sourcesContent":["/**\n * The packages plugins import that the project installs itself (`ServerPlugin.packages`: deictic's optional peers,\n * or a plugin's own), and how to install them with the project's package manager. A missing one is said as the dev\n * server starts, with the command that installs it, not on the first shot or recording, where it would fail.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\n\nimport manifest from '#package.json' with { type: 'json' };\nimport type { Problem, ServerPlugin } from '#src/index.ts';\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';\n\n/** Each package manager's lockfiles, in the order they're looked for in a folder. */\nconst LOCKS: [string, PackageManager][] = [\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['package-lock.json', 'npm'],\n];\nconst MANAGERS: PackageManager[] = ['npm', 'pnpm', 'yarn', 'bun'];\n\n/**\n * The project's package manager: its `packageManager` field, or the lockfile nearest the root (a workspace's is\n * above it), or the one running this (`npm_config_user_agent`), or npm. The lockfile wins over what runs this,\n * as `npx deictic init` runs under npm in a project of any manager's.\n */\nexport function packageManager(root: string, agent = process.env.npm_config_user_agent): PackageManager {\n for (let dir = root; ; dir = dirname(dir)) {\n const field = fieldOf(dir);\n if (field !== undefined) return field;\n const lock = LOCKS.find(([file]) => existsSync(join(dir, file)));\n if (lock !== undefined) return lock[1];\n if (dirname(dir) === dir) break;\n }\n const running = agent?.split('/')[0];\n return MANAGERS.find((m) => m === running) ?? 'npm';\n}\n\n/** A package.json's `packageManager` (`pnpm@9.1.0`), by its manager's name. */\nfunction fieldOf(dir: string): PackageManager | undefined {\n const field = readJson(join(dir, 'package.json'))?.packageManager;\n const name = typeof field === 'string' ? field.split('@')[0] : undefined;\n return MANAGERS.find((m) => m === name);\n}\n\nexport function readJson(path: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A package as the install command names it: with deictic's range for it where it's one of deictic's peers (rrweb's\n * packages must agree), or deictic's own version for deictic. Quoted, as `>` and `^` are a shell's.\n */\nexport function specOf(name: string): string {\n const range = name === manifest.name ? `^${manifest.version}` : (manifest.peerDependencies as Record<string, string>)[name];\n return range === undefined ? name : `\"${name}@${range}\"`;\n}\n\n/** The command that adds `names` to the project's dev dependencies. A pnpm workspace's root takes them only with `-w`. */\nexport function installCommand(manager: PackageManager, names: readonly string[], root: string): string {\n const add = {\n npm: 'npm install -D',\n pnpm: existsSync(join(root, 'pnpm-workspace.yaml')) ? 'pnpm add -D -w' : 'pnpm add -D',\n yarn: 'yarn add -D',\n bun: 'bun add -d',\n }[manager];\n return [add, ...names.map(specOf)].join(' ');\n}\n\n/** What runs a package's CLI without installing it, for the manager: `npx`, `bunx`. */\nexport const runnerOf = (manager: PackageManager) => ({ npm: 'npx', pnpm: 'pnpm dlx', yarn: 'npx', bun: 'bunx' })[manager];\n\n/** What runs a CLI the project installed, for the manager: `npx`, `bunx`, each the project's own version. */\nexport const execOf = (manager: PackageManager) => ({ npm: 'npx', pnpm: 'pnpm exec', yarn: 'yarn', bun: 'bunx' })[manager];\n\n/** Whether the project can import `name`: it's found from the root, as the bundler and deictic's own imports find it. */\nexport function installed(root: string, name: string): boolean {\n try {\n createRequire(join(root, 'package.json')).resolve(`${name}/package.json`);\n return true;\n } catch (e) {\n // There, but its `exports` don't name its package.json: only \"not found\" means it's missing.\n return (e as { code?: string }).code !== 'MODULE_NOT_FOUND';\n }\n}\n\n/** Each plugin with the packages it imports that the project hasn't installed, where it has any. */\nexport function missing(root: string, plugins: readonly ServerPlugin[]): { plugin: string; packages: string[] }[] {\n return plugins.flatMap(({ name, packages = [] }) => {\n const gone = packages.filter((p) => !installed(root, p));\n return gone.length === 0 ? [] : [{ plugin: name, packages: gone }];\n });\n}\n\n/**\n * What to report as the dev server starts when plugins' packages are missing: which, and the command that installs\n * them. Its key names them, so a problem fixed and then another missing is a new one.\n */\nexport function missingProblem(root: string, plugins: readonly ServerPlugin[]): Problem | undefined {\n const gone = missing(root, plugins);\n if (gone.length === 0) return undefined;\n const names = [...new Set(gone.flatMap((g) => g.packages))];\n const which = gone.map((g) => g.plugin);\n const who = which.length === 1 ? which[0] : `${which.slice(0, -1).join(', ')} and ${which.at(-1)}`;\n const need = which.length === 1 ? 'needs' : 'need';\n return {\n key: `packages:${[...names].sort().join(',')}`,\n kind: 'setup',\n message: `install what ${who} ${need}, then restart the dev server: ${installCommand(packageManager(root), names, root)}`,\n };\n}\n"],"mappings":";;;;;;;;;;;AAeA,MAAM,QAAoC;CACxC,CAAC,YAAY,KAAK;CAClB,CAAC,aAAa,KAAK;CACnB,CAAC,kBAAkB,MAAM;CACzB,CAAC,aAAa,MAAM;CACpB,CAAC,qBAAqB,KAAK;AAC7B;AACA,MAAM,WAA6B;CAAC;CAAO;CAAQ;CAAQ;AAAK;;;;;;AAOhE,SAAgB,eAAe,MAAc,QAAQ,QAAQ,IAAI,u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be read");
89
89
  await doc.fonts.ready;
90
90
  await Promise.all([...doc.images].map((img) => img.decode().catch(() => {})));
91
- iframe.contentWindow?.scrollTo(scroll.x, scroll.y);
91
+ iframe.contentWindow?.scrollTo({
92
+ left: scroll.x,
93
+ top: scroll.y,
94
+ behavior: "instant"
95
+ });
92
96
  const isElement = (node) => node?.nodeType === 1;
93
97
  for (const id of mirror.getIds()) {
94
98
  const node = mirror.getNode(id);
95
99
  const meta = node === null ? null : mirror.getMeta(node);
96
100
  if (!isElement(node) || meta === null || !("attributes" in meta)) continue;
97
101
  const { rr_scrollTop: top, rr_scrollLeft: left } = meta.attributes;
98
- if (typeof top === "number") node.scrollTop = top;
99
- if (typeof left === "number") node.scrollLeft = left;
102
+ if (typeof top !== "number" && typeof left !== "number") continue;
103
+ node.scrollTo({
104
+ top: typeof top === "number" ? top : node.scrollTop,
105
+ left: typeof left === "number" ? left : node.scrollLeft,
106
+ behavior: "instant"
107
+ });
100
108
  }
101
109
  const node = element === void 0 ? null : mirror.getNode(element);
102
110
  const rect = isElement(node) ? node.getBoundingClientRect() : void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"playwright.js","names":[],"sources":["../../src/plugins/screenshots/playwright.ts"],"sourcesContent":["/**\n * The `rrweb()` renderer's server half: rebuilds a page's snapshot in a browser beside the dev server and\n * screenshots it at the page's viewport, scroll and pixel density, so text lays out as the page's does. The\n * browser is launched on the first shot and kept for the next; Playwright closes it with the process.\n *\n * The snapshot is rebuilt into a sandboxed iframe filling a blank page on the page's own origin, which\n * Playwright answers itself, so nothing asks the dev server for it: rrweb has made the snapshot's URLs\n * whole, and its stylesheets' fonts and images load from the dev server as the page's did.\n *\n * The browser is as big as the page's window, scrollbars and all, and shows its own: a media query asks the\n * window's width, and the page is laid out in what the scrollbar leaves. At the width without it, a window\n * right on a breakpoint (1024 wide, 1009 to lay out in) would render as the narrower layout. The shot is then\n * cut to the part the page is in.\n */\nimport { createRequire } from 'node:module';\n\nimport type { Browser } from 'playwright-core';\nimport type * as Rrweb from 'rrweb-snapshot';\n\nimport type { Box, BrowserOptions } from './index.ts';\n\n/** What the page sends: its snapshot and what's needed to show it as the page does. */\n/** A node of an rrweb snapshot, as `snapshot()` answers it. */\nexport type SnapshotNode = NonNullable<ReturnType<typeof Rrweb.snapshot>>;\n\nexport interface Snapshot {\n snapshot: SnapshotNode;\n url: string;\n viewport: { width: number; height: number };\n /** The window's size, scrollbars included, where it has any: what the page's media queries ask. */\n window?: { width: number; height: number };\n scroll: { x: number; y: number };\n scale: number;\n /** The element the shot is of, as the snapshot numbers its nodes: found again in the rebuilt page, for where it is there. */\n element?: number;\n /** The part of the viewport to keep, for a shot of an element alone: where the element was in the page. */\n clip?: Box;\n /** An SVG the viewport's size, drawn over the page: the annotations, where there are any. */\n overlay?: string;\n}\n\nconst HOST = '<!doctype html><html><body style=\"margin:0\"></body></html>';\n\nconst browsers = new Map<string, Promise<Browser>>();\n\n/** A browser by the options, launched once: the one named, or Playwright's own Chromium, then Chrome, then Edge. */\nexport function browserOf(options: BrowserOptions): Promise<Browser> {\n const key = JSON.stringify(options);\n const known = browsers.get(key);\n if (known !== undefined) return known;\n const launched = launch(options);\n browsers.set(key, launched);\n // A launch that failed is tried again on the next shot, after the user installs what it said to.\n launched.catch(() => browsers.delete(key));\n return launched;\n}\n\n/** Playwright hides a headless browser's scrollbars, and with them the room they take in the page. */\nconst SCROLLBARS = { ignoreDefaultArgs: ['--hide-scrollbars'] };\n\nasync function launch({ executablePath, channel }: BrowserOptions): Promise<Browser> {\n const { chromium } = await import('playwright-core').catch((e: unknown) => {\n throw new Error('the rrweb() renderer needs playwright-core: add it to your devDependencies', { cause: e });\n });\n if (executablePath !== undefined || channel !== undefined) return chromium.launch({ executablePath, channel, ...SCROLLBARS });\n const tried: string[] = [];\n for (const attempt of [{}, { channel: 'chrome' }, { channel: 'msedge' }]) {\n try {\n return await chromium.launch({ ...attempt, ...SCROLLBARS });\n } catch (e) {\n tried.push(\n `${'channel' in attempt ? attempt.channel : \"Playwright's Chromium\"}: ${(e instanceof Error ? e.message : String(e)).split('\\n', 1)[0]}`,\n );\n }\n }\n throw new Error(\n `the rrweb() renderer found no browser to render in (${tried.join('; ')}): run \\`npx playwright install chromium\\`, or pass rrweb({ executablePath })`,\n );\n}\n\n/** The rrweb-snapshot bundle that defines `rrwebSnapshot` in a page: its CommonJS entry is that bundle. */\nconst bundle = () => createRequire(import.meta.url).resolve('rrweb-snapshot');\n\n/**\n * The PNG, and where the element is in it. That's measured in the rebuilt page, not taken from the live one: the\n * two can lay out a few pixels apart (a font that loaded differently, a panel's own scroll), and an outline drawn\n * at the live page's box would then cross the element.\n */\nexport async function render(input: unknown, options: BrowserOptions): Promise<{ png: Uint8Array; box?: Box }> {\n const shot = input as Snapshot;\n if (typeof shot?.url !== 'string' || typeof shot.snapshot !== 'object' || typeof shot.viewport?.width !== 'number')\n throw new Error('screenshots: that is not a snapshot the rrweb() renderer took');\n const browser = await browserOf(options);\n const context = await browser.newContext({ viewport: shot.window ?? shot.viewport, deviceScaleFactor: shot.scale });\n try {\n const page = await context.newPage();\n const host = new URL('/__deictic/plugins/screenshots/host', shot.url).href;\n await page.route(host, (route) => route.fulfill({ contentType: 'text/html', body: HOST }));\n await page.goto(host);\n await page.addScriptTag({ path: bundle() });\n const found = await page.evaluate(async ({ snapshot, scroll, overlay, element }) => {\n const { rebuildIntoSandboxedIframe, createCache, createMirror } = (globalThis as unknown as { rrwebSnapshot: typeof Rrweb })\n .rrwebSnapshot;\n const mirror = createMirror();\n const { iframe } = rebuildIntoSandboxedIframe(snapshot, {\n root: document.body,\n cache: createCache(),\n mirror,\n iframeAttributes: { style: 'border:0;position:fixed;inset:0;width:100vw;height:100vh' },\n });\n const doc = iframe.contentDocument;\n if (doc === null) throw new Error('screenshots: the snapshot was rebuilt where it cannot be read');\n await doc.fonts.ready;\n await Promise.all([...doc.images].map((img) => img.decode().catch(() => {})));\n iframe.contentWindow?.scrollTo(scroll.x, scroll.y);\n // rrweb scrolled each element as it built it, before the fonts and images gave its content its height:\n // one that couldn't scroll that far yet is scrolled again now.\n // By its kind: the iframe's elements aren't instances of this page's `Element`.\n const isElement = (node: Node | null): node is Element => node?.nodeType === 1;\n for (const id of mirror.getIds()) {\n const node = mirror.getNode(id);\n const meta = node === null ? null : mirror.getMeta(node);\n if (!isElement(node) || meta === null || !('attributes' in meta)) continue;\n const { rr_scrollTop: top, rr_scrollLeft: left } = meta.attributes;\n if (typeof top === 'number') node.scrollTop = top;\n if (typeof left === 'number') node.scrollLeft = left;\n }\n const node = element === undefined ? null : mirror.getNode(element);\n // The iframe fills the page from its top left, so a box in it is one in the shot.\n const rect = isElement(node) ? node.getBoundingClientRect() : undefined;\n const box = rect === undefined ? undefined : { x: rect.x, y: rect.y, width: rect.width, height: rect.height };\n if (overlay === undefined) return box;\n // Over the page and its scroll: the SVG is the viewport's, already where it scrolled to.\n const marks = document.createElement('div');\n marks.style.cssText = 'position:fixed;inset:0;z-index:1;pointer-events:none';\n marks.innerHTML = overlay;\n document.body.append(marks);\n return box;\n }, shot);\n // Without the scrollbars: a shot is what the page is drawn in, which is what an element's box is from.\n // A shot of the element alone is cut where the element is here.\n const clip = clamp(shot.clip === undefined ? { x: 0, y: 0, ...shot.viewport } : (found ?? shot.clip), shot.viewport);\n const png = new Uint8Array(await page.screenshot({ type: 'png', ...(clip === undefined ? {} : { clip }) }));\n return { png, ...(found === undefined || shot.clip !== undefined ? {} : { box: found }) };\n } finally {\n await context.close();\n }\n}\n\n/** A box kept within the viewport: an element partly scrolled out of it shows only the part that's in. */\nfunction clamp(box: Box, viewport: { width: number; height: number }): Box | undefined {\n const x = Math.max(0, box.x);\n const y = Math.max(0, box.y);\n const width = Math.min(viewport.width, box.x + box.width) - x;\n const height = Math.min(viewport.height, box.y + box.height) - y;\n return width > 0 && height > 0 ? { x, y, width, height } : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAA8B;;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QAAQ,IAAI,IAAI,IAAI,MAAM,IAAI;CAC/D,OAAO,QAAQ,KAAK,SAAS,IAAI;EAAE;EAAG;EAAG;EAAO;CAAO,IAAI,KAAA;AAC7D"}
1
+ {"version":3,"file":"playwright.js","names":[],"sources":["../../src/plugins/screenshots/playwright.ts"],"sourcesContent":["/**\n * The `rrweb()` renderer's server half: rebuilds a page's snapshot in a browser beside the dev server and\n * screenshots it at the page's viewport, scroll and pixel density, so text lays out as the page's does. The\n * browser is launched on the first shot and kept for the next; Playwright closes it with the process.\n *\n * The snapshot is rebuilt into a sandboxed iframe filling a blank page on the page's own origin, which\n * Playwright answers itself, so nothing asks the dev server for it: rrweb has made the snapshot's URLs\n * whole, and its stylesheets' fonts and images load from the dev server as the page's did.\n *\n * The browser is as big as the page's window, scrollbars and all, and shows its own: a media query asks the\n * window's width, and the page is laid out in what the scrollbar leaves. At the width without it, a window\n * right on a breakpoint (1024 wide, 1009 to lay out in) would render as the narrower layout. The shot is then\n * cut to the part the page is in.\n */\nimport { createRequire } from 'node:module';\n\nimport type { Browser } from 'playwright-core';\nimport type * as Rrweb from 'rrweb-snapshot';\n\nimport type { Box, BrowserOptions } from './index.ts';\n\n/** What the page sends: its snapshot and what's needed to show it as the page does. */\n/** A node of an rrweb snapshot, as `snapshot()` answers it. */\nexport type SnapshotNode = NonNullable<ReturnType<typeof Rrweb.snapshot>>;\n\nexport interface Snapshot {\n snapshot: SnapshotNode;\n url: string;\n viewport: { width: number; height: number };\n /** The window's size, scrollbars included, where it has any: what the page's media queries ask. */\n window?: { width: number; height: number };\n scroll: { x: number; y: number };\n scale: number;\n /** The element the shot is of, as the snapshot numbers its nodes: found again in the rebuilt page, for where it is there. */\n element?: number;\n /** The part of the viewport to keep, for a shot of an element alone: where the element was in the page. */\n clip?: Box;\n /** An SVG the viewport's size, drawn over the page: the annotations, where there are any. */\n overlay?: string;\n}\n\nconst HOST = '<!doctype html><html><body style=\"margin:0\"></body></html>';\n\nconst browsers = new Map<string, Promise<Browser>>();\n\n/** A browser by the options, launched once: the one named, or Playwright's own Chromium, then Chrome, then Edge. */\nexport function browserOf(options: BrowserOptions): Promise<Browser> {\n const key = JSON.stringify(options);\n const known = browsers.get(key);\n if (known !== undefined) return known;\n const launched = launch(options);\n browsers.set(key, launched);\n // A launch that failed is tried again on the next shot, after the user installs what it said to.\n launched.catch(() => browsers.delete(key));\n return launched;\n}\n\n/** Playwright hides a headless browser's scrollbars, and with them the room they take in the page. */\nconst SCROLLBARS = { ignoreDefaultArgs: ['--hide-scrollbars'] };\n\nasync function launch({ executablePath, channel }: BrowserOptions): Promise<Browser> {\n const { chromium } = await import('playwright-core').catch((e: unknown) => {\n throw new Error('the rrweb() renderer needs playwright-core: add it to your devDependencies', { cause: e });\n });\n if (executablePath !== undefined || channel !== undefined) return chromium.launch({ executablePath, channel, ...SCROLLBARS });\n const tried: string[] = [];\n for (const attempt of [{}, { channel: 'chrome' }, { channel: 'msedge' }]) {\n try {\n return await chromium.launch({ ...attempt, ...SCROLLBARS });\n } catch (e) {\n tried.push(\n `${'channel' in attempt ? attempt.channel : \"Playwright's Chromium\"}: ${(e instanceof Error ? e.message : String(e)).split('\\n', 1)[0]}`,\n );\n }\n }\n throw new Error(\n `the rrweb() renderer found no browser to render in (${tried.join('; ')}): run \\`npx playwright install chromium\\`, or pass rrweb({ executablePath })`,\n );\n}\n\n/** The rrweb-snapshot bundle that defines `rrwebSnapshot` in a page: its CommonJS entry is that bundle. */\nconst bundle = () => createRequire(import.meta.url).resolve('rrweb-snapshot');\n\n/**\n * The PNG, and where the element is in it. That's measured in the rebuilt page, not taken from the live one: the\n * two can lay out a few pixels apart (a font that loaded differently, a panel's own scroll), and an outline drawn\n * at the live page's box would then cross the element.\n */\nexport async function render(input: unknown, options: BrowserOptions): Promise<{ png: Uint8Array; box?: Box }> {\n const shot = input as Snapshot;\n if (typeof shot?.url !== 'string' || typeof shot.snapshot !== 'object' || typeof shot.viewport?.width !== 'number')\n throw new Error('screenshots: that is not a snapshot the rrweb() renderer took');\n const browser = await browserOf(options);\n const context = await browser.newContext({ viewport: shot.window ?? shot.viewport, deviceScaleFactor: shot.scale });\n try {\n const page = await context.newPage();\n const host = new URL('/__deictic/plugins/screenshots/host', shot.url).href;\n await page.route(host, (route) => route.fulfill({ contentType: 'text/html', body: HOST }));\n await page.goto(host);\n await page.addScriptTag({ path: bundle() });\n const found = await page.evaluate(async ({ snapshot, scroll, overlay, element }) => {\n const { rebuildIntoSandboxedIframe, createCache, createMirror } = (globalThis as unknown as { rrwebSnapshot: typeof Rrweb })\n .rrwebSnapshot;\n const mirror = createMirror();\n const { iframe } = rebuildIntoSandboxedIframe(snapshot, {\n root: document.body,\n cache: createCache(),\n mirror,\n iframeAttributes: { style: 'border:0;position:fixed;inset:0;width:100vw;height:100vh' },\n });\n const doc = iframe.contentDocument;\n if (doc === null) throw new Error('screenshots: the snapshot was rebuilt where it cannot be read');\n await doc.fonts.ready;\n await Promise.all([...doc.images].map((img) => img.decode().catch(() => {})));\n // At once: a page with `scroll-behavior: smooth` would glide there, and be shot on its way.\n iframe.contentWindow?.scrollTo({ left: scroll.x, top: scroll.y, behavior: 'instant' });\n // rrweb scrolled each element as it built it, before the fonts and images gave its content its height:\n // one that couldn't scroll that far yet is scrolled again now.\n // By its kind: the iframe's elements aren't instances of this page's `Element`.\n const isElement = (node: Node | null): node is Element => node?.nodeType === 1;\n for (const id of mirror.getIds()) {\n const node = mirror.getNode(id);\n const meta = node === null ? null : mirror.getMeta(node);\n if (!isElement(node) || meta === null || !('attributes' in meta)) continue;\n const { rr_scrollTop: top, rr_scrollLeft: left } = meta.attributes;\n if (typeof top !== 'number' && typeof left !== 'number') continue;\n node.scrollTo({\n top: typeof top === 'number' ? top : node.scrollTop,\n left: typeof left === 'number' ? left : node.scrollLeft,\n behavior: 'instant',\n });\n }\n const node = element === undefined ? null : mirror.getNode(element);\n // The iframe fills the page from its top left, so a box in it is one in the shot.\n const rect = isElement(node) ? node.getBoundingClientRect() : undefined;\n const box = rect === undefined ? undefined : { x: rect.x, y: rect.y, width: rect.width, height: rect.height };\n if (overlay === undefined) return box;\n // Over the page and its scroll: the SVG is the viewport's, already where it scrolled to.\n const marks = document.createElement('div');\n marks.style.cssText = 'position:fixed;inset:0;z-index:1;pointer-events:none';\n marks.innerHTML = overlay;\n document.body.append(marks);\n return box;\n }, shot);\n // Without the scrollbars: a shot is what the page is drawn in, which is what an element's box is from.\n // A shot of the element alone is cut where the element is here.\n const clip = clamp(shot.clip === undefined ? { x: 0, y: 0, ...shot.viewport } : (found ?? shot.clip), shot.viewport);\n const png = new Uint8Array(await page.screenshot({ type: 'png', ...(clip === undefined ? {} : { clip }) }));\n return { png, ...(found === undefined || shot.clip !== undefined ? {} : { box: found }) };\n } finally {\n await context.close();\n }\n}\n\n/** A box kept within the viewport: an element partly scrolled out of it shows only the part that's in. */\nfunction clamp(box: Box, viewport: { width: number; height: number }): Box | undefined {\n const x = Math.max(0, box.x);\n const y = Math.max(0, box.y);\n const width = Math.min(viewport.width, box.x + box.width) - x;\n const height = Math.min(viewport.height, box.y + box.height) - y;\n return width > 0 && height > 0 ? { x, y, width, height } : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAA8B;;AAGnD,SAAgB,UAAU,SAA2C;CACnE,MAAM,MAAM,KAAK,UAAU,OAAO;CAClC,MAAM,QAAQ,SAAS,IAAI,GAAG;CAC9B,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,MAAM,WAAW,OAAO,OAAO;CAC/B,SAAS,IAAI,KAAK,QAAQ;CAE1B,SAAS,YAAY,SAAS,OAAO,GAAG,CAAC;CACzC,OAAO;AACT;;AAGA,MAAM,aAAa,EAAE,mBAAmB,CAAC,mBAAmB,EAAE;AAE9D,eAAe,OAAO,EAAE,gBAAgB,WAA6C;CACnF,MAAM,EAAE,aAAa,MAAM,OAAO,kBAAkB,CAAC,OAAO,MAAe;EACzE,MAAM,IAA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