@stefan.inc/feedback-engine 0.0.0-stage → 0.0.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/package.json +57 -5
  4. package/src/core/annotations.ts +104 -0
  5. package/src/core/cardLayout.ts +82 -0
  6. package/src/core/describe.ts +143 -0
  7. package/src/core/index.ts +9 -0
  8. package/src/core/model.ts +133 -0
  9. package/src/core/problem.ts +51 -0
  10. package/src/core/report.ts +74 -0
  11. package/src/core/session.ts +184 -0
  12. package/src/core/taskTitle.ts +35 -0
  13. package/src/core/tree.ts +117 -0
  14. package/src/dom/capture.ts +78 -0
  15. package/src/dom/image.ts +316 -0
  16. package/src/dom/procrastimate.ts +205 -0
  17. package/src/dom/scene.ts +286 -0
  18. package/src/dom/screenshot.ts +118 -0
  19. package/src/dom/share.ts +71 -0
  20. package/src/dom/tags.ts +21 -0
  21. package/src/dom/webhook.ts +80 -0
  22. package/src/dom/zip.ts +52 -0
  23. package/src/editor/Button.svelte +125 -0
  24. package/src/editor/Editor.svelte +1078 -0
  25. package/src/editor/Host.svelte +31 -0
  26. package/src/editor/ItemsSheet.svelte +233 -0
  27. package/src/editor/Pill.svelte +65 -0
  28. package/src/editor/ProblemCard.svelte +67 -0
  29. package/src/editor/ProcrastimateSheet.svelte +304 -0
  30. package/src/editor/WebhookSheet.svelte +132 -0
  31. package/src/editor/engine.ts +154 -0
  32. package/src/editor/setup.ts +106 -0
  33. package/src/next/index.d.ts +13 -0
  34. package/src/next/index.js +69 -0
  35. package/src/next/loader.js +23 -0
  36. package/src/react/components.ts +101 -0
  37. package/src/react/index.ts +44 -0
  38. package/src/react/public.d.ts +101 -0
  39. package/src/svelte/index.ts +32 -0
  40. package/src/vite/index.d.ts +44 -0
  41. package/src/vite/index.js +207 -0
  42. package/src/vite/react.js +172 -0
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The types of `@stefan.inc/feedback-engine/react`, written out so an app's compiler never reads the package's source
3
+ * under the app's own options. `public.test.ts` fails the type check when they drift from `index.ts`.
4
+ */
5
+
6
+ export type FeedbackOptions = {
7
+ /** The app's name in exports. Defaults to the document's title. */
8
+ app?: string;
9
+ version?: string;
10
+ /**
11
+ * What opens Feedback. A chord that ends in `Click`, such as the default `Alt+Meta+Click`, opens the editor with the
12
+ * element under the pointer selected. A chord that ends in a key, such as `Alt+Shift+F`, shows the Add Feedback
13
+ * pill. `false` turns it off.
14
+ */
15
+ shortcut?: string | false;
16
+ /**
17
+ * Shows a round Feedback button on every screen, for a phone or an app opened from the home screen, which have no
18
+ * keyboard. Pressing it captures the page. Drag it to move it to another height or the other side.
19
+ */
20
+ button?: boolean;
21
+ /**
22
+ * Adds ProcrastiMate to the Share menu. Leave it out behind `feedbackProcrastimate()` from the Vite entry point,
23
+ * which adds the entry by itself when it has a token. Set it for a proxy of your own.
24
+ */
25
+ procrastimate?: {
26
+ /** Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. */
27
+ url: string;
28
+ /** Sent as a bearer token. Leave it out behind the proxy, which adds its own. */
29
+ token?: string;
30
+ /** The ProcrastiMate web app, for the link to a posted task. */
31
+ app?: string;
32
+ };
33
+ /**
34
+ * Adds one entry to the Share menu per webhook. Choosing it posts the image export and the JSON export to the
35
+ * webhook's `url`, with nothing more to fill in.
36
+ */
37
+ webhooks?: Webhook[];
38
+ };
39
+
40
+ /** One entry of the Share menu that posts the feedback to a server of the app's own. `docs/webhooks.md` has the request. */
41
+ export type Webhook = {
42
+ /** The entry's name in the Share menu, such as `GitHub Issue`. */
43
+ name: string;
44
+ /** Where the post goes. A path, such as `/api/feedback`, is on the page's own origin. */
45
+ url: string;
46
+ /** An icon beside the name: anything an `<img>` loads, such as `githubIcon` or a data URL. */
47
+ image?: string;
48
+ /** Sent with the post, such as `Authorization`. Whatever a page sends is public. */
49
+ headers?: Record<string, string>;
50
+ /** Added to the URL's query. */
51
+ query?: Record<string, string>;
52
+ };
53
+
54
+ /** GitHub's mark in white, for a webhook that files issues. */
55
+ export const githubIcon: string;
56
+
57
+ export type FeedbackEngine = {
58
+ /** Registers app state to attach to every capture. `value` runs when a capture is taken. Registering a name again replaces the earlier one. */
59
+ context(name: string, value: () => unknown): void;
60
+ /** Captures the page and opens the editor. Does nothing while the editor is open. */
61
+ present(): Promise<void>;
62
+ /** Shows the Add Feedback pill, as a keyboard shortcut does. Pressing it captures the page. Left alone, it leaves after 5 seconds. */
63
+ showPill(): void;
64
+ /**
65
+ * Shows the pill counting down from `seconds`, 5 unless given, then captures the page and opens the editor. For a
66
+ * trigger inside one of the app's menus, such as on a phone: the user has the countdown to leave the menu and reach
67
+ * the screen they mean. Pressing the pill captures at once.
68
+ */
69
+ countdown(seconds?: number): void;
70
+ /** The files of the last export, for automation that cannot use the clipboard or a download. */
71
+ readonly lastExport: { name: string; blob: Blob }[];
72
+ /** Removes the shortcut and Feedback's UI from the page. */
73
+ destroy(): void;
74
+ };
75
+
76
+ /** A value that Feedback describes as `toFeedback()` in its place, at any depth. */
77
+ export type FeedbackRepresentable = { toFeedback(): unknown };
78
+
79
+ /**
80
+ * Turns Feedback on: Alt+Meta+click on anything captures the page and opens the editor on what was clicked. Call it
81
+ * once, in the browser, before or after React renders. On a server it returns an engine that does nothing.
82
+ */
83
+ export function setupFeedbackEngine(options?: FeedbackOptions): FeedbackEngine;
84
+
85
+ type Named = (name: string, data?: () => unknown) => (element: Element | null) => void;
86
+
87
+ /**
88
+ * Names an element in feedback captures: `<section ref={feedback('Chart', () => plot)}>`. The Vite plugin already
89
+ * finds every component of the app, so this is for a region drawn inline, and for a component's root element, under
90
+ * the component's own name, to report data that React keeps out of its props, such as state. `data` runs when a
91
+ * capture is taken.
92
+ */
93
+ export const feedback: Named & {
94
+ /** What the Vite plugin rewrites `feedback(` into. Not for app code. */
95
+ at(source: string): Named;
96
+ };
97
+
98
+ declare global {
99
+ /** The engine of this page, for automation: `__feedbackEngine.present()` and `__feedbackEngine.lastExport`. */
100
+ var __feedbackEngine: FeedbackEngine | undefined;
101
+ }
@@ -0,0 +1,32 @@
1
+ import type { Attachment } from 'svelte/attachments';
2
+ import { tags } from '../dom/tags.ts';
3
+
4
+ export type { FeedbackRepresentable } from '../core/index.ts';
5
+ export { githubIcon, type Webhook } from '../dom/webhook.ts';
6
+ export type { FeedbackOptions } from '../editor/engine.ts';
7
+ export { setupFeedbackEngine, type FeedbackEngine } from '../editor/setup.ts';
8
+
9
+ type Named = (name?: string, data?: () => unknown) => Attachment<Element>;
10
+
11
+ function tagged(defaults: { name?: string; source?: string; data?: () => unknown }): Named {
12
+ return (name, data) => element => {
13
+ tags.set(element, {
14
+ name: name ?? defaults.name ?? 'Component',
15
+ data: data ?? defaults.data,
16
+ source: defaults.source,
17
+ });
18
+ return () => tags.delete(element);
19
+ };
20
+ }
21
+
22
+ /**
23
+ * Names an element in feedback captures: `{@attach feedback()}` on a component's root element. `data` runs when a
24
+ * capture is taken. The Vite plugin fills in the name, from the file, and the `file:line` of the call. A call without
25
+ * arguments also reports the component's props and state.
26
+ */
27
+ export const feedback: Named & {
28
+ /** What the Vite plugin rewrites `feedback(` into. Not for app code. */
29
+ at(source: string, name: string, data?: () => unknown): Named;
30
+ } = Object.assign(tagged({}), {
31
+ at: (source: string, name: string, data?: () => unknown) => tagged({ source, name, data }),
32
+ });
@@ -0,0 +1,44 @@
1
+ import type { Plugin } from 'vite';
2
+
3
+ /** The name a tag gets without one, from the component's file. */
4
+ export function componentName(file: string): string;
5
+
6
+ /** Rewrites each `{@attach feedback(...)}` call so it carries its `file:line` and a default name. `undefined` when nothing changed. */
7
+ export function addLocations(content: string, file: string): string | undefined;
8
+
9
+ /** A Svelte preprocessor that gives every `feedback()` tag its `file:line` and a default name. */
10
+ export function feedbackEngine(options?: {
11
+ /** The folder paths are written from. Defaults to the working directory. */
12
+ root?: string;
13
+ }): { name: string; markup(input: { content: string; filename?: string }): { code: string } | undefined };
14
+
15
+ /**
16
+ * A Vite plugin that forwards `path` on the dev and preview servers to ProcrastiMate and adds the token there. With a
17
+ * token, the Share menu lists ProcrastiMate. Without one it does not.
18
+ */
19
+ export function feedbackProcrastimate(options?: {
20
+ /** ProcrastiMate's origin. Defaults to `https://procrastimate.stf.lol`. */
21
+ url?: string;
22
+ /** A ProcrastiMate API token. Pass `process.env.PROCRASTIMATE_TOKEN`, so the entry shows only where it is set. */
23
+ token?: string;
24
+ /** Defaults to `/__feedback/procrastimate`. */
25
+ path?: string;
26
+ }): Plugin;
27
+
28
+ /**
29
+ * Registers a React module's components, rewrites its `feedback(` calls to carry their `file:line`, and, with
30
+ * `elementSources`, writes each HTML element's `file:line` into an attribute. `undefined` when nothing changed.
31
+ */
32
+ export function addReact(code: string, file: string, options?: { elementSources?: boolean }): string | undefined;
33
+
34
+ /**
35
+ * The Vite plugin for a React app: it finds the app's components for captures, and compiles the editor. Put it before
36
+ * the React plugin. It needs Vite 8 or later.
37
+ */
38
+ export function feedbackEngineReact(options?: {
39
+ /** Writes each HTML element's `file:line` into a `data-feedback-source` attribute. Defaults to the dev server only. */
40
+ elementSources?: boolean;
41
+ }): Plugin;
42
+
43
+ /** The attribute `elementSources` writes. */
44
+ export const sourceAttribute: string;
@@ -0,0 +1,207 @@
1
+ import { basename, relative, sep } from 'node:path';
2
+ import { parse } from 'svelte/compiler';
3
+
4
+ export { addReact, feedbackEngineReact, sourceAttribute } from './react.js';
5
+
6
+ const entry = '@stefan.inc/feedback-engine/svelte';
7
+
8
+ /** What `setupFeedbackEngine()` reads for the proxy's path. `editor/setup.ts` spells the same name. */
9
+ const procrastimateDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE';
10
+
11
+ /**
12
+ * The name a tag gets without one: the file's, as `.feedback(self)` uses the type's on iOS. A SvelteKit route file is
13
+ * named after its folder, so `routes/lists/[id]/+page.svelte` is `ListsIdPage`.
14
+ *
15
+ * @param {string} file
16
+ */
17
+ export function componentName(file) {
18
+ const pascal = (/** @type {string} */ text) =>
19
+ text
20
+ .split(/[^\p{L}\p{N}]+/u)
21
+ .filter(Boolean)
22
+ .map(word => word[0].toUpperCase() + word.slice(1))
23
+ .join('');
24
+ const stem = basename(file).replace(/\.svelte$/, '');
25
+ if (!stem.startsWith('+')) return pascal(stem) || 'Component';
26
+ const folders = file.split('/').slice(0, -1);
27
+ const routes = folders.lastIndexOf('routes');
28
+ return pascal([...folders.slice(routes + 1), stem].join(' '));
29
+ }
30
+
31
+ /**
32
+ * The names a bare `feedback()` reports, as `.feedback(self)` reports a view's stored properties and state on iOS: the
33
+ * component's props, and the variables it declares with `$state`.
34
+ *
35
+ * @param {any} instance The component's instance script.
36
+ * @returns {string[]}
37
+ */
38
+ function dataNames(instance) {
39
+ /** @type {string[]} */
40
+ const names = [];
41
+ for (const statement of instance?.content.body ?? []) {
42
+ if (statement.type !== 'VariableDeclaration') continue;
43
+ for (const { id, init } of statement.declarations) {
44
+ if (init?.type !== 'CallExpression') continue;
45
+ const callee = init.callee.type === 'MemberExpression' ? init.callee.object : init.callee;
46
+ if (callee.type !== 'Identifier') continue;
47
+ if (callee.name === '$state' && id.type === 'Identifier') names.push(id.name);
48
+ if (callee.name !== '$props') continue;
49
+ if (id.type === 'Identifier') names.push(`...${id.name}`);
50
+ for (const property of id.type === 'ObjectPattern' ? id.properties : []) {
51
+ if (property.type !== 'Property') continue;
52
+ const value = property.value.type === 'AssignmentPattern' ? property.value.left : property.value;
53
+ if (value.type === 'Identifier') names.push(value.name);
54
+ }
55
+ }
56
+ }
57
+ return names;
58
+ }
59
+
60
+ /**
61
+ * Finds every `{@attach feedback(...)}` in a component and rewrites the call to `feedback.at("file:line", "Name")(...)`.
62
+ * JavaScript has no `#fileID` and `#line`, so the location is written in at build time. A call without arguments also
63
+ * gets the component's props and state as its data.
64
+ *
65
+ * @param {string} content
66
+ * @param {string} file The component's path from the project root.
67
+ * @returns {string | undefined} The new source, or `undefined` when nothing changed.
68
+ */
69
+ export function addLocations(content, file) {
70
+ if (!content.includes(entry)) return;
71
+ const ast = parse(content, { modern: true, filename: file });
72
+ /** @type {Set<string>} */
73
+ const locals = new Set();
74
+ for (const script of [ast.instance, ast.module]) {
75
+ for (const node of script?.content.body ?? []) {
76
+ if (node.type !== 'ImportDeclaration' || node.source.value !== entry) continue;
77
+ for (const specifier of node.specifiers) {
78
+ if (
79
+ specifier.type === 'ImportSpecifier' &&
80
+ specifier.imported.type === 'Identifier' &&
81
+ specifier.imported.name === 'feedback'
82
+ ) {
83
+ locals.add(specifier.local.name);
84
+ }
85
+ }
86
+ }
87
+ }
88
+ if (!locals.size) return;
89
+
90
+ /** @type {{ at: number, text: string }[]} */
91
+ const edits = [];
92
+ const name = JSON.stringify(componentName(file));
93
+ const names = dataNames(ast.instance);
94
+ const data = names.length ? `, () => ({ ${names.join(', ')} })` : '';
95
+ const visit = (/** @type {any} */ node) => {
96
+ if (!node || typeof node !== 'object') return;
97
+ if (Array.isArray(node)) return node.forEach(visit);
98
+ if (node.type === 'AttachTag') {
99
+ const call = node.expression;
100
+ if (call.type === 'CallExpression' && call.callee.type === 'Identifier' && locals.has(call.callee.name)) {
101
+ const line = content.slice(0, call.start).split('\n').length;
102
+ const bare = call.arguments.length === 0 ? data : '';
103
+ edits.push({ at: call.callee.end, text: `.at(${JSON.stringify(`${file}:${line}`)}, ${name}${bare})` });
104
+ }
105
+ return;
106
+ }
107
+ for (const key of [
108
+ 'fragment',
109
+ 'nodes',
110
+ 'attributes',
111
+ 'consequent',
112
+ 'alternate',
113
+ 'body',
114
+ 'fallback',
115
+ 'pending',
116
+ 'then',
117
+ 'catch',
118
+ ]) {
119
+ visit(node[key]);
120
+ }
121
+ };
122
+ visit(ast.fragment);
123
+ if (!edits.length) return;
124
+ let code = content;
125
+ for (const edit of edits.toSorted((a, b) => b.at - a.at))
126
+ code = code.slice(0, edit.at) + edit.text + code.slice(edit.at);
127
+ return code;
128
+ }
129
+
130
+ /**
131
+ * A Svelte preprocessor that gives every `feedback()` tag its `file:line` and a default name. Add it to the
132
+ * preprocessors of the Svelte or SvelteKit Vite plugin.
133
+ *
134
+ * @param {{ root?: string }} [options] `root` is the folder paths are written from. Defaults to the working directory.
135
+ */
136
+ export function feedbackEngine(options = {}) {
137
+ const root = options.root ?? process.cwd();
138
+ return {
139
+ name: 'feedback-engine',
140
+ /** @param {{ content: string, filename?: string }} input */
141
+ markup({ content, filename }) {
142
+ if (!filename || filename.includes('node_modules')) return;
143
+ const code = addLocations(content, relative(root, filename).split(sep).join('/'));
144
+ return code === undefined ? undefined : { code };
145
+ },
146
+ };
147
+ }
148
+
149
+ /**
150
+ * A Vite plugin that lets the page post to ProcrastiMate. A browser on another origin cannot call ProcrastiMate, and a
151
+ * token in the page would be public, so the dev and preview servers forward `path` to ProcrastiMate and add the
152
+ * token there.
153
+ *
154
+ * The token is the switch. With one, the plugin tells the page where the proxy is, and the Share menu lists
155
+ * ProcrastiMate. Without one the page is told nothing, so the entry is not there. A page that names the path itself
156
+ * then gets a 501 that says why.
157
+ *
158
+ * @param {{ url?: string, token?: string, path?: string }} [options]
159
+ */
160
+ export function feedbackProcrastimate(options = {}) {
161
+ const path = options.path ?? '/__feedback/procrastimate';
162
+ const target = (options.url ?? 'https://procrastimate.stf.lol').replace(/\/$/, '');
163
+ /** @type {import('vite').Connect.NextHandleFunction} */
164
+ const handler = async (request, response, next) => {
165
+ if (!request.url?.startsWith(`${path}/`)) return next();
166
+ const reply = (/** @type {number} */ status, /** @type {string} */ message) => {
167
+ response.statusCode = status;
168
+ response.setHeader('Content-Type', 'application/json');
169
+ response.end(JSON.stringify({ message }));
170
+ };
171
+ if (!options.token)
172
+ return reply(501, 'the dev server has no ProcrastiMate token. Pass one to feedbackProcrastimate().');
173
+ try {
174
+ const chunks = [];
175
+ for await (const chunk of request) chunks.push(chunk);
176
+ const body = Buffer.concat(chunks);
177
+ const upstream = await fetch(target + request.url.slice(path.length), {
178
+ method: request.method,
179
+ headers: {
180
+ Authorization: `Bearer ${options.token}`,
181
+ 'User-Agent': 'Feedback',
182
+ ...(request.headers['content-type'] ? { 'Content-Type': request.headers['content-type'] } : {}),
183
+ },
184
+ body: body.length ? body : undefined,
185
+ });
186
+ response.statusCode = upstream.status;
187
+ response.setHeader('Content-Type', upstream.headers.get('content-type') ?? 'application/json');
188
+ response.end(Buffer.from(await upstream.arrayBuffer()));
189
+ } catch (error) {
190
+ reply(502, `the dev server could not reach ${target}: ${/** @type {Error} */ (error).message}`);
191
+ }
192
+ };
193
+ return {
194
+ name: 'feedback-engine-procrastimate',
195
+ config() {
196
+ return { define: { [procrastimateDefine]: JSON.stringify(options.token ? path : '') } };
197
+ },
198
+ /** @param {import('vite').ViteDevServer} server */
199
+ configureServer(server) {
200
+ server.middlewares.use(handler);
201
+ },
202
+ /** @param {import('vite').PreviewServer} server */
203
+ configurePreviewServer(server) {
204
+ server.middlewares.use(handler);
205
+ },
206
+ };
207
+ }
@@ -0,0 +1,172 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { relative, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { parseSync } from 'oxc-parser';
5
+ import { compile } from 'svelte/compiler';
6
+
7
+ const entry = '@stefan.inc/feedback-engine/react';
8
+ /** The same name as `sourceAttribute` in `dom/tags.ts`. Node cannot import that file from `node_modules`, so a test compares the two. */
9
+ export const sourceAttribute = 'data-feedback-source';
10
+ /** The package's own source folder. Only its Svelte files are compiled, and its modules are never registered. */
11
+ export const packageSource = realpathSync(fileURLToPath(new URL('..', import.meta.url))) + sep;
12
+
13
+ /**
14
+ * Compiles one of the editor's Svelte files to JavaScript, with its styles in the code, for a React app's bundler.
15
+ *
16
+ * @param {string} code
17
+ * @param {string} file
18
+ * @param {'client' | 'server'} generate
19
+ */
20
+ export function compileEditor(code, file, generate) {
21
+ const { js } = compile(code, { filename: file, css: 'injected', generate });
22
+ return js;
23
+ }
24
+
25
+ const wrappers = new Set(['TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression', 'ParenthesizedExpression']);
26
+ const values = new Set(['ArrowFunctionExpression', 'FunctionExpression', 'ClassExpression', 'CallExpression']);
27
+
28
+ /**
29
+ * Whether a variable's value can be a component: a function, a class, or a call such as `memo(...)`. A call that
30
+ * returns something else is registered too, and never matches anything React renders.
31
+ *
32
+ * @param {any} init
33
+ */
34
+ function canBeComponent(init) {
35
+ let value = init;
36
+ while (value && wrappers.has(value.type)) value = value.expression;
37
+ return Boolean(value) && values.has(value.type);
38
+ }
39
+
40
+ const named = (/** @type {any} */ id) => id?.type === 'Identifier' && /^[A-Z]/.test(id.name);
41
+
42
+ /**
43
+ * Prepares a React module for feedback captures.
44
+ *
45
+ * - Registers every component the module declares at its top level, with its name and `file:line`. React keeps a
46
+ * component's name only as the function's name, which a minified build replaces, and has no record of where a
47
+ * component came from. Being registered is also what tells the app's components from a library's.
48
+ * - Rewrites each `feedback(` call to `feedback.at("file:line")(`, as the Svelte preprocessor does.
49
+ * - With `elementSources`, gives every HTML element its `file:line` in an attribute. React 19 no longer records it.
50
+ *
51
+ * Every edit stays on its line, so the module's line numbers hold without a source map.
52
+ *
53
+ * @param {string} code
54
+ * @param {string} file The module's path from the project root.
55
+ * @param {{ elementSources?: boolean }} [options]
56
+ * @returns {string | undefined} The new source, or `undefined` when nothing changed or the module does not parse.
57
+ */
58
+ export function addReact(code, file, options = {}) {
59
+ const { program, errors } = parseSync(file, code);
60
+ if (errors.length) return;
61
+ // A server functions module may export only async functions, and a registration call is not one.
62
+ if (program.body[0]?.type === 'ExpressionStatement' && program.body[0].directive === 'use server') return;
63
+
64
+ const lineStarts = [0];
65
+ for (let index = code.indexOf('\n'); index !== -1; index = code.indexOf('\n', index + 1)) lineStarts.push(index + 1);
66
+ const where = (/** @type {number} */ offset) => {
67
+ let low = 0;
68
+ let high = lineStarts.length - 1;
69
+ while (low < high) {
70
+ const middle = (low + high + 1) >> 1;
71
+ if (lineStarts[middle] <= offset) low = middle;
72
+ else high = middle - 1;
73
+ }
74
+ return `${file}:${low + 1}`;
75
+ };
76
+
77
+ /** @type {[name: string, source: string][]} */
78
+ const components = [];
79
+ /** @type {Set<string>} */
80
+ const locals = new Set();
81
+ for (const statement of /** @type {any[]} */ (program.body)) {
82
+ if (statement.type === 'ImportDeclaration' && statement.source.value === entry) {
83
+ for (const specifier of statement.specifiers) {
84
+ if (specifier.type === 'ImportSpecifier' && specifier.imported.name === 'feedback')
85
+ locals.add(specifier.local.name);
86
+ }
87
+ }
88
+ const declaration = /^Export(Named|Default)Declaration$/.test(statement.type) ? statement.declaration : statement;
89
+ if (!declaration || declaration.declare) continue;
90
+ if (/^(Function|Class)Declaration$/.test(declaration.type) && named(declaration.id) && declaration.body) {
91
+ components.push([declaration.id.name, where(declaration.id.start)]);
92
+ }
93
+ for (const { id, init } of declaration.type === 'VariableDeclaration' ? declaration.declarations : []) {
94
+ if (named(id) && canBeComponent(init)) components.push([id.name, where(id.start)]);
95
+ }
96
+ }
97
+
98
+ /** @type {{ at: number, text: string }[]} */
99
+ const edits = [];
100
+ const visit = (/** @type {any} */ node) => {
101
+ if (!node || typeof node !== 'object') return;
102
+ if (Array.isArray(node)) return node.forEach(visit);
103
+ if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && locals.has(node.callee.name)) {
104
+ edits.push({ at: node.callee.end, text: `.at(${JSON.stringify(where(node.start))})` });
105
+ }
106
+ if (
107
+ options.elementSources &&
108
+ node.type === 'JSXOpeningElement' &&
109
+ node.name.type === 'JSXIdentifier' &&
110
+ /^[a-z]/.test(node.name.name) &&
111
+ !node.attributes.some((/** @type {any} */ attribute) => attribute.name?.name === sourceAttribute)
112
+ ) {
113
+ edits.push({ at: node.name.end, text: ` ${sourceAttribute}={${JSON.stringify(where(node.start))}}` });
114
+ }
115
+ for (const key in node) if (key !== 'type') visit(node[key]);
116
+ };
117
+ visit(program.body);
118
+
119
+ if (!edits.length && !components.length) return;
120
+ let changed = code;
121
+ for (const edit of edits.toSorted((a, b) => b.at - a.at))
122
+ changed = changed.slice(0, edit.at) + edit.text + changed.slice(edit.at);
123
+ if (!components.length) return changed;
124
+ const calls = components.map(
125
+ ([name, source]) => `register(${name}, ${JSON.stringify(name)}, ${JSON.stringify(source)});`,
126
+ );
127
+ // A value that is not a function or an object cannot be a component, and a WeakMap would throw on it.
128
+ return `${changed}\n;(register => { ${calls.join(' ')} })((component, name, source) => { if (typeof component === 'function' || (typeof component === 'object' && component !== null)) (globalThis.__feedbackComponents ??= new WeakMap()).set(component, [name, source]); });\n`;
129
+ }
130
+
131
+ /**
132
+ * The Vite plugin for a React app. Put it before the React plugin.
133
+ *
134
+ * - It runs `addReact` on the app's `.jsx` and `.tsx` modules, so a capture finds the app's components by name.
135
+ * - It compiles the editor, which is written in Svelte, so the app needs no Svelte plugin of its own.
136
+ *
137
+ * @param {{ elementSources?: boolean }} [options] `elementSources` defaults to the dev server only, and never in tests.
138
+ */
139
+ export function feedbackEngineReact(options = {}) {
140
+ let root = process.cwd();
141
+ let elementSources = false;
142
+ return {
143
+ name: 'feedback-engine-react',
144
+ enforce: /** @type {const} */ ('pre'),
145
+ // Pre-bundling would meet the editor's Svelte files without this plugin to compile them.
146
+ config: () => ({ optimizeDeps: { exclude: ['@stefan.inc/feedback-engine'] } }),
147
+ /** @param {import('vite').ResolvedConfig} config */
148
+ configResolved(config) {
149
+ root = config.root;
150
+ elementSources = options.elementSources ?? (config.command === 'serve' && config.mode !== 'test');
151
+ },
152
+ transform: {
153
+ filter: { id: /\.(svelte|jsx|tsx)(\?.*)?$/ },
154
+ /**
155
+ * @param {string} code
156
+ * @param {string} id
157
+ * @param {{ ssr?: boolean }} [transformOptions]
158
+ */
159
+ handler(code, id, transformOptions) {
160
+ const file = id.split('?')[0];
161
+ if (file.endsWith('.svelte')) {
162
+ if (!file.startsWith(packageSource)) return;
163
+ const js = compileEditor(code, file, transformOptions?.ssr ? 'server' : 'client');
164
+ return { code: js.code, map: js.map };
165
+ }
166
+ if (file.includes('/node_modules/') || file.startsWith(packageSource)) return;
167
+ const changed = addReact(code, relative(root, file).split(sep).join('/'), { elementSources });
168
+ return changed === undefined ? undefined : { code: changed, map: null };
169
+ },
170
+ },
171
+ };
172
+ }