@stefan.inc/feedback-engine 1.9.0 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -198,7 +198,7 @@ export function Feedback() {
198
198
  - Client components are in the capture under their own names, as in a Vite app. A server component leaves no component in the page, so it is not a node. The elements it draws are, each with its own `file:line`.
199
199
  - On a deployed preview, such as a Vercel preview link, pass `withFeedbackEngine(config, { elementSources: true })` so a production build keeps every element's `file:line`. Components keep theirs in every build without it. The attribute puts your file paths in the page's HTML, so leave it off a public production deploy, for example with `elementSources: process.env.VERCEL_ENV === 'preview'`.
200
200
  - To keep Feedback off a production deploy, render `<Feedback />` only where you want it, for example behind `process.env.NEXT_PUBLIC_VERCEL_ENV !== 'production'`.
201
- - `feedbackProcrastimate()` is a Vite plugin, so a Next.js app has no ProcrastiMate entry unless you pass `procrastimate: { url, projects }` for a proxy of your own.
201
+ - [Post to ProcrastiMate](#post-to-procrastimate) works the same in Next.js as in Vite: pass `procrastimate: { projects: ['Your Project'] }` to `setupFeedbackEngine()`.
202
202
 
203
203
  ## Component data and untagged content
204
204
 
@@ -229,9 +229,7 @@ The editor works as on iOS, with these differences:
229
229
 
230
230
  Optional, and off until you configure it. [ProcrastiMate](https://github.com/smirea/procrastimate) is the task app that Feedback's author files feedback into.
231
231
 
232
- ### With the signed-in ProcrastiMate account (recommended)
233
-
234
- Pass the whitelisted `projects` to `setupFeedbackEngine()` with no `url` and no token:
232
+ Pass the whitelisted `projects` to `setupFeedbackEngine()`:
235
233
 
236
234
  ```ts
237
235
  setupFeedbackEngine({
@@ -240,32 +238,13 @@ setupFeedbackEngine({
240
238
  });
241
239
  ```
242
240
 
243
- Choosing **ProcrastiMate** opens a popup on `https://procrastimate.stf.lol/feedback` (or `procrastimate.app`) and hands over the annotated screenshot and `feedback.json` via `postMessage`. Because the popup runs on ProcrastiMate's own origin, it uses whoever is signed into ProcrastiMate in that browser (or lets them sign in there) with no hardcoded token, no backend proxy, and no CORS setup, so it works on deployed static sites, Vite, and Next.js alike. Anyone with an `edit` share on a listed project posts under their own account. Pass `space` (the project owner's user id) only if two spaces share the same project name.
244
-
245
- ### With a dev-server proxy and token
246
-
247
- For local development with a fixed personal token instead of the browser's ProcrastiMate login, `feedbackProcrastimate()` forwards calls from the Vite dev and preview servers and adds the token there:
248
-
249
- ```ts
250
- // vite.config.ts
251
- import { feedbackProcrastimate } from '@stefan.inc/feedback-engine/vite';
252
-
253
- export default defineConfig({
254
- plugins: [
255
- feedbackProcrastimate({ token: process.env.PROCRASTIMATE_TOKEN, projects: ['Website'] }),
256
- /* and the plugins above */
257
- ],
258
- });
259
- ```
260
-
261
- With the proxy plugin, the token is the switch: when `PROCRASTIMATE_TOKEN` is set, **ProcrastiMate** shows in the Share menu without any `setupFeedbackEngine()` option.
241
+ Choosing **ProcrastiMate** opens a popup on `https://procrastimate.stf.lol/feedback` (or `procrastimate.app`) and hands over the annotated screenshot and `feedback.json` via `postMessage`. Because the popup runs on ProcrastiMate's own origin, it uses whoever is signed into ProcrastiMate in that browser (or lets them sign in there) with no hardcoded token, no backend proxy, and no CORS setup, so it works on deployed static sites, Vite, and Next.js alike. Anyone with an `edit` share on a listed project posts under their own account.
262
242
 
263
- - The token is a ProcrastiMate personal token, from Settings › Personal token. An AI account's token lists the projects but cannot upload the image, so the post fails with `Not for AI accounts`. `feedbackProcrastimate({ url })` names another ProcrastiMate server.
264
- - `projects` is required in every mode: the only projects Feedback posts to, by name (ignoring case) or id, in the picker's order. There is no way to allow every project, and the Inbox is never offered. The picker opens on the last of them posted to, or the first. A listed name ProcrastiMate does not have shows as an error above the list.
265
- - Both the Vite proxy and ProcrastiMate's `/feedback` popup enforce the list. The proxy shows the page only the listed projects, creates a task only in one of them, and forwards nothing but the calls a post makes; anything else answers 403.
266
- - Each project in the picker has a ↗ link to its page in ProcrastiMate, which opens in a new tab for someone signed in to its space.
267
- - `project` names the project the picker opens on, by name (ignoring case) or id, so an app's feedback lands in its own project. It has to be one of `projects`. Without it, the picker opens on the last project posted to.
268
- - For a proxy or same-origin API of your own, pass its address and the projects to the page instead: `setupFeedbackEngine({ procrastimate: { url: '/my-proxy', projects: ['Website'] } })`. Your proxy should refuse tasks anywhere else, as this one does.
243
+ - `projects` is required and non-empty: the only projects Feedback posts to, by name (ignoring case) or id, in the picker's order. There is no way to allow every project, and the Inbox is never offered. ProcrastiMate's `/feedback` popup enforces the list and reports any missing name above the picker.
244
+ - `project` names the project the picker opens on, by name (ignoring case) or id, so an app's feedback lands in its own project. It has to be one of `projects`. Without it, the picker opens on the last project posted to, or the first listed.
245
+ - `space` names another user's ProcrastiMate user id when two spaces share the same project name; leave it out to match across the signed-in user's own and edit-shared projects.
246
+ - `app` points at another ProcrastiMate origin if you self-host or run locally.
247
+ - Each project in the picker has a ↗ link to its page in ProcrastiMate (`/projects/<id>`), which opens in a new tab.
269
248
 
270
249
  ## How capture works
271
250
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stefan.inc/feedback-engine",
3
- "version": "1.9.0",
3
+ "version": "1.10.1",
4
4
  "description": "In-app feedback for Svelte and React: point at a component, write what should change, and export its name, file:line, and data for an agent.",
5
5
  "keywords": [
6
6
  "accessibility",
@@ -1,177 +1,27 @@
1
- import { Problem } from '../core/problem.ts';
2
- import { postId } from './webhook.ts';
3
-
4
1
  export type ProcrastimateConfig = {
5
- /**
6
- * Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. Leave it out
7
- * to open a popup on the ProcrastiMate web app (`app`) that posts using whoever is signed in there, with no token
8
- * and no proxy.
9
- */
10
- url?: string;
11
- /** Sent as a bearer token. Leave it out behind the proxy or when posting through the popup. */
12
- token?: string;
13
- /** The ProcrastiMate web app, for the popup and for links to posted tasks and projects. */
2
+ /** The ProcrastiMate web app whose `/feedback` popup opens. Defaults to `https://procrastimate.stf.lol`. */
14
3
  app?: string;
15
4
  /** The project the picker opens on, by name (ignoring case) or id, in place of the last one posted to. */
16
5
  project?: string;
17
6
  /**
18
- * The only projects the picker offers, by name (ignoring case) or id, in this order. The Inbox is not offered.
19
- * Required, and not empty. A proxy of your own should refuse tasks anywhere else.
7
+ * The only projects the `/feedback` popup offers, by name (ignoring case) or id, in this order. The Inbox is not
8
+ * offered. Required, and not empty.
20
9
  */
21
10
  projects: string[];
22
11
  /**
23
- * Another user's space (their ProcrastiMate user id) whose shared projects the picker lists. Leave it out to match
24
- * across the signed-in user's own and edit-shared projects in the popup, or the token's space behind a proxy.
12
+ * Another user's space (their ProcrastiMate user id) whose shared projects the popup lists. Leave it out to match
13
+ * across the signed-in user's own and edit-shared projects.
25
14
  */
26
15
  space?: string;
27
16
  };
28
17
 
29
- export type Section = { id: string; name: string };
30
- export type Project = { id: string; name: string; sections: Section[] };
31
- /** Where a task goes: the project's top, above its sections, without a section. No project yet while none is listed. */
32
- export type Place = { projectId?: string; sectionId?: string };
33
-
34
18
  /** ProcrastiMate's `FILE_PART_BYTES` (`shared/images.ts` there): the most it takes as a file in one request. */
35
19
  export const fileMaxBytes = 16 * 1024 * 1024;
36
20
  export const defaultProcrastimateApp = 'https://procrastimate.stf.lol';
37
21
 
38
- const projectsKey = 'feedback.procrastimate.projects';
39
- const lastProjectKey = 'feedback.procrastimate.project';
40
-
41
- function stored<T>(key: string): T | undefined {
42
- try {
43
- const value = localStorage.getItem(key);
44
- return value === null ? undefined : (JSON.parse(value) as T);
45
- } catch {
46
- return undefined;
47
- }
48
- }
49
-
50
- const store = (key: string, value: unknown) => {
51
- try {
52
- if (value === undefined) localStorage.removeItem(key);
53
- else localStorage.setItem(key, JSON.stringify(value));
54
- } catch {
55
- // Storage can be off, as in a private window. The picker then opens empty.
56
- }
57
- };
58
-
59
- /** The projects from the last time the picker loaded them, so it opens filled. */
60
- export const cachedProjects = () => stored<Project[]>(projectsKey) ?? [];
61
- /** The project of the last post. Its section is not kept, so a new post starts at the project's top. */
62
- export const lastProject = () => stored<string>(lastProjectKey);
63
-
64
- /** The project `config.project` names, by id or by name ignoring case. */
65
- export const namedProject = (projects: Project[], name: string) =>
66
- projects.find(project => project.id === name) ??
67
- projects.find(project => project.name.toLowerCase() === name.toLowerCase());
68
-
69
- /** The projects the picker lists: those `names` lists, in its order. `missing` has the names ProcrastiMate lacks. */
70
- export function listedProjects(all: Project[], names: string[]) {
71
- const projects: Project[] = [];
72
- const missing: string[] = [];
73
- for (const name of names) {
74
- const project = namedProject(all, name);
75
- if (!project) missing.push(name);
76
- else if (!projects.includes(project)) projects.push(project);
77
- }
78
- return { projects, missing };
79
- }
80
-
81
- /**
82
- * The project the picker opens on, among the listed ones: the one the app names, else the last one posted to, else
83
- * the first. `undefined` only while none is listed.
84
- */
85
- export function startingProject(listed: Project[], config: ProcrastimateConfig, last: string | undefined) {
86
- if (config.project) return namedProject(listed, config.project)?.id;
87
- if (listed.some(project => project.id === last)) return last;
88
- return listed[0]?.id;
89
- }
90
-
91
22
  export const procrastimateAppURL = (config: ProcrastimateConfig) =>
92
23
  (config.app ?? defaultProcrastimateApp).replace(/\/$/, '');
93
24
 
94
- /** The project's page in the ProcrastiMate web app, which opens for someone signed in to its space. */
95
- export const projectLink = (config: ProcrastimateConfig, id: string) =>
96
- `${procrastimateAppURL(config)}/projects/${encodeURIComponent(id)}`;
97
-
98
- export const taskLink = (config: ProcrastimateConfig, id: string) =>
99
- `${procrastimateAppURL(config)}/inbox?task=${encodeURIComponent(id)}`;
100
-
101
- async function send(
102
- config: ProcrastimateConfig,
103
- method: string,
104
- path: string,
105
- query: Record<string, string> = {},
106
- body?: BodyInit,
107
- type?: string,
108
- ) {
109
- if (config.url === undefined) {
110
- throw new Error('ProcrastiMate has no API URL; popup mode posts from the ProcrastiMate web app.');
111
- }
112
- const fullQuery = config.space ? { space: config.space, ...query } : query;
113
- const search = new URLSearchParams(Object.entries(fullQuery).toSorted(([a], [b]) => a.localeCompare(b)));
114
- const url = `${config.url.replace(/\/$/, '')}/${path}${search.size ? `?${search}` : ''}`;
115
- let response: Response;
116
- try {
117
- response = await fetch(url, {
118
- method,
119
- body,
120
- headers: {
121
- ...(config.token ? { Authorization: `Bearer ${config.token}` } : {}),
122
- ...(type ? { 'Content-Type': type } : {}),
123
- },
124
- });
125
- } catch (error) {
126
- throw Problem.request(method, url, undefined, undefined, error);
127
- }
128
- if (response.ok) return response;
129
- const text = await response.text().catch(() => '');
130
- if (response.status === 401) {
131
- throw Problem.request(
132
- method,
133
- url,
134
- response.status,
135
- text,
136
- new Error('ProcrastiMate rejected the token. Check the token Feedback was set up with.'),
137
- );
138
- }
139
- let message: string | undefined;
140
- try {
141
- message = (JSON.parse(text) as { message?: string }).message;
142
- } catch {
143
- // A proxy's HTML error page, which the details show as it came.
144
- }
145
- throw Problem.request(
146
- method,
147
- url,
148
- response.status,
149
- text,
150
- new Error(message ? `ProcrastiMate: ${message}` : `ProcrastiMate answered ${response.status}.`),
151
- );
152
- }
153
-
154
- type Row = { id: string; name: string; order: number; createdAt: number };
155
- const inOrder = <T extends Row>(rows: T[]) => rows.toSorted((a, b) => a.order - b.order || a.createdAt - b.createdAt);
156
-
157
- /** The space's projects and their sections in the app's order. `/api/view` is the only route that lists them. */
158
- export async function loadProjects(config: ProcrastimateConfig): Promise<Project[]> {
159
- const view = (await (await send(config, 'GET', 'api/view')).json()) as {
160
- projects: Row[];
161
- sections: (Row & { projectId: string })[];
162
- };
163
- const projects = inOrder(view.projects).map(project => ({
164
- id: project.id,
165
- name: project.name,
166
- sections: inOrder(view.sections.filter(section => section.projectId === project.id)).map(({ id, name }) => ({
167
- id,
168
- name,
169
- })),
170
- }));
171
- store(projectsKey, projects);
172
- return projects;
173
- }
174
-
175
25
  export type EncodedImage = { blob: Blob; width: number; height: number };
176
26
 
177
27
  /**
@@ -200,60 +50,3 @@ export async function encodeTaskImages(image: HTMLCanvasElement): Promise<{ full
200
50
  const thumb = await jpeg(image, 320, 200_000);
201
51
  return { full, thumb };
202
52
  }
203
-
204
- /**
205
- * Creates one task with the image export and `feedback.json` attached, and returns its id. The attachments upload
206
- * before the task that lists them, as ProcrastiMate's own clients do, so the task never names bytes the server
207
- * cannot serve.
208
- */
209
- export async function postTask(
210
- config: ProcrastimateConfig,
211
- title: string,
212
- place: Place,
213
- image: HTMLCanvasElement,
214
- report: string,
215
- step: (text: string) => void,
216
- ) {
217
- const bytes = new TextEncoder().encode(report);
218
- if (bytes.length > fileMaxBytes)
219
- throw new Error('The JSON report is over the 16 MB ProcrastiMate takes in one upload.');
220
- step('Encoding the image');
221
- const { full, thumb } = await encodeTaskImages(image);
222
- const imageId = postId();
223
- const reportId = postId();
224
- const taskId = postId();
225
- step('Uploading the image');
226
- await send(config, 'PUT', 'api/images', { id: imageId, size: 'full' }, full.blob, 'image/jpeg');
227
- step('Uploading the thumbnail');
228
- await send(config, 'PUT', 'api/images', { id: imageId, size: 'thumb' }, thumb.blob, 'image/jpeg');
229
- step('Uploading feedback.json');
230
- await send(
231
- config,
232
- 'PUT',
233
- 'api/images',
234
- { id: reportId, size: 'file', name: 'feedback.json', type: 'application/json' },
235
- bytes,
236
- 'application/octet-stream',
237
- );
238
- step('Creating the task');
239
- const created = await send(
240
- config,
241
- 'POST',
242
- 'api/tasks',
243
- {},
244
- JSON.stringify({
245
- id: taskId,
246
- title,
247
- projectId: place.projectId ?? null,
248
- sectionId: place.sectionId ?? null,
249
- attachments: [
250
- { id: imageId, width: full.width, height: full.height },
251
- { id: reportId, name: 'feedback.json', type: 'application/json', bytes: bytes.length },
252
- ],
253
- }),
254
- 'application/json',
255
- );
256
- const { id } = (await created.json()) as { id: string };
257
- store(lastProjectKey, place.projectId);
258
- return id;
259
- }
@@ -54,11 +54,71 @@ export function parsePopupReply(
54
54
  function popupFeatures() {
55
55
  const width = 460;
56
56
  const height = 680;
57
- const left = Math.max(0, Math.round((window.screenX ?? 0) + (window.outerWidth - width) / 2));
58
- const top = Math.max(0, Math.round((window.screenY ?? 0) + (window.outerHeight - height) / 2));
57
+ const scr = window.screen as { availLeft?: number; availTop?: number };
58
+ const rawLeft = Math.round((window.screenX ?? 0) + (window.outerWidth - width) / 2);
59
+ const rawTop = Math.round((window.screenY ?? 0) + (window.outerHeight - height) / 2);
60
+ const left = scr.availLeft === undefined ? rawLeft : Math.max(scr.availLeft, rawLeft);
61
+ const top = scr.availTop === undefined ? rawTop : Math.max(scr.availTop, rawTop);
59
62
  return `popup,width=${width},height=${height},left=${left},top=${top}`;
60
63
  }
61
64
 
65
+ /**
66
+ * Distinguishes a real browser WindowProxy from `null`, an already-closed window, or a plain JS stub returned by a
67
+ * popup-blocker extension (which sets `location.href` synchronously and leaves `closed: false` forever).
68
+ */
69
+ export function isRealPopup(popup: unknown, expectedOrigin: string, currentOrigin: string): popup is Window {
70
+ if (!popup || (typeof popup !== 'object' && typeof popup !== 'function')) return false;
71
+ const candidate = popup as Window;
72
+ try {
73
+ if (candidate.closed) return false;
74
+ } catch {
75
+ return false;
76
+ }
77
+ let href: string;
78
+ try {
79
+ href = candidate.location.href;
80
+ } catch {
81
+ // Reading `location.href` threw a cross-origin SecurityError: only a real browser WindowProxy enforces that.
82
+ return true;
83
+ }
84
+ if (Object.prototype.toString.call(candidate) !== '[object Window]') return false;
85
+ if (expectedOrigin !== currentOrigin && typeof href === 'string' && href.startsWith(expectedOrigin)) return false;
86
+ return true;
87
+ }
88
+
89
+ /**
90
+ * Runs `action` on the shadow host's light-DOM click bubble when the click originated inside a shadow root.
91
+ * Per the DOM spec, browsers clear `window.event` while an event dispatches inside a shadow tree, which causes popup
92
+ * blockers that inspect `window.event.currentTarget` (such as Poper Blocker) to treat a real button click as having no
93
+ * user interaction. Waiting one synchronous propagation step onto `root.host` restores `window.event` within the same
94
+ * click gesture.
95
+ */
96
+ export function runOnLightClick(event: MouseEvent | undefined, action: () => void) {
97
+ if (!event || !event.bubbles || !event.composed || event.cancelBubble) {
98
+ action();
99
+ return;
100
+ }
101
+ const path = event.composedPath();
102
+ const root = (path[0] as Node | undefined)?.getRootNode?.();
103
+ if (!(root instanceof ShadowRoot) || !path.includes(root.host)) {
104
+ action();
105
+ return;
106
+ }
107
+ let ran = false;
108
+ const host = root.host;
109
+ const onHostClick = (bubbled: Event) => {
110
+ if (bubbled !== event || ran) return;
111
+ ran = true;
112
+ host.removeEventListener(event.type, onHostClick);
113
+ action();
114
+ };
115
+ host.addEventListener(event.type, onHostClick);
116
+ // Macrotask, not microtask: browsers drain microtasks between each listener in an event's bubble path.
117
+ setTimeout(() => {
118
+ if (!ran) host.removeEventListener(event.type, onHostClick);
119
+ }, 0);
120
+ }
121
+
62
122
  /**
63
123
  * Opens ProcrastiMate's `/feedback` popup synchronously (so the browser's click gesture allows `window.open`) while
64
124
  * encoding the screenshot in parallel, then hands over the draft over `postMessage` once the popup signals ready.
@@ -102,7 +162,7 @@ export function openProcrastimatePopup({
102
162
  }
103
163
 
104
164
  const popup = window.open(url, 'feedback-procrastimate', popupFeatures());
105
- if (!popup) {
165
+ if (!isRealPopup(popup, expectedOrigin, location.origin)) {
106
166
  onerror(
107
167
  new Problem('The browser blocked ProcrastiMate’s window. Allow pop-ups for this site and try again.', [
108
168
  { label: 'URL', value: url },
@@ -111,6 +171,11 @@ export function openProcrastimatePopup({
111
171
  );
112
172
  return { cancel() {} };
113
173
  }
174
+ try {
175
+ popup.focus();
176
+ } catch {
177
+ // Some browsers restrict focusing a popup window.
178
+ }
114
179
 
115
180
  // Render synchronously before any await; encode JPEGs while the popup loads.
116
181
  let prepared: Promise<{ full: Blob; thumb: Blob; width: number; height: number }>;
@@ -15,7 +15,7 @@
15
15
  type SavedWebhook,
16
16
  } from '../core/index.ts';
17
17
  import type { Screen } from '../dom/capture.ts';
18
- import { openProcrastimatePopup } from '../dom/procrastimatePopup.ts';
18
+ import { openProcrastimatePopup, runOnLightClick } from '../dom/procrastimatePopup.ts';
19
19
  import {
20
20
  buildExport,
21
21
  canShare,
@@ -31,7 +31,6 @@
31
31
  import { destinations, pinnedDestinations, type Destination } from './destinations.ts';
32
32
  import type { Engine } from './engine.ts';
33
33
  import ProblemCard from './ProblemCard.svelte';
34
- import ProcrastimateSheet from './ProcrastimateSheet.svelte';
35
34
  import WebhookDialog from './WebhookDialog.svelte';
36
35
  import WebhookSheet from './WebhookSheet.svelte';
37
36
 
@@ -99,7 +98,6 @@
99
98
  /** The list of items starts open beside the screenshot, and closed under it on a phone, where it would cover the picture. */
100
99
  let showsItems = $state(matchMedia('(min-width: 900px)').matches);
101
100
  let showsShare = $state(false);
102
- let showsProcrastimate = $state(false);
103
101
  let popup = { cancel() {} };
104
102
  let posting = $state<Delivery>();
105
103
 
@@ -270,8 +268,8 @@
270
268
  failure = undefined;
271
269
  } else if (confirmsClose) {
272
270
  confirmsClose = false;
273
- } else if (showsInfo || showsShare || showsProcrastimate || posting || pending || editing) {
274
- showsInfo = showsShare = showsProcrastimate = false;
271
+ } else if (showsInfo || showsShare || posting || pending || editing) {
272
+ showsInfo = showsShare = false;
275
273
  posting = pending = editing = undefined;
276
274
  } else if (session.isTyping || session.unshared.length) {
277
275
  confirmsClose = true;
@@ -280,37 +278,41 @@
280
278
  }
281
279
  }
282
280
 
283
- function send(destination: Destination) {
281
+ function send(destination: Destination, event?: MouseEvent) {
284
282
  showsShare = false;
285
283
  if (destination.kind === 'procrastimate') {
286
284
  const config = engine.options.procrastimate;
287
285
  if (!config) return;
288
- if (config.url !== undefined) {
289
- showsProcrastimate = true;
290
- } else {
286
+ runOnLightClick(event, () => {
291
287
  popup.cancel();
292
288
  const items = [...session.items];
293
289
  const names = taskTitle(session.capture, items);
294
- popup = openProcrastimatePopup({
295
- config,
296
- title: names.placeholder,
297
- app: engine.options.app ?? (document.title.trim() || undefined),
298
- screen,
299
- annotations: session.annotations,
300
- report: session.compactJSON,
301
- onposted: ({ destination: where, url }) => {
302
- act(() => {
303
- session.markShared(items);
304
- session.toast = { text: `Added to ${where} in ProcrastiMate`, link: url };
305
- });
306
- },
307
- onerror: problem => {
308
- act(() => {
309
- session.toast = { text: 'Couldn’t open ProcrastiMate', problem };
310
- });
311
- },
312
- });
313
- }
290
+ try {
291
+ popup = openProcrastimatePopup({
292
+ config,
293
+ title: names.placeholder,
294
+ app: engine.options.app ?? (document.title.trim() || undefined),
295
+ screen,
296
+ annotations: session.annotations,
297
+ report: session.compactJSON,
298
+ onposted: ({ destination: where, url }) => {
299
+ act(() => {
300
+ session.markShared(items);
301
+ session.toast = { text: `Added to ${where} in ProcrastiMate`, link: url };
302
+ });
303
+ },
304
+ onerror: problem => {
305
+ act(() => {
306
+ session.toast = { text: 'Couldn’t open ProcrastiMate', problem };
307
+ });
308
+ },
309
+ });
310
+ } catch (error) {
311
+ act(() => {
312
+ session.toast = { text: 'Couldn’t open ProcrastiMate', problem: Problem.from(error) };
313
+ });
314
+ }
315
+ });
314
316
  } else if (destination.kind === 'saved') edit(destination.saved);
315
317
  else posting = destination.delivery;
316
318
  }
@@ -413,7 +415,7 @@
413
415
  <button type="button" role="menuitem" onclick={() => void choose(format as ExportFormat)}>{name}</button>
414
416
  {/each}
415
417
  {#each targets as destination, index (index)}
416
- <button type="button" role="menuitem" class="destination" onclick={() => send(destination)}>
418
+ <button type="button" role="menuitem" class="destination" onclick={event => send(destination, event)}>
417
419
  {#if destination.image}<img src={destination.image} alt="" />{/if}
418
420
  {destination.name}
419
421
  </button>
@@ -432,7 +434,7 @@
432
434
  aria-label={destination.name}
433
435
  title={destination.name}
434
436
  disabled={!view.items.length || busy}
435
- onclick={() => send(destination)}
437
+ onclick={event => send(destination, event)}
436
438
  >
437
439
  {#if destination.image}
438
440
  <img src={destination.image} alt="" />
@@ -659,8 +661,8 @@
659
661
  <button
660
662
  type="button"
661
663
  class:failed={problem}
662
- onclick={() => {
663
- if (link) open(link, '_blank', 'noopener');
664
+ onclick={event => {
665
+ if (link) runOnLightClick(event, () => open(link, '_blank', 'noopener'));
664
666
  if (problem) failure = { title: text, problem };
665
667
  act(() => (session.toast = undefined));
666
668
  }}
@@ -670,22 +672,6 @@
670
672
  </div>
671
673
  {/if}
672
674
 
673
- {#if showsProcrastimate && engine.options.procrastimate}
674
- <ProcrastimateSheet
675
- {screen}
676
- {session}
677
- config={engine.options.procrastimate}
678
- onclose={() => (showsProcrastimate = false)}
679
- onposted={(items, toast) => {
680
- showsProcrastimate = false;
681
- act(() => {
682
- session.markShared(items);
683
- session.toast = toast;
684
- });
685
- }}
686
- />
687
- {/if}
688
-
689
675
  {#if editing}
690
676
  {@const webhook = editing.webhook}
691
677
  <WebhookDialog
@@ -26,10 +26,8 @@ export type FeedbackOptions = {
26
26
  */
27
27
  threeFingerHold?: boolean;
28
28
  /**
29
- * Adds ProcrastiMate to the Share menu. Pass `{ projects: ['Website'] }` (with no `url`) to post through a popup on
30
- * the ProcrastiMate web app using whoever is signed in there, with no token and no proxy. Pass `{ url, projects }`
31
- * for a same-origin API or a proxy of your own. Leave it out behind `feedbackProcrastimate()` from the Vite entry
32
- * point, which adds the entry by itself when it has a token.
29
+ * Adds ProcrastiMate to the Share menu. Pass `{ projects: ['Website'] }` to post through a popup on the
30
+ * ProcrastiMate web app (`/feedback`) using whoever is signed in there, with no token and no proxy.
33
31
  */
34
32
  procrastimate?: ProcrastimateConfig;
35
33
  /**
@@ -55,20 +55,9 @@ export function setupFeedbackEngine(options: FeedbackOptions = {}): FeedbackEngi
55
55
  }
56
56
  current?.destroy();
57
57
 
58
- // Written by `feedbackProcrastimate()` when it has a token. Vite replaces the whole member expression, so it stays in
59
- // one piece. Webpack has no `import.meta.env`. The cast needs no `import.meta.env` type from the app.
60
- type Meta = { env?: Record<string, string | undefined> };
61
- const proxy = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE;
62
- const project = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE_PROJECT;
63
- const projects = (import.meta as Meta).env && (import.meta as Meta).env!.FEEDBACK_PROCRASTIMATE_PROJECTS;
64
- const procrastimate =
65
- options.procrastimate ??
66
- (proxy
67
- ? { url: proxy, project: project || undefined, projects: JSON.parse(projects || '[]') as string[] }
68
- : undefined);
69
- if (procrastimate && !procrastimate.projects?.length)
58
+ if (options.procrastimate && !options.procrastimate.projects?.length)
70
59
  throw new Error('setupFeedbackEngine({ procrastimate }) needs the projects Feedback may post to, by name or id.');
71
- const engine = new Engine({ ...options, procrastimate });
60
+ const engine = new Engine(options);
72
61
  const host = document.createElement('div');
73
62
  host.setAttribute(hostAttribute, '');
74
63
  // The shadow root keeps the app's styles out of the editor and the editor's styles out of the app.
@@ -24,32 +24,22 @@ export type FeedbackOptions = {
24
24
  */
25
25
  threeFingerHold?: boolean;
26
26
  /**
27
- * Adds ProcrastiMate to the Share menu. Pass `{ projects: ['Website'] }` (with no `url`) to post through a popup on
28
- * the ProcrastiMate web app using whoever is signed in there, with no token and no proxy. Pass `{ url, projects }`
29
- * for a same-origin API or a proxy of your own. Leave it out behind `feedbackProcrastimate()` from the Vite entry
30
- * point, which adds the entry by itself when it has a token.
27
+ * Adds ProcrastiMate to the Share menu. Pass `{ projects: ['Website'] }` to post through a popup on the
28
+ * ProcrastiMate web app (`/feedback`) using whoever is signed in there, with no token and no proxy.
31
29
  */
32
30
  procrastimate?: {
33
- /**
34
- * Where ProcrastiMate's API answers: the Vite plugin's proxy path, or a server that allows this origin. Leave it
35
- * out to open a popup on the ProcrastiMate web app (`app`) that posts using whoever is signed in there, with no
36
- * token and no proxy.
37
- */
38
- url?: string;
39
- /** Sent as a bearer token. Leave it out behind the proxy or when posting through the popup. */
40
- token?: string;
41
- /** The ProcrastiMate web app, for the popup and for links to posted tasks and projects. */
31
+ /** The ProcrastiMate web app whose `/feedback` popup opens. Defaults to `https://procrastimate.stf.lol`. */
42
32
  app?: string;
43
33
  /** The project the picker opens on, by name (ignoring case) or id, in place of the last one posted to. */
44
34
  project?: string;
45
35
  /**
46
- * The only projects the picker offers, by name (ignoring case) or id, in this order. The Inbox is not offered.
47
- * Required, and not empty. A proxy of your own should refuse tasks anywhere else.
36
+ * The only projects the `/feedback` popup offers, by name (ignoring case) or id, in this order. The Inbox is not
37
+ * offered. Required, and not empty.
48
38
  */
49
39
  projects: string[];
50
40
  /**
51
- * Another user's space (their ProcrastiMate user id) whose shared projects the picker lists. Leave it out to match
52
- * across the signed-in user's own and edit-shared projects in the popup, or the token's space behind a proxy.
41
+ * Another user's space (their ProcrastiMate user id) whose shared projects the popup lists. Leave it out to match
42
+ * across the signed-in user's own and edit-shared projects.
53
43
  */
54
44
  space?: string;
55
45
  };
@@ -12,27 +12,6 @@ export function feedbackEngine(options?: {
12
12
  root?: string;
13
13
  }): { name: string; markup(input: { content: string; filename?: string }): { code: string } | undefined };
14
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. It forwards only what a post needs, and creates
18
- * tasks only in the listed projects.
19
- */
20
- export function feedbackProcrastimate(options: {
21
- /** ProcrastiMate's origin. Defaults to `https://procrastimate.stf.lol`. */
22
- url?: string;
23
- /** A ProcrastiMate API token. Pass `process.env.PROCRASTIMATE_TOKEN`, so the entry shows only where it is set. */
24
- token?: string;
25
- /** Defaults to `/__feedback/procrastimate`. */
26
- path?: string;
27
- /** The project the picker opens on, by name (ignoring case) or id, in place of the last one posted to. */
28
- project?: string;
29
- /**
30
- * The only projects Feedback posts to, by name (ignoring case) or id, in the picker's order, each with a link to its
31
- * page in ProcrastiMate. The proxy refuses a task anywhere else, the Inbox included. Required, and not empty.
32
- */
33
- projects: string[];
34
- }): Plugin;
35
-
36
15
  /**
37
16
  * Registers a React module's components, rewrites its `feedback(` calls to carry their `file:line`, and, with
38
17
  * `elementSources`, writes each HTML element's `file:line` into an attribute. `undefined` when nothing changed.
package/src/vite/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { basename, relative, sep } from 'node:path';
2
2
  import { parse } from 'svelte/compiler';
3
3
 
4
- export { feedbackProcrastimate } from './procrastimate.js';
5
4
  export { addReact, feedbackEngineReact, sourceAttribute } from './react.js';
6
5
 
7
6
  const entry = '@stefan.inc/feedback-engine/svelte';
@@ -1,249 +0,0 @@
1
- <svelte:options css="injected" />
2
-
3
- <script lang="ts">
4
- import { Problem, taskTitle, type Fact, type FeedbackItem, type Session, type Toast } from '../core/index.ts';
5
- import type { Screen } from '../dom/capture.ts';
6
- import { annotatedImage } from '../dom/image.ts';
7
- import {
8
- cachedProjects,
9
- lastProject,
10
- listedProjects,
11
- loadProjects,
12
- postTask,
13
- projectLink,
14
- startingProject,
15
- taskLink,
16
- type Place,
17
- type ProcrastimateConfig,
18
- } from '../dom/procrastimate.ts';
19
- import ProblemCard from './ProblemCard.svelte';
20
- import Sheet from './Sheet.svelte';
21
-
22
- let {
23
- screen,
24
- session,
25
- config,
26
- onclose,
27
- onposted,
28
- }: {
29
- screen: Screen;
30
- session: Session;
31
- config: ProcrastimateConfig;
32
- onclose: () => void;
33
- onposted: (items: FeedbackItem[], toast: Toast) => void;
34
- } = $props();
35
-
36
- // svelte-ignore state_referenced_locally
37
- const names = taskTitle(session.capture, session.items);
38
- let name = $state(names.placeholder);
39
- let all = $state(cachedProjects());
40
- const projects = $derived(listedProjects(all, config.projects).projects);
41
- // svelte-ignore state_referenced_locally
42
- let place = $state<Place>({ projectId: startingProject(projects, config, lastProject()) });
43
- let loading = $state(true);
44
- /** Whether the user chose a place, which a project list that finishes loading must not undo. */
45
- let chosen = false;
46
- let loadProblem = $state<Problem>();
47
- let postProblem = $state<Problem>();
48
- /** What the post is doing, while it runs. */
49
- let step = $state<string>();
50
- const posting = $derived(step !== undefined);
51
- /** Without a project, a post would land in the Inbox, which Feedback never posts to. */
52
- const unresolved = $derived(!place.projectId);
53
- let status = $state<HTMLElement>();
54
- // svelte-ignore state_referenced_locally
55
- const environment: Fact[] = session.capture.environment.map(entry => ({ label: entry.name, value: entry.value }));
56
-
57
- $effect(() => {
58
- loadProjects(config)
59
- .then(loaded => {
60
- all = loaded;
61
- const listed = listedProjects(loaded, config.projects);
62
- if (!chosen) place = { projectId: startingProject(listed.projects, config, lastProject()) };
63
- const project = listed.projects.find(candidate => candidate.id === place.projectId);
64
- if (!project) place = { projectId: listed.projects[0]?.id };
65
- else if (!project.sections.some(section => section.id === place.sectionId)) place = { projectId: project.id };
66
- const missing = [...listed.missing];
67
- if (config.project && !startingProject(listed.projects, config, undefined)) missing.push(config.project);
68
- if (missing.length) {
69
- const names = [...new Set(missing)].map(name => `"${name}"`).join(', ');
70
- throw new Error(`ProcrastiMate has no project named ${names} among the projects Feedback may post to`);
71
- }
72
- })
73
- .catch(
74
- (error: unknown) =>
75
- (loadProblem = Problem.from(error).with([{ label: 'Step', value: 'Loading the projects' }], environment)),
76
- )
77
- .finally(() => (loading = false));
78
- });
79
-
80
- async function post() {
81
- step = 'Drawing the image';
82
- postProblem = undefined;
83
- const started = performance.now();
84
- const items = [...session.items];
85
- const project = projects.find(candidate => candidate.id === place.projectId);
86
- const section = project?.sections.find(candidate => candidate.id === place.sectionId);
87
- const report = session.compactJSON;
88
- const facts: Fact[] = [
89
- {
90
- label: 'Place',
91
- value: [project && `${project.name} (${project.id})`, section && `${section.name} (${section.id})`]
92
- .filter(Boolean)
93
- .join(' / '),
94
- },
95
- { label: 'Report', value: `${new TextEncoder().encode(report).length} bytes` },
96
- { label: 'Server', value: config.url ?? '' },
97
- ];
98
- try {
99
- const image = annotatedImage(screen, session.annotations);
100
- facts.push({ label: 'Image', value: `${image.width} × ${image.height} px` });
101
- const id = await postTask(config, name.trim(), place, image, report, text => (step = text));
102
- const destination = [project?.name, section?.name].filter(Boolean).join(' / ');
103
- onposted(items, { text: `Added to ${destination} in ProcrastiMate`, link: taskLink(config, id) });
104
- } catch (error) {
105
- const elapsed = { label: 'Elapsed', value: `${((performance.now() - started) / 1000).toFixed(1)} s` };
106
- postProblem = Problem.from(error).with(
107
- [{ label: 'Step', value: step ?? 'Posting' }, elapsed],
108
- [...facts, ...environment],
109
- );
110
- step = undefined;
111
- }
112
- }
113
-
114
- // Above the project list, which can be longer than the sheet: an error under it goes unseen.
115
- $effect(() => {
116
- if (postProblem || step) status?.scrollIntoView({ block: 'nearest' });
117
- });
118
- </script>
119
-
120
- {#snippet row(label: string, picked: boolean, indented: boolean, pick: () => void, link?: string)}
121
- <div class="row" class:indented>
122
- <button
123
- type="button"
124
- role="option"
125
- aria-selected={picked}
126
- disabled={posting}
127
- onclick={() => {
128
- chosen = true;
129
- pick();
130
- }}
131
- >
132
- <span>{label}</span>
133
- {#if picked}<span class="check" aria-hidden="true">✓</span>{/if}
134
- </button>
135
- {#if link}
136
- <a
137
- class="open"
138
- href={link}
139
- target="_blank"
140
- rel="noopener"
141
- aria-label="Open {label} in ProcrastiMate"
142
- title="Open in ProcrastiMate">↗</a
143
- >
144
- {/if}
145
- </div>
146
- {/snippet}
147
-
148
- <Sheet label="Add to ProcrastiMate" onsubmit={() => void post()}>
149
- {#snippet header()}
150
- <button type="button" class="link" disabled={posting} onclick={onclose}>Cancel</button>
151
- <h2>Add to ProcrastiMate</h2>
152
- <button type="submit" class="link strong" disabled={posting || unresolved || !name.trim()}
153
- >{posting ? 'Adding…' : 'Add'}</button
154
- >
155
- {/snippet}
156
-
157
- <div class="status" bind:this={status}>
158
- {#if step}<p class="step" role="status">{step}…</p>{/if}
159
- {#if postProblem}<ProblemCard problem={postProblem} />{/if}
160
- {#if loadProblem}<ProblemCard problem={loadProblem} />{/if}
161
- </div>
162
- <label>
163
- <span class="caption">Name</span>
164
- <input bind:value={name} aria-label="Task name" disabled={posting} />
165
- </label>
166
- <span class="caption">Project{loading ? ' · loading…' : ''}</span>
167
- <div class="list" role="listbox" aria-label="Project">
168
- {#each projects as project (project.id)}
169
- {@const open = project.id === place.projectId && project.sections.length > 0}
170
- {@render row(
171
- project.name,
172
- project.id === place.projectId && !open,
173
- false,
174
- () => (place = { projectId: project.id }),
175
- projectLink(config, project.id),
176
- )}
177
- {#if open}
178
- {@render row('No section', !place.sectionId, true, () => (place = { projectId: project.id }))}
179
- {#each project.sections as section (section.id)}
180
- {@render row(
181
- section.name,
182
- place.sectionId === section.id,
183
- true,
184
- () => (place = { projectId: project.id, sectionId: section.id }),
185
- )}
186
- {/each}
187
- {/if}
188
- {/each}
189
- </div>
190
- </Sheet>
191
-
192
- <style>
193
- .strong {
194
- font-weight: 600;
195
- }
196
-
197
- .list {
198
- display: grid;
199
- border-radius: 10px;
200
- background: #2c2c2e;
201
- overflow: hidden;
202
- }
203
-
204
- .row {
205
- display: flex;
206
- border-bottom: 1px solid rgb(255 255 255 / 0.08);
207
- }
208
-
209
- .row > button {
210
- display: flex;
211
- flex: 1;
212
- justify-content: space-between;
213
- gap: 8px;
214
- padding: 11px 12px;
215
- text-align: left;
216
- }
217
-
218
- .row.indented > button {
219
- padding-left: 40px;
220
- }
221
-
222
- .open {
223
- display: grid;
224
- place-items: center;
225
- width: 44px;
226
- border-left: 1px solid rgb(255 255 255 / 0.08);
227
- color: #0a84ff;
228
- text-decoration: none;
229
- }
230
-
231
- .check {
232
- color: #0a84ff;
233
- font-weight: 700;
234
- }
235
-
236
- .status {
237
- display: grid;
238
- gap: 8px;
239
- }
240
-
241
- .status:empty {
242
- display: none;
243
- }
244
-
245
- .step {
246
- margin: 0;
247
- color: #aeaeb2;
248
- }
249
- </style>
@@ -1,11 +0,0 @@
1
- export { feedbackProcrastimate } from './index.js';
2
-
3
- type Project = { id: string; name: string };
4
- type View = { projects: Project[]; sections: { id: string; projectId: string }[] };
5
-
6
- export function allowedProjectIds(projects: Project[], names: string[]): Set<string>;
7
- export function refusal(
8
- call: { method: string; route: string; query: URLSearchParams; body: string },
9
- state: { allowed?: Set<string>; created: Set<string> },
10
- ): string | undefined;
11
- export function allowedView(view: View, allowed: Set<string>): View;
@@ -1,187 +0,0 @@
1
- /** What `setupFeedbackEngine()` reads. `editor/setup.ts` spells the same names. */
2
- const pathDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE';
3
- const projectDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE_PROJECT';
4
- const projectsDefine = 'import.meta.env.FEEDBACK_PROCRASTIMATE_PROJECTS';
5
-
6
- /**
7
- * @typedef {{ id: string, name: string }} Project
8
- * @typedef {{ projects: Project[], sections: { id: string, projectId: string }[] }} View
9
- */
10
-
11
- /**
12
- * The ids of the projects `names` lists, each by id or by name ignoring case, as the picker matches them.
13
- *
14
- * @param {Project[]} projects
15
- * @param {string[]} names
16
- */
17
- export function allowedProjectIds(projects, names) {
18
- /** @type {Set<string>} */
19
- const ids = new Set();
20
- for (const name of names) {
21
- const project =
22
- projects.find(candidate => candidate.id === name) ??
23
- projects.find(candidate => candidate.name.toLowerCase() === name.toLowerCase());
24
- if (project) ids.add(project.id);
25
- }
26
- return ids;
27
- }
28
-
29
- /**
30
- * Why the proxy refuses a call, or `undefined` to forward it. The token can do anything in the space, so the proxy
31
- * forwards only the calls a post makes: listing the projects, uploading its files, creating a task in an allowed
32
- * project, and attaching the files to, or deleting, a task this proxy created.
33
- *
34
- * @param {{ method: string, route: string, query: URLSearchParams, body: string }} call
35
- * @param {{ allowed?: Set<string>, created: Set<string> }} state `allowed` is needed only to create a task.
36
- */
37
- export function refusal({ method, route, query, body }, { allowed, created }) {
38
- const key = `${method} ${route}`;
39
- if (key === 'GET api/view' || key === 'PUT api/images') return;
40
- if (key === 'POST api/tasks') {
41
- /** @type {{ projectId?: string | null }} */
42
- let task;
43
- try {
44
- task = JSON.parse(body);
45
- } catch {
46
- return 'the task is not JSON';
47
- }
48
- if (!task.projectId || !allowed?.has(task.projectId))
49
- return 'Feedback posts only to the projects feedbackProcrastimate({ projects }) lists';
50
- return;
51
- }
52
- if (key === 'PATCH api/tasks' || key === 'DELETE api/tasks') {
53
- const id = query.get('id');
54
- if (!id || !created.has(id)) return 'Feedback changes only the tasks it created';
55
- if (method === 'PATCH') {
56
- try {
57
- if (Object.keys(JSON.parse(body)).some(field => field !== 'attachments'))
58
- return 'Feedback only attaches files to a task it created';
59
- } catch {
60
- return 'the change is not JSON';
61
- }
62
- }
63
- return;
64
- }
65
- return `Feedback does not forward ${method} /${route}`;
66
- }
67
-
68
- /**
69
- * The view with only the allowed projects and their sections, which is all the picker reads.
70
- *
71
- * @param {View} view
72
- * @param {Set<string>} allowed
73
- */
74
- export const allowedView = (view, allowed) => ({
75
- projects: view.projects.filter(project => allowed.has(project.id)),
76
- sections: view.sections.filter(section => allowed.has(section.projectId)),
77
- });
78
-
79
- /**
80
- * A Vite plugin that lets the page post to ProcrastiMate. A browser on another origin cannot call ProcrastiMate, and a
81
- * token in the page would be public, so the dev and preview servers forward `path` to ProcrastiMate and add the
82
- * token there.
83
- *
84
- * The token is the switch. With one, the plugin tells the page where the proxy is, and the Share menu lists
85
- * ProcrastiMate. Without one the page is told nothing, so the entry is not there. A page that names the path itself
86
- * then gets a 501 that says why.
87
- *
88
- * @param {{ url?: string, token?: string, path?: string, project?: string, projects: string[] }} options
89
- */
90
- export function feedbackProcrastimate(options) {
91
- if (!options?.projects?.length)
92
- throw new Error(
93
- 'feedbackProcrastimate({ projects }) needs the ProcrastiMate projects Feedback may post to, by name or id.',
94
- );
95
- const { projects } = options;
96
- const path = options.path ?? '/__feedback/procrastimate';
97
- const target = (options.url ?? 'https://procrastimate.stf.lol').replace(/\/$/, '');
98
- /** @type {Set<string>} */
99
- const created = new Set();
100
-
101
- /** @param {string} route @param {RequestInit} [init] */
102
- const upstream = (route, init = {}) =>
103
- fetch(`${target}/${route}`, {
104
- ...init,
105
- headers: { Authorization: `Bearer ${options.token}`, 'User-Agent': 'Feedback', ...init.headers },
106
- });
107
-
108
- /** @type {import('vite').Connect.NextHandleFunction} */
109
- const handler = (request, response, next) => {
110
- if (!request.url?.startsWith(`${path}/`)) return next();
111
- const reply = (/** @type {number} */ status, /** @type {string} */ message) => {
112
- response.statusCode = status;
113
- response.setHeader('Content-Type', 'application/json');
114
- response.end(JSON.stringify({ message }));
115
- };
116
- if (!options.token)
117
- return reply(501, 'the dev server has no ProcrastiMate token. Pass one to feedbackProcrastimate().');
118
- const forward = async () => {
119
- const chunks = [];
120
- for await (const chunk of request) chunks.push(chunk);
121
- const body = Buffer.concat(chunks);
122
- const method = request.method ?? 'GET';
123
- const relative = /** @type {string} */ (request.url).slice(path.length + 1);
124
- const url = new URL(relative, 'http://proxy/');
125
- const route = url.pathname.slice(1);
126
- const send = async (/** @type {Response} */ answer, /** @type {Buffer} */ bytes) => {
127
- response.statusCode = answer.status;
128
- response.setHeader('Content-Type', answer.headers.get('content-type') ?? 'application/json');
129
- response.end(bytes);
130
- };
131
- const view = async () => {
132
- const answer = await upstream('api/view');
133
- if (!answer.ok) return { answer };
134
- const data = /** @type {View} */ (await answer.json());
135
- return { answer, data, allowed: allowedProjectIds(data.projects, projects) };
136
- };
137
-
138
- if (method === 'GET' && route === 'api/view') {
139
- const { answer, data, allowed } = await view();
140
- if (!data) return send(answer, Buffer.from(await answer.arrayBuffer()));
141
- response.setHeader('Content-Type', 'application/json');
142
- return response.end(JSON.stringify(allowedView(data, allowed)));
143
- }
144
- const creates = method === 'POST' && route === 'api/tasks';
145
- let allowed;
146
- if (creates) {
147
- const listed = await view();
148
- if (!listed.data) return send(listed.answer, Buffer.from(await listed.answer.arrayBuffer()));
149
- allowed = listed.allowed;
150
- }
151
- const why = refusal({ method, route, query: url.searchParams, body: body.toString() }, { allowed, created });
152
- if (why) return reply(403, why);
153
- const answer = await upstream(relative, {
154
- method,
155
- headers: request.headers['content-type'] ? { 'Content-Type': request.headers['content-type'] } : {},
156
- body: body.length ? body : undefined,
157
- });
158
- const bytes = Buffer.from(await answer.arrayBuffer());
159
- if (answer.ok && creates) created.add(/** @type {{ id: string }} */ (JSON.parse(bytes.toString())).id);
160
- if (answer.ok && method === 'DELETE') created.delete(url.searchParams.get('id') ?? '');
161
- send(answer, bytes);
162
- };
163
- forward().catch(error =>
164
- reply(502, `the dev server could not reach ${target}: ${/** @type {Error} */ (error).message}`),
165
- );
166
- };
167
- return {
168
- name: 'feedback-engine-procrastimate',
169
- config() {
170
- return {
171
- define: {
172
- [pathDefine]: JSON.stringify(options.token ? path : ''),
173
- [projectDefine]: JSON.stringify(options.project ?? ''),
174
- [projectsDefine]: JSON.stringify(JSON.stringify(projects)),
175
- },
176
- };
177
- },
178
- /** @param {import('vite').ViteDevServer} server */
179
- configureServer(server) {
180
- server.middlewares.use(handler);
181
- },
182
- /** @param {import('vite').PreviewServer} server */
183
- configurePreviewServer(server) {
184
- server.middlewares.use(handler);
185
- },
186
- };
187
- }