deictic 0.8.1 → 0.10.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 (128) hide show
  1. package/API.md +81 -17
  2. package/README.md +1 -1
  3. package/dist/annotations/client.js +1 -1
  4. package/dist/bun.d.ts.map +1 -1
  5. package/dist/bun.js +26 -8
  6. package/dist/bun.js.map +1 -1
  7. package/dist/cli.js +1 -1
  8. package/dist/cli.js.map +1 -1
  9. package/dist/client/index.d.ts +13 -13
  10. package/dist/client/index.d.ts.map +1 -1
  11. package/dist/client/index.js +19 -7
  12. package/dist/client/index.js.map +1 -1
  13. package/dist/next.d.ts.map +1 -1
  14. package/dist/next.js +45 -25
  15. package/dist/next.js.map +1 -1
  16. package/dist/react/client.d.ts +19 -0
  17. package/dist/react/client.d.ts.map +1 -0
  18. package/dist/react/client.js +504 -0
  19. package/dist/react/client.js.map +1 -0
  20. package/dist/react/index.d.ts +2 -0
  21. package/dist/react/index.js +1 -0
  22. package/dist/recommended/index.d.ts +15 -7
  23. package/dist/recommended/index.d.ts.map +1 -1
  24. package/dist/recommended/index.js +1 -1
  25. package/dist/recordings/client.d.ts.map +1 -1
  26. package/dist/recordings/client.js +48 -5
  27. package/dist/recordings/client.js.map +1 -1
  28. package/dist/screenshots/client.d.ts +9 -1
  29. package/dist/screenshots/client.d.ts.map +1 -1
  30. package/dist/screenshots/rrweb.d.ts +0 -6
  31. package/dist/screenshots/rrweb.d.ts.map +1 -1
  32. package/dist/screenshots/rrweb.js +46 -12
  33. package/dist/screenshots/rrweb.js.map +1 -1
  34. package/dist/shared/board.js +1 -1
  35. package/dist/shared/client.js +44 -2
  36. package/dist/shared/client.js.map +1 -1
  37. package/dist/shared/dom.js +7 -1
  38. package/dist/shared/dom.js.map +1 -1
  39. package/dist/shared/drawer.js +1 -1
  40. package/dist/shared/endpoints.js +15 -4
  41. package/dist/shared/endpoints.js.map +1 -1
  42. package/dist/shared/index.d.ts +11 -0
  43. package/dist/shared/index.d.ts.map +1 -1
  44. package/dist/shared/index10.d.ts +70 -0
  45. package/dist/shared/index10.d.ts.map +1 -0
  46. package/dist/shared/index3.d.ts +11 -0
  47. package/dist/shared/index3.d.ts.map +1 -1
  48. package/dist/shared/index7.d.ts +92 -312
  49. package/dist/shared/index7.d.ts.map +1 -1
  50. package/dist/shared/index8.d.ts +324 -47
  51. package/dist/shared/index8.d.ts.map +1 -1
  52. package/dist/shared/index9.d.ts +45 -63
  53. package/dist/shared/index9.d.ts.map +1 -1
  54. package/dist/shared/init.js +15 -11
  55. package/dist/shared/init.js.map +1 -1
  56. package/dist/shared/integration.d.ts +6 -0
  57. package/dist/shared/integration.d.ts.map +1 -1
  58. package/dist/shared/integration.js +28 -1
  59. package/dist/shared/integration.js.map +1 -1
  60. package/dist/shared/marks.js +7 -1
  61. package/dist/shared/marks.js.map +1 -1
  62. package/dist/shared/package.js +3 -1
  63. package/dist/shared/packages.js +1 -1
  64. package/dist/shared/playwright.js +39 -1
  65. package/dist/shared/playwright.js.map +1 -1
  66. package/dist/shared/react.js +25 -0
  67. package/dist/shared/react.js.map +1 -0
  68. package/dist/shared/recommended.js +6 -3
  69. package/dist/shared/recommended.js.map +1 -1
  70. package/dist/shared/recording.js +80 -3
  71. package/dist/shared/recording.js.map +1 -1
  72. package/dist/shared/recordings.js +30 -2
  73. package/dist/shared/recordings.js.map +1 -1
  74. package/dist/shared/screenshots.js.map +1 -1
  75. package/dist/shared/src.js.map +1 -1
  76. package/dist/shared/task.js +1 -0
  77. package/dist/shared/task.js.map +1 -1
  78. package/dist/shared/tasks.js +11 -0
  79. package/dist/shared/tasks.js.map +1 -1
  80. package/dist/shared/vite.d.ts +1 -1
  81. package/dist/shared/vite.d.ts.map +1 -1
  82. package/dist/shared/vite.js +28 -10
  83. package/dist/shared/vite.js.map +1 -1
  84. package/dist/tailwind/client.d.ts +1 -1
  85. package/dist/tailwind/index.d.ts +1 -1
  86. package/dist/tasks/client.d.ts +1 -1
  87. package/dist/tasks/client.js +45 -19
  88. package/dist/tasks/client.js.map +1 -1
  89. package/dist/tasks/index.d.ts +1 -1
  90. package/dist/voice/client.d.ts +1 -1
  91. package/dist/voice/client.js +1 -1
  92. package/dist/voice/index.d.ts +1 -1
  93. package/dist/webpack.d.ts +4 -0
  94. package/dist/webpack.d.ts.map +1 -1
  95. package/dist/webpack.js +37 -15
  96. package/dist/webpack.js.map +1 -1
  97. package/package.json +25 -1
  98. package/src/bun.ts +32 -8
  99. package/src/cli/bun.ts +2 -2
  100. package/src/cli/init.ts +14 -9
  101. package/src/cli/recording.ts +90 -4
  102. package/src/cli/task.ts +4 -0
  103. package/src/cli.ts +13 -6
  104. package/src/client/dom.ts +14 -0
  105. package/src/client/index.ts +25 -14
  106. package/src/index.ts +11 -0
  107. package/src/next.ts +34 -15
  108. package/src/plugins/react/client.ts +162 -0
  109. package/src/plugins/react/index.ts +130 -0
  110. package/src/plugins/react/renders.ts +219 -0
  111. package/src/plugins/react/serialize.ts +139 -0
  112. package/src/plugins/react/timeline.ts +143 -0
  113. package/src/plugins/recommended/index.ts +17 -5
  114. package/src/plugins/recordings/client.ts +64 -4
  115. package/src/plugins/recordings/marks.ts +7 -0
  116. package/src/plugins/recordings/replay.ts +30 -2
  117. package/src/plugins/screenshots/client.ts +42 -2
  118. package/src/plugins/screenshots/index.ts +11 -0
  119. package/src/plugins/screenshots/playwright.ts +65 -1
  120. package/src/plugins/screenshots/rrweb.ts +55 -28
  121. package/src/plugins/screenshots/states.ts +26 -0
  122. package/src/plugins/tasks/client.ts +41 -6
  123. package/src/plugins/tasks/composer.ts +24 -7
  124. package/src/plugins/tasks/index.ts +16 -2
  125. package/src/tools/integration.ts +33 -0
  126. package/src/tools/source.ts +14 -2
  127. package/src/vite.ts +31 -10
  128. package/src/webpack.ts +48 -16
@@ -26,7 +26,7 @@ import type { ClientContext, LightboxItem, Point, Target } from '#src/index.ts';
26
26
  // For `use()`'s types: the plugins may not be loaded, and nothing of them runs here.
27
27
  import type { Annotation, Annotations, Picture } from '#src/plugins/annotations/index.ts';
28
28
  import type { Recording } from '#src/plugins/recordings/index.ts';
29
- import type { Shot } from '#src/plugins/screenshots/index.ts';
29
+ import type { Capture, Shot } from '#src/plugins/screenshots/index.ts';
30
30
  import type { Clip, Take } from '#src/plugins/voice/index.ts';
31
31
 
32
32
  import type { Marks, Op } from './index.ts';
@@ -134,6 +134,8 @@ export type Sent = NonNullable<Op['screenshots']>[number] & { url: string };
134
134
  export interface Seen extends Pick<Op, 'point' | 'pointed' | 'count' | 'which' | 'chain'> {
135
135
  /** The element's HTML, as it would be attached. */
136
136
  html: string;
137
+ /** What React's DevTools would show of it, `react.json`, where the react plugin is loaded and React wrote it. */
138
+ react?: string;
137
139
  }
138
140
 
139
141
  /**
@@ -211,6 +213,11 @@ export interface ComposerOptions {
211
213
  at?: Point;
212
214
  /** Whether a shot is taken as it's sent, while nothing else is attached and none was asked for or not: a task's. */
213
215
  shoot?: boolean;
216
+ /**
217
+ * The popup's own element as the press that opened it froze the page (`screenshots.frozen`): what a shot of it is,
218
+ * rather than the page as it is when it's sent, by which time a tooltip or a menu may have closed.
219
+ */
220
+ frozen?: Promise<Shot>;
214
221
  /** Whether this page has what's shot and drawn on: not for a task back from a recording on a page without it. */
215
222
  here?: boolean;
216
223
  /** Whether it's over the page, in the overlay's root: a press on the page picks an element, and attached ones are outlined. */
@@ -309,10 +316,20 @@ export function composerIn(context: ClientContext, options: ComposerOptions): Co
309
316
 
310
317
  const text = element('textarea', { placeholder: options.placeholder, rows: 1 });
311
318
  const chipsEl = element('div', { className: 'chips' });
312
- const camera = toolButton(CAMERA, `Attach a screenshot, taken as it's sent`, undefined, () => {
313
- wanted = !shooting();
314
- showChips();
315
- });
319
+ /** A shot of `of`: as the press froze it, where it's the popup's own element still first, else as the page is now. */
320
+ const shotOf = (s: Capture, of: Element) => {
321
+ const frozen = about[0]?.own === true && onPage(about[0]) === of ? options.frozen : undefined;
322
+ return frozen === undefined ? s.capture(of) : frozen.catch(() => s.capture(of));
323
+ };
324
+ const camera = toolButton(
325
+ CAMERA,
326
+ options.frozen === undefined ? `Attach a screenshot, taken as it's sent` : 'Attach a screenshot of the page as it was when you pressed',
327
+ undefined,
328
+ () => {
329
+ wanted = !shooting();
330
+ showChips();
331
+ },
332
+ );
316
333
  camera.hidden = shots === undefined || !here;
317
334
  const code = toolButton(CODE, 'Attach an HTML snapshot: the element as the page has it now, as a file', undefined, () => {
318
335
  withHtml = !withHtml;
@@ -541,7 +558,7 @@ export function composerIn(context: ClientContext, options: ComposerOptions): Co
541
558
  problem.textContent = '';
542
559
  try {
543
560
  if (old === undefined) doing.textContent = 'Capturing…';
544
- const shot = old?.drawn?.shot ?? (await shots.capture(onPage(about[0]) ?? document.documentElement));
561
+ const shot = old?.drawn?.shot ?? (await shotOf(shots, onPage(about[0]) ?? document.documentElement));
545
562
  doing.textContent = '';
546
563
  const picture: Picture = { url: shot.url, ...shot.size };
547
564
  const marks = await notes.edit(picture, old?.drawn?.marks ?? [], { signal: aborts.signal });
@@ -676,7 +693,7 @@ export function composerIn(context: ClientContext, options: ComposerOptions): Co
676
693
  // Of the first element, which the shot then says the place of; of the page, with none on it.
677
694
  const first = onPage(about[0]);
678
695
  const of = first ?? document.documentElement;
679
- const now = await shots.capture(of);
696
+ const now = await shotOf(shots, of);
680
697
  const where = first === undefined ? {} : { box: now.box };
681
698
  // The others as the page has them, moved by as much as the shot has the first off where the page has it.
682
699
  const live = of.getBoundingClientRect();
@@ -229,7 +229,7 @@ export interface Op {
229
229
  * The other elements it's about, after the one it's sent on, in the order they were attached: each one's place,
230
230
  * its tag, and its HTML as it rendered, where that's attached.
231
231
  */
232
- also?: { at: string; tag: string; html?: string }[];
232
+ also?: { at: string; tag: string; html?: string; react?: string }[];
233
233
  /**
234
234
  * No element is attached: it's about the page, and the element it's sent on is only where the popup was. It has
235
235
  * no place then, so no element's tab lists it and nothing pins it.
@@ -244,6 +244,11 @@ export interface Op {
244
244
  chain?: string[];
245
245
  /** The element's HTML as it rendered, to attach: cut short, and masked where the screenshots plugin is loaded. */
246
246
  html?: string;
247
+ /**
248
+ * What React's DevTools would show of the components that wrote it, as JSON, to attach as `react.json`: where the
249
+ * react plugin is loaded, and sent with the HTML.
250
+ */
251
+ react?: string;
247
252
  /**
248
253
  * Shots the screenshots plugin took, to attach, where that plugin is loaded: each with where the element is in
249
254
  * it (`box`, for one taken of the element; one taken of the window from the tool panel has none), whether
@@ -607,8 +612,14 @@ export function tasks(options: TasksOptions = {}) {
607
612
  if (html !== undefined) files.push({ data: new TextEncoder().encode(html.slice(0, HTML)), name: 'element.html', type: 'text/html' });
608
613
  else if (op.pointed !== undefined)
609
614
  files.push({ data: new TextEncoder().encode(op.pointed.html.slice(0, HTML)), name: 'pointed.html', type: 'text/html' });
615
+ const json = (of: unknown, name: string) => {
616
+ if (typeof of === 'string' && of !== '')
617
+ files.push({ data: new TextEncoder().encode(of.slice(0, REACT)), name, type: 'application/json' });
618
+ };
619
+ json(op.react, 'react.json');
610
620
  // The others': the Nth element's is `element.N.html`, the first being the one it's sent on.
611
621
  for (const [i, other] of (op.also ?? []).entries()) {
622
+ json(other.react, `react.${i + 2}.json`);
612
623
  if (typeof other.html !== 'string' || other.html === '') continue;
613
624
  files.push({ data: new TextEncoder().encode(other.html.slice(0, HTML)), name: `element.${i + 2}.html`, type: 'text/html' });
614
625
  }
@@ -845,7 +856,7 @@ function textPage(name: string, text: string): string {
845
856
  type Kind = 'screenshot' | 'recording' | 'voice clip' | 'voice note';
846
857
 
847
858
  /** What a task or a reply attaches: files, and what the labels say of them. */
848
- type Attaching = Partial<Pick<Op, 'screenshots' | 'recordings' | 'voice' | 'annotations' | 'html' | 'pointed' | 'also'>>;
859
+ type Attaching = Partial<Pick<Op, 'screenshots' | 'recordings' | 'voice' | 'annotations' | 'html' | 'react' | 'pointed' | 'also'>>;
849
860
 
850
861
  /**
851
862
  * A message's files, as the drawer shows them: each recording with where it replays, which its
@@ -913,6 +924,9 @@ const boxOf = ({ x, y, width, height }: Box) => [x, y, width, height].map(Math.r
913
924
  /** What `element.html` holds of an element at most, in characters: a table's rows, not a whole page. */
914
925
  const HTML = 100_000;
915
926
 
927
+ /** What `react.json` holds at most, in characters: the page half cuts it to less. */
928
+ const REACT = 250_000;
929
+
916
930
  /** A label's value: a board holds 256 characters. */
917
931
  const LABEL = 256;
918
932
 
@@ -25,6 +25,39 @@ export interface DeicticOptions {
25
25
  * `false` for none, leaving only plugins' own shortcuts.
26
26
  */
27
27
  shortcut?: Shortcut | false;
28
+ /**
29
+ * For a package that adds its own plugin to the bundler with deictic (prosebook does): these options give way to
30
+ * those of any other deictic in the same build, which merges them in, so the app's own `deictic()` decides the
31
+ * shortcut and its plugin of the same name is the one loaded.
32
+ */
33
+ defaults?: boolean;
34
+ }
35
+
36
+ /**
37
+ * Every deictic one build was given, as one: the app's and those packages added (`defaults`). The plugins of all of
38
+ * them, each name once, the first given winning, those of an instance with `defaults` after the rest's; any other
39
+ * option from the first that sets it, the same way. Two that aren't `defaults` setting one differently is an error,
40
+ * as neither can be the one meant.
41
+ */
42
+ export function merge<O extends DeicticOptions>(instances: readonly O[]): O {
43
+ const ordered = [...instances.filter((o) => o.defaults !== true), ...instances.filter((o) => o.defaults === true)];
44
+ const plugins = new Map<string, ServerPlugin>();
45
+ const merged: Record<string, unknown> = {};
46
+ const setBy: Record<string, O> = {};
47
+ for (const options of ordered) {
48
+ for (const plugin of options.plugins ?? []) if (!plugins.has(plugin.name)) plugins.set(plugin.name, plugin);
49
+ for (const [key, value] of Object.entries(options)) {
50
+ if (key === 'plugins' || key === 'defaults' || value === undefined) continue;
51
+ const first = setBy[key];
52
+ if (first === undefined) {
53
+ merged[key] = value;
54
+ setBy[key] = options;
55
+ } else if (first.defaults !== true && options.defaults !== true && JSON.stringify(merged[key]) !== JSON.stringify(value)) {
56
+ throw new Error(`deictic: the build has deictic twice, with ${key} set two ways: set it in one of them only`);
57
+ }
58
+ }
59
+ }
60
+ return { ...merged, plugins: [...plugins.values()] } as O;
28
61
  }
29
62
 
30
63
  /** The options with their defaults, checked now, so a wrong set stops the dev server as it starts, not the page. */
@@ -73,13 +73,16 @@ function astro(root: string, file: string, code: string): Parsed {
73
73
  return parsed;
74
74
  }
75
75
 
76
- /** Each file's text after its edits, which must not overlap. */
76
+ /**
77
+ * Each file's text after its edits, which must not overlap. A file that isn't there is made where every edit to it is
78
+ * at its start (a locale's first translation, say); any other edit to one is refused.
79
+ */
77
80
  export function applyEdits(source: Source, edits: TextEdit[]): Map<string, string> {
78
81
  const byFile = Map.groupBy(edits, (e) => e.file ?? source.file);
79
82
  const out = new Map<string, string>();
80
83
  for (const [file, list] of byFile) {
81
84
  const sorted = list.toSorted((a, b) => b.start - a.start);
82
- let code = file === source.file ? source.code : source.read(file);
85
+ let code = file === source.file ? source.code : textOf(source, file, list);
83
86
  let floor = Infinity;
84
87
  for (const edit of sorted) {
85
88
  if (edit.end > floor) throw new Error(`deictic: edits to ${file} overlap at ${edit.end}`);
@@ -90,3 +93,12 @@ export function applyEdits(source: Source, edits: TextEdit[]): Map<string, strin
90
93
  }
91
94
  return out;
92
95
  }
96
+
97
+ function textOf(source: Source, file: string, edits: TextEdit[]): string {
98
+ try {
99
+ return source.read(file);
100
+ } catch (e) {
101
+ if (e instanceof Refusal && e.cause !== undefined && edits.every((edit) => edit.start === 0 && edit.end === 0)) return '';
102
+ throw e;
103
+ }
104
+ }
package/src/vite.ts CHANGED
@@ -7,13 +7,16 @@
7
7
  * line moves and frameworks that render their own HTML get it too. The endpoints are middleware on
8
8
  * Vite's server, and a place opens through Vite's own `/__open-in-editor`, so the editor is whichever
9
9
  * Vite already launches. A write reaches the page through Vite's usual update for the file.
10
+ *
11
+ * A build may have deictic more than once: the app's, and one a package added with its own plugin (`defaults`).
12
+ * The first in Vite's list does the work with all of their options merged (`merge`); the others do nothing.
10
13
  */
11
14
  import { resolve } from 'node:path';
12
15
 
13
16
  import type { Plugin } from 'vite';
14
17
 
15
18
  import { endpoints, nodeMiddleware, redirect } from './tools/endpoints.ts';
16
- import { clientModule, type DeicticOptions, mark, markAstro, prepare } from './tools/integration.ts';
19
+ import { clientModule, type DeicticOptions, mark, markAstro, merge, prepare } from './tools/integration.ts';
17
20
 
18
21
  export { clientModule, type DeicticOptions };
19
22
 
@@ -31,23 +34,40 @@ export interface ViteOptions extends DeicticOptions {
31
34
  export const CLIENT = 'virtual:deictic/client';
32
35
  const CLIENT_ID = '\0deictic/client';
33
36
 
34
- export function deictic(options: ViteOptions = {}): Plugin {
35
- const { plugins, shortcut } = prepare(options);
37
+ /** What each deictic in Vite's list carries, for the first of them to find the others by. */
38
+ interface Carried {
39
+ deictic: { options: ViteOptions; id: symbol };
40
+ }
41
+
42
+ const carriedBy = (plugin: { api?: unknown }) => (plugin.api as Partial<Carried> | undefined)?.deictic;
43
+
44
+ export function deictic(given: ViteOptions = {}): Plugin {
45
+ const id = Symbol('deictic');
46
+ let options = given;
47
+ let { plugins, shortcut } = prepare(given);
48
+ let leading = true;
36
49
  let root = '';
37
50
  let base = '/';
38
51
  let building = false;
39
52
  return {
40
53
  name: 'deictic',
41
54
  enforce: 'pre',
42
- apply: (_, { command }) => command === 'serve' || options.standalone !== undefined,
55
+ apply: (_, { command }) => command === 'serve' || given.standalone !== undefined,
56
+ api: { deictic: { options: given, id } } satisfies Carried,
43
57
  // The client is the app's to bundle as it changes, not a dependency to prebundle once.
44
58
  config: () => ({ optimizeDeps: { exclude: ['deictic'] } }),
45
59
  configResolved(config) {
46
60
  root = config.root;
47
61
  base = config.base;
48
62
  building = config.command === 'build';
63
+ const all = config.plugins.flatMap((p) => carriedBy(p) ?? []);
64
+ leading = all[0]?.id === id;
65
+ if (!leading || all.length === 1) return;
66
+ options = merge(all.map((c) => c.options));
67
+ ({ plugins, shortcut } = prepare(options));
49
68
  },
50
69
  configureServer(server) {
70
+ if (!leading) return;
51
71
  const handle = endpoints({
52
72
  root,
53
73
  plugins,
@@ -56,9 +76,9 @@ export function deictic(options: ViteOptions = {}): Plugin {
56
76
  });
57
77
  server.middlewares.use(nodeMiddleware(handle));
58
78
  },
59
- resolveId: (id) => (id === CLIENT ? CLIENT_ID : undefined),
60
- load(id) {
61
- if (id !== CLIENT_ID) return undefined;
79
+ resolveId: (source) => (leading && source === CLIENT ? CLIENT_ID : undefined),
80
+ load(module) {
81
+ if (!leading || module !== CLIENT_ID) return undefined;
62
82
  // Only a build's page asks the module: the dev server is there to answer.
63
83
  const server = building && options.standalone !== undefined ? resolve(root, options.standalone).replaceAll('\\', '/') : undefined;
64
84
  return clientModule(plugins, base, shortcut, server);
@@ -67,10 +87,11 @@ export function deictic(options: ViteOptions = {}): Plugin {
67
87
  // First of all, not only first of the `pre` plugins: the React Compiler (`react({ compiler: true })`) is
68
88
  // `pre` too and compiles the JSX away, so after it there'd be no element to mark, wherever deictic is listed.
69
89
  order: 'pre',
70
- handler(code, id) {
71
- const [path = ''] = id.split('?');
90
+ handler(code, module) {
91
+ if (!leading) return undefined;
92
+ const [path = ''] = module.split('?');
72
93
  // An `.astro` component itself, not the styles and scripts Astro loads from it by a query.
73
- if (path.endsWith('.astro')) return id === path ? markAstro(code, path, root) : undefined;
94
+ if (path.endsWith('.astro')) return module === path ? markAstro(code, path, root) : undefined;
74
95
  const browser = this.environment.config.consumer === 'client';
75
96
  return mark(code, path, root, browser ? `\nimport ${JSON.stringify(CLIENT)};\n` : '');
76
97
  },
package/src/webpack.ts CHANGED
@@ -9,15 +9,17 @@
9
9
  * webpack-dev-server and Rspack's both read), and a place opens with `launch-editor`, as webpack has no
10
10
  * launcher of its own. Where the dev server is started by hand, or by Rsbuild, `middleware` is the
11
11
  * endpoints to mount there.
12
+ *
13
+ * A compiler may be given deictic more than once: the app's, and one a package applied with its own plugin
14
+ * (`defaults`). The first applied adds the rule and the middleware, and every one writes the client again with all
15
+ * of their options merged (`merge`), so the last applied writes it whole before the compiler runs.
12
16
  */
13
17
  import type { IncomingMessage, ServerResponse } from 'node:http';
14
18
 
15
- import type { ServerPlugin } from './index.ts';
16
19
  import type { LoaderOptions } from './loader.ts';
17
- import type { Shortcut } from './shortcut.ts';
18
20
  import { openInEditor } from './tools/editor.ts';
19
21
  import { endpoints, nodeMiddleware } from './tools/endpoints.ts';
20
- import { beside, type DeicticOptions, prepare, writeClient } from './tools/integration.ts';
22
+ import { beside, type DeicticOptions, merge, prepare, writeClient } from './tools/integration.ts';
21
23
  import { JSX } from './tools/locate.ts';
22
24
 
23
25
  export interface DeicticWebpackOptions extends DeicticOptions {
@@ -47,39 +49,69 @@ const loaderPath = beside(import.meta.url, 'loader');
47
49
  const forBrowser = (target: Compiler['options']['target']) =>
48
50
  target === undefined || [target].flat().some((t) => t !== false && !/^(async-)?node|^electron-main|^electron-preload/.test(t));
49
51
 
52
+ /** Every deictic one compiler was given, and the first of them, which serves the endpoints. */
53
+ interface Applied {
54
+ given: DeicticWebpackOptions[];
55
+ first: DeicticPlugin;
56
+ }
57
+
58
+ const appliedTo = new WeakMap<Compiler, Applied>();
59
+
50
60
  export class DeicticPlugin {
51
61
  readonly #options: DeicticWebpackOptions;
52
- readonly #plugins: ServerPlugin[];
53
- readonly #shortcut: Shortcut | false | undefined;
62
+ #applied: Applied | undefined;
54
63
  #middleware: Middleware | undefined;
55
64
  #root = '';
56
65
 
57
66
  constructor(options: DeicticWebpackOptions = {}) {
58
67
  this.#options = options;
59
68
  // Now, so a wrong set of plugins stops the dev server as it starts, rather than the page.
60
- ({ plugins: this.#plugins, shortcut: this.#shortcut } = prepare(options));
69
+ prepare(options);
70
+ }
71
+
72
+ /** The options of every deictic the compiler was given, merged. */
73
+ #merged(): DeicticWebpackOptions {
74
+ const given = this.#applied?.given ?? [this.#options];
75
+ return given.length === 1 ? given[0]! : merge(given);
61
76
  }
62
77
 
63
78
  /** The endpoints as Node middleware, once the plugin is applied: for a dev server started by hand. */
64
79
  get middleware(): Middleware {
80
+ const applied = this.#applied;
81
+ if (applied === undefined) throw new Error('deictic: give the plugin to the compiler before mounting its middleware');
82
+ if (applied.first !== this) return applied.first.middleware;
65
83
  if (this.#middleware !== undefined) return this.#middleware;
66
- if (this.#root === '') throw new Error('deictic: give the plugin to the compiler before mounting its middleware');
67
- const root = this.#root;
68
- const handle = endpoints({
69
- root,
70
- plugins: this.#plugins,
71
- base: this.#options.base ?? '/',
72
- open: (path, loc) => openInEditor(path, loc),
84
+ let handle: Middleware | undefined;
85
+ // Made at the first request, once every deictic of the compiler has been applied.
86
+ return (this.#middleware = (req, res, next) => {
87
+ if (handle === undefined) {
88
+ const merged = this.#merged();
89
+ handle = nodeMiddleware(
90
+ endpoints({
91
+ root: this.#root,
92
+ plugins: prepare(merged).plugins,
93
+ base: merged.base ?? '/',
94
+ open: (path, loc) => openInEditor(path, loc),
95
+ }),
96
+ );
97
+ }
98
+ handle(req, res, next);
73
99
  });
74
- return (this.#middleware = nodeMiddleware(handle));
75
100
  }
76
101
 
77
102
  apply(compiler: Compiler): void {
78
103
  // Development only: a build without a mode is webpack's production one.
79
104
  if (compiler.options.mode !== 'development') return;
80
- this.#root = this.#options.root ?? compiler.context;
105
+ let applied = appliedTo.get(compiler);
106
+ if (applied === undefined) appliedTo.set(compiler, (applied = { given: [], first: this }));
107
+ applied.given.push(this.#options);
108
+ this.#applied = applied;
109
+ const merged = this.#merged();
110
+ const { plugins, shortcut } = prepare(merged);
111
+ this.#root = merged.root ?? compiler.context;
81
112
  const browser = forBrowser(compiler.options.target);
82
- const client = browser ? writeClient(this.#root, this.#plugins, this.#options.base ?? '/', this.#shortcut) : undefined;
113
+ const client = browser ? writeClient(this.#root, plugins, merged.base ?? '/', shortcut) : undefined;
114
+ if (applied.first !== this) return;
83
115
  const options: LoaderOptions = { root: this.#root, ...(client === undefined ? {} : { client }) };
84
116
  // First, and `pre`, so it sees the source as written whatever the app's own rules do.
85
117
  compiler.options.module.rules.unshift({